HttpWebRequestTest.cs 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540
  1. //
  2. // HttpWebRequestTest.cs - NUnit Test Cases for System.Net.HttpWebRequest
  3. //
  4. // Authors:
  5. // Lawrence Pit ([email protected])
  6. // Martin Willemoes Hansen ([email protected])
  7. // Gonzalo Paniagua Javier ([email protected])
  8. // Andres G. Aragoneses ([email protected])
  9. // Bogdanov Kirill ([email protected])
  10. //
  11. // (C) 2003 Martin Willemoes Hansen
  12. // Copyright (c) 2005 Novell, Inc. (http://www.novell.com
  13. // Copyright (c) 2013 7digital Media Ltd (http://www.7digital.com)
  14. //
  15. using NUnit.Framework;
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Specialized;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Net;
  22. using System.Net.Sockets;
  23. using System.Security.Cryptography;
  24. using System.Security.Cryptography.X509Certificates;
  25. using System.Text;
  26. using System.Threading;
  27. using System.Reflection;
  28. using Mono.Security.Authenticode;
  29. #if !MOBILE && !MONOMAC
  30. using Mono.Security.Protocol.Tls;
  31. #endif
  32. using MonoTests.Helpers;
  33. namespace MonoTests.System.Net
  34. {
  35. [TestFixture]
  36. public class HttpWebRequestTest
  37. {
  38. private Random rand = new Random ();
  39. private byte [] data64KB = new byte [64 * 1024];
  40. [TestFixtureSetUp]
  41. public void Setup ()
  42. {
  43. #if !FEATURE_NO_BSD_SOCKETS
  44. ServicePointManager.Expect100Continue = false;
  45. #endif
  46. rand.NextBytes (data64KB);
  47. }
  48. [Test]
  49. #if FEATURE_NO_BSD_SOCKETS
  50. [ExpectedException (typeof (PlatformNotSupportedException))]
  51. #endif
  52. public void Proxy_Null ()
  53. {
  54. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
  55. Assert.IsNotNull (req.Proxy, "#1");
  56. req.Proxy = null;
  57. Assert.IsNull (req.Proxy, "#2");
  58. }
  59. [Test]
  60. [Category("InetAccess")]
  61. #if FEATURE_NO_BSD_SOCKETS
  62. [ExpectedException (typeof (PlatformNotSupportedException))]
  63. #endif
  64. public void Sync ()
  65. {
  66. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
  67. Assert.IsNotNull (req.IfModifiedSince, "req:If Modified Since: ");
  68. req.UserAgent = "MonoClient v1.0";
  69. Assert.AreEqual ("User-Agent", req.Headers.GetKey (0), "#A1");
  70. Assert.AreEqual ("MonoClient v1.0", req.Headers.Get (0), "#A2");
  71. HttpWebResponse res = (HttpWebResponse) req.GetResponse ();
  72. Assert.AreEqual ("OK", res.StatusCode.ToString (), "#B1");
  73. Assert.AreEqual ("OK", res.StatusDescription, "#B2");
  74. Assert.IsTrue (res.Headers.Get ("Content-Type").StartsWith ("text/html; charset=", StringComparison.OrdinalIgnoreCase), "#C1");
  75. Assert.IsNotNull (res.LastModified, "#C2");
  76. Assert.AreEqual (0, res.Cookies.Count, "#C3");
  77. res.Close ();
  78. }
  79. [Test]
  80. #if FEATURE_NO_BSD_SOCKETS
  81. [ExpectedException (typeof (PlatformNotSupportedException))]
  82. #endif
  83. public void AddRange ()
  84. {
  85. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
  86. req.AddRange (10);
  87. req.AddRange (50, 90);
  88. req.AddRange ("bytes", 100);
  89. req.AddRange ("bytes", 100, 120);
  90. Assert.AreEqual ("bytes=10-,50-90,100-,100-120", req.Headers ["Range"], "#1");
  91. try {
  92. req.AddRange ("bits", 2000);
  93. Assert.Fail ("#2");
  94. } catch (InvalidOperationException) {}
  95. }
  96. [Test] // bug #471782
  97. #if FEATURE_NO_BSD_SOCKETS
  98. [ExpectedException (typeof (PlatformNotSupportedException))]
  99. #endif
  100. public void CloseRequestStreamAfterReadingResponse ()
  101. {
  102. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  103. string url = "http://" + ep.ToString () + "/test/";
  104. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  105. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  106. req.Method = "POST";
  107. req.Timeout = 2000;
  108. req.ReadWriteTimeout = 2000;
  109. byte [] data = new byte [128];
  110. req.ContentLength = data.Length;
  111. Stream rs = req.GetRequestStream ();
  112. rs.Write (data, 0, data.Length);
  113. rs.Flush ();
  114. HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
  115. response.Close ();
  116. rs.Close ();
  117. }
  118. }
  119. [Test]
  120. [Category("InetAccess")]
  121. [Category ("NotWorking")] // Disabled until a server that meets requirements is found
  122. public void Cookies1 ()
  123. {
  124. // The purpose of this test is to ensure that the cookies we get from a request
  125. // are stored in both, the CookieCollection in HttpWebResponse and the CookieContainer
  126. // in HttpWebRequest.
  127. // If this URL stops sending *one* and only one cookie, replace it.
  128. string url = "http://xamarin.com";
  129. CookieContainer cookies = new CookieContainer ();
  130. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  131. req.KeepAlive = false;
  132. req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv; 1.7.6) Gecko/20050317 Firefox/1.0.2";
  133. req.CookieContainer = cookies;
  134. Assert.AreEqual (0, cookies.Count, "#01");
  135. using (HttpWebResponse res = (HttpWebResponse) req.GetResponse()) {
  136. CookieCollection coll = req.CookieContainer.GetCookies (new Uri (url));
  137. Assert.AreEqual (1, coll.Count, "#02");
  138. Assert.AreEqual (1, res.Cookies.Count, "#03");
  139. Cookie one = coll [0];
  140. Cookie two = res.Cookies [0];
  141. Assert.AreEqual (true, object.ReferenceEquals (one, two), "#04");
  142. }
  143. }
  144. #if !MOBILE && !MONOMAC
  145. [Test]
  146. [Ignore ("Fails on MS.NET")]
  147. public void SslClientBlock ()
  148. {
  149. // This tests that the write request/initread/write body sequence does not hang
  150. // when using SSL.
  151. // If there's a regression for this, the test will hang.
  152. ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
  153. try {
  154. SslHttpServer server = new SslHttpServer ();
  155. server.Start ();
  156. string url = String.Format ("https://{0}:{1}/nothing.html", server.IPAddress, server.Port);
  157. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  158. request.Method = "POST";
  159. Stream stream = request.GetRequestStream ();
  160. byte [] bytes = new byte [100];
  161. stream.Write (bytes, 0, bytes.Length);
  162. stream.Close ();
  163. HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
  164. Assert.AreEqual (200, (int) resp.StatusCode, "StatusCode");
  165. StreamReader sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
  166. sr.ReadToEnd ();
  167. sr.Close ();
  168. resp.Close ();
  169. server.Stop ();
  170. if (server.Error != null)
  171. throw server.Error;
  172. } finally {
  173. ServicePointManager.CertificatePolicy = null;
  174. }
  175. }
  176. #endif
  177. [Test]
  178. #if FEATURE_NO_BSD_SOCKETS
  179. [ExpectedException (typeof (PlatformNotSupportedException))]
  180. #endif
  181. public void Missing_ContentEncoding ()
  182. {
  183. ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
  184. try {
  185. BadChunkedServer server = new BadChunkedServer ();
  186. server.Start ();
  187. string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
  188. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  189. request.Method = "GET";
  190. HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
  191. Assert.AreEqual ("", resp.ContentEncoding);
  192. resp.Close ();
  193. server.Stop ();
  194. if (server.Error != null)
  195. throw server.Error;
  196. } finally {
  197. ServicePointManager.CertificatePolicy = null;
  198. }
  199. }
  200. [Test]
  201. #if FEATURE_NO_BSD_SOCKETS
  202. [ExpectedException (typeof (PlatformNotSupportedException))]
  203. #endif
  204. public void BadServer_ChunkedClose ()
  205. {
  206. // The server will send a chunked response without a 'last-chunked' mark
  207. // and then shutdown the socket for sending.
  208. BadChunkedServer server = new BadChunkedServer ();
  209. server.Start ();
  210. string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
  211. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  212. HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
  213. string x = null;
  214. try {
  215. byte [] bytes = new byte [32];
  216. // Using StreamReader+UTF8Encoding here fails on MS runtime
  217. Stream stream = resp.GetResponseStream ();
  218. int nread = stream.Read (bytes, 0, 32);
  219. Assert.AreEqual (16, nread, "#01");
  220. x = Encoding.ASCII.GetString (bytes, 0, 16);
  221. } finally {
  222. resp.Close ();
  223. server.Stop ();
  224. }
  225. if (server.Error != null)
  226. throw server.Error;
  227. Assert.AreEqual ("1234567890123456", x);
  228. }
  229. [Test]
  230. [Ignore ("This test asserts that our code violates RFC 2616")]
  231. public void MethodCase ()
  232. {
  233. ListDictionary methods = new ListDictionary ();
  234. methods.Add ("post", "POST");
  235. methods.Add ("puT", "PUT");
  236. methods.Add ("POST", "POST");
  237. methods.Add ("whatever", "whatever");
  238. methods.Add ("PUT", "PUT");
  239. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  240. string url = "http://" + ep.ToString () + "/test/";
  241. foreach (DictionaryEntry de in methods) {
  242. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  243. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  244. req.Method = (string) de.Key;
  245. req.Timeout = 2000;
  246. req.ReadWriteTimeout = 2000;
  247. req.KeepAlive = false;
  248. Stream rs = req.GetRequestStream ();
  249. rs.Close ();
  250. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  251. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  252. Encoding.UTF8);
  253. string line = sr.ReadLine ();
  254. sr.Close ();
  255. Assert.AreEqual (((string) de.Value) + " /test/ HTTP/1.1",
  256. line, req.Method);
  257. resp.Close ();
  258. }
  259. }
  260. }
  261. }
  262. [Test]
  263. #if FEATURE_NO_BSD_SOCKETS
  264. [ExpectedException (typeof (PlatformNotSupportedException))]
  265. #endif
  266. public void BeginGetRequestStream_Body_NotAllowed ()
  267. {
  268. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  269. string url = "http://" + ep.ToString () + "/test/";
  270. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  271. HttpWebRequest request;
  272. request = (HttpWebRequest) WebRequest.Create (url);
  273. request.Method = "GET";
  274. try {
  275. var result = request.BeginGetRequestStream (null, null);
  276. request.EndGetRequestStream (result);
  277. Assert.Fail ("#A1");
  278. } catch (ProtocolViolationException ex) {
  279. // Cannot send a content-body with this
  280. // verb-type
  281. Assert.IsNull (ex.InnerException, "#A2");
  282. Assert.IsNotNull (ex.Message, "#A3");
  283. }
  284. request = (HttpWebRequest) WebRequest.Create (url);
  285. request.Method = "HEAD";
  286. try {
  287. var res = request.BeginGetRequestStream (null, null);
  288. request.EndGetRequestStream (res);
  289. Assert.Fail ("#B1");
  290. } catch (ProtocolViolationException ex) {
  291. // Cannot send a content-body with this
  292. // verb-type
  293. Assert.IsNull (ex.InnerException, "#B2");
  294. Assert.IsNotNull (ex.Message, "#B3");
  295. }
  296. }
  297. }
  298. [Test] // bug #465613
  299. #if FEATURE_NO_BSD_SOCKETS
  300. [ExpectedException (typeof (PlatformNotSupportedException))]
  301. #endif
  302. public void BeginGetRequestStream_NoBuffering ()
  303. {
  304. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  305. string url = "http://" + ep.ToString () + "/test/";
  306. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  307. HttpWebRequest req;
  308. Stream rs;
  309. IAsyncResult ar;
  310. req = (HttpWebRequest) WebRequest.Create (url);
  311. req.Method = "POST";
  312. req.SendChunked = false;
  313. req.KeepAlive = false;
  314. req.AllowWriteStreamBuffering = false;
  315. ar = req.BeginGetRequestStream (null, null);
  316. rs = req.EndGetRequestStream (ar);
  317. rs.Close ();
  318. req = (HttpWebRequest) WebRequest.Create (url);
  319. req.Method = "POST";
  320. req.SendChunked = false;
  321. req.KeepAlive = true;
  322. req.AllowWriteStreamBuffering = false;
  323. try {
  324. var result = req.BeginGetRequestStream (null, null);
  325. req.EndGetRequestStream (result);
  326. Assert.Fail ("#A1");
  327. } catch (ProtocolViolationException ex) {
  328. // When performing a write operation with
  329. // AllowWriteStreamBuffering set to false,
  330. // you must either set ContentLength to a
  331. // non-negative number or set SendChunked
  332. // to true
  333. Assert.IsNull (ex.InnerException, "#A2");
  334. Assert.IsNotNull (ex.Message, "#A3");
  335. }
  336. req = (HttpWebRequest) WebRequest.Create (url);
  337. req.Method = "POST";
  338. req.SendChunked = false;
  339. req.KeepAlive = true;
  340. req.AllowWriteStreamBuffering = false;
  341. req.ContentLength = 0;
  342. ar = req.BeginGetRequestStream (null, null);
  343. rs = req.EndGetRequestStream (ar);
  344. rs.Close ();
  345. }
  346. }
  347. [Test] // bug #508027
  348. [Category ("NotWorking")] // #5842
  349. public void BeginGetResponse ()
  350. {
  351. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  352. string url = "http://" + ep.ToString () + "/test/";
  353. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  354. HttpWebRequest req;
  355. req = (HttpWebRequest) WebRequest.Create (url);
  356. req.Timeout = 5000;
  357. req.Method = "POST";
  358. req.SendChunked = false;
  359. req.KeepAlive = false;
  360. req.AllowWriteStreamBuffering = false;
  361. req.BeginGetResponse (null, null);
  362. req.Abort ();
  363. req = (HttpWebRequest) WebRequest.Create (url);
  364. req.Timeout = 5000;
  365. req.Method = "POST";
  366. req.SendChunked = true;
  367. req.KeepAlive = false;
  368. req.AllowWriteStreamBuffering = false;
  369. req.GetRequestStream ().WriteByte (1);
  370. req.BeginGetResponse (null, null);
  371. req.Abort ();
  372. req = (HttpWebRequest) WebRequest.Create (url);
  373. req.Timeout = 5000;
  374. req.Method = "POST";
  375. req.ContentLength = 5;
  376. req.SendChunked = false;
  377. req.KeepAlive = false;
  378. req.AllowWriteStreamBuffering = false;
  379. req.GetRequestStream ().WriteByte (5);
  380. req.BeginGetResponse (null, null);
  381. req.Abort ();
  382. req = (HttpWebRequest) WebRequest.Create (url);
  383. req.Timeout = 5000;
  384. req.Method = "POST";
  385. req.SendChunked = false;
  386. req.KeepAlive = true;
  387. req.AllowWriteStreamBuffering = false;
  388. req.BeginGetResponse (null, null);
  389. req.Abort ();
  390. req = (HttpWebRequest) WebRequest.Create (url);
  391. req.Timeout = 5000;
  392. req.Method = "POST";
  393. req.SendChunked = false;
  394. req.KeepAlive = false;
  395. req.AllowWriteStreamBuffering = false;
  396. req.ContentLength = 5;
  397. req.BeginGetResponse (null, null);
  398. req.Abort ();
  399. req = (HttpWebRequest) WebRequest.Create (url);
  400. req.Timeout = 5000;
  401. req.Method = "POST";
  402. req.SendChunked = false;
  403. req.KeepAlive = true;
  404. req.AllowWriteStreamBuffering = false;
  405. req.ContentLength = 5;
  406. req.BeginGetResponse (null, null);
  407. req.Abort ();
  408. req = (HttpWebRequest) WebRequest.Create (url);
  409. req.Timeout = 5000;
  410. req.Method = "GET";
  411. req.SendChunked = true;
  412. req.BeginGetResponse (null, null);
  413. req.Abort ();
  414. req = (HttpWebRequest) WebRequest.Create (url);
  415. req.Timeout = 5000;
  416. req.Method = "GET";
  417. req.ContentLength = 5;
  418. req.BeginGetResponse (null, null);
  419. req.Abort ();
  420. req = (HttpWebRequest) WebRequest.Create (url);
  421. req.Timeout = 5000;
  422. req.Method = "GET";
  423. req.ContentLength = 0;
  424. req.BeginGetResponse (null, null);
  425. req.Abort ();
  426. }
  427. }
  428. [Test] // bug #511851
  429. #if FEATURE_NO_BSD_SOCKETS
  430. [ExpectedException (typeof (PlatformNotSupportedException))]
  431. #endif
  432. public void BeginGetRequestStream_Request_Aborted ()
  433. {
  434. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  435. string url = "http://" + ep.ToString () + "/test/";
  436. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  437. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  438. req.Method = "POST";
  439. req.Abort ();
  440. try {
  441. req.BeginGetRequestStream (null, null);
  442. Assert.Fail ("#1");
  443. } catch (WebException ex) {
  444. // The request was aborted: The request was canceled
  445. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  446. Assert.IsNull (ex.InnerException, "#3");
  447. Assert.IsNotNull (ex.Message, "#4");
  448. Assert.IsNull (ex.Response, "#5");
  449. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  450. }
  451. }
  452. }
  453. [Test] // bug #511851
  454. #if FEATURE_NO_BSD_SOCKETS
  455. [ExpectedException (typeof (PlatformNotSupportedException))]
  456. #endif
  457. public void BeginGetResponse_Request_Aborted ()
  458. {
  459. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  460. string url = "http://" + ep.ToString () + "/test/";
  461. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  462. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  463. req.Method = "POST";
  464. req.Abort ();
  465. try {
  466. req.BeginGetResponse (null, null);
  467. Assert.Fail ("#1");
  468. } catch (WebException ex) {
  469. // The request was aborted: The request was canceled
  470. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  471. Assert.IsNull (ex.InnerException, "#3");
  472. Assert.IsNotNull (ex.Message, "#4");
  473. Assert.IsNull (ex.Response, "#5");
  474. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  475. }
  476. }
  477. }
  478. [Test]
  479. #if FEATURE_NO_BSD_SOCKETS
  480. [ExpectedException (typeof (PlatformNotSupportedException))]
  481. #endif
  482. public void EndGetRequestStream_AsyncResult_Null ()
  483. {
  484. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  485. string url = "http://" + ep.ToString () + "/test/";
  486. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  487. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  488. req.Method = "POST";
  489. req.BeginGetRequestStream (null, null);
  490. try {
  491. req.EndGetRequestStream (null);
  492. Assert.Fail ("#1");
  493. } catch (ArgumentNullException ex) {
  494. Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
  495. Assert.IsNull (ex.InnerException, "#3");
  496. Assert.IsNotNull (ex.Message, "#4");
  497. Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
  498. } finally {
  499. req.Abort ();
  500. }
  501. }
  502. }
  503. [Test]
  504. [Category ("NotWorking")] // do not get consistent result on MS
  505. public void EndGetRequestStream_Request_Aborted ()
  506. {
  507. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  508. string url = "http://" + ep.ToString () + "/test/";
  509. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  510. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  511. req.Method = "POST";
  512. IAsyncResult ar = req.BeginGetRequestStream (null, null);
  513. req.Abort ();
  514. Thread.Sleep (500);
  515. try {
  516. req.EndGetRequestStream (ar);
  517. Assert.Fail ("#1");
  518. } catch (WebException ex) {
  519. // The request was aborted: The request was canceled
  520. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  521. Assert.IsNull (ex.InnerException, "#3");
  522. Assert.IsNotNull (ex.Message, "#4");
  523. Assert.IsNull (ex.Response, "#5");
  524. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  525. }
  526. }
  527. }
  528. [Test] // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=471522
  529. [Category ("NotWorking")]
  530. public void EndGetResponse_AsyncResult_Invalid ()
  531. {
  532. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  533. string url = "http://" + ep.ToString () + "/test/";
  534. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  535. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  536. req.Method = "POST";
  537. req.Timeout = 2000;
  538. req.ReadWriteTimeout = 2000;
  539. IAsyncResult ar = req.BeginGetRequestStream (null, null);
  540. // AsyncResult was not returned from call to BeginGetResponse
  541. try {
  542. req.EndGetResponse (ar);
  543. Assert.Fail ();
  544. } catch (InvalidCastException) {
  545. } finally {
  546. req.Abort ();
  547. }
  548. }
  549. }
  550. [Test]
  551. #if FEATURE_NO_BSD_SOCKETS
  552. [ExpectedException (typeof (PlatformNotSupportedException))]
  553. #endif
  554. public void EndGetResponse_AsyncResult_Null ()
  555. {
  556. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  557. string url = "http://" + ep.ToString () + "/test/";
  558. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  559. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  560. req.Timeout = 2000;
  561. req.ReadWriteTimeout = 2000;
  562. req.Method = "POST";
  563. IAsyncResult ar = req.BeginGetResponse (null, null);
  564. try {
  565. req.EndGetResponse (null);
  566. Assert.Fail ("#1");
  567. } catch (ArgumentNullException ex) {
  568. Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
  569. Assert.IsNull (ex.InnerException, "#3");
  570. Assert.IsNotNull (ex.Message, "#4");
  571. Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
  572. } finally {
  573. req.Abort ();
  574. /*
  575. using (HttpWebResponse resp = (HttpWebResponse) req.EndGetResponse (ar)) {
  576. resp.Close ();
  577. }*/
  578. }
  579. }
  580. }
  581. [Test] // bug #429200
  582. #if FEATURE_NO_BSD_SOCKETS
  583. [ExpectedException (typeof (PlatformNotSupportedException))]
  584. #endif
  585. public void GetRequestStream ()
  586. {
  587. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  588. string url = "http://" + ep.ToString () + "/test/";
  589. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  590. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  591. req.Method = "POST";
  592. req.Timeout = 2000;
  593. req.ReadWriteTimeout = 2000;
  594. Stream rs1 = req.GetRequestStream ();
  595. Stream rs2 = req.GetRequestStream ();
  596. Assert.IsNotNull (rs1, "#1");
  597. Assert.AreSame (rs1, rs2, "#2");
  598. rs1.Close ();
  599. }
  600. }
  601. [Test] // bug #511851
  602. #if FEATURE_NO_BSD_SOCKETS
  603. [ExpectedException (typeof (PlatformNotSupportedException))]
  604. #endif
  605. public void GetRequestStream_Request_Aborted ()
  606. {
  607. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  608. string url = "http://" + ep.ToString () + "/test/";
  609. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  610. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  611. req.Method = "POST";
  612. req.Abort ();
  613. try {
  614. req.GetRequestStream ();
  615. Assert.Fail ("#1");
  616. } catch (WebException ex) {
  617. // The request was aborted: The request was canceled
  618. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  619. Assert.IsNull (ex.InnerException, "#3");
  620. Assert.IsNotNull (ex.Message, "#4");
  621. Assert.IsNull (ex.Response, "#5");
  622. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  623. }
  624. }
  625. }
  626. [Test] // bug #510661
  627. [Category ("NotWorking")] // #5842
  628. public void GetRequestStream_Close_NotAllBytesWritten ()
  629. {
  630. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  631. string url = "http://" + ep.ToString () + "/test/";
  632. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  633. HttpWebRequest req;
  634. Stream rs;
  635. req = (HttpWebRequest) WebRequest.Create (url);
  636. req.Method = "POST";
  637. req.ContentLength = 2;
  638. rs = req.GetRequestStream ();
  639. try {
  640. rs.Close ();
  641. Assert.Fail ("#A1");
  642. } catch (WebException ex) {
  643. // The request was aborted: The request was canceled
  644. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  645. Assert.IsNotNull (ex.Message, "#A3");
  646. Assert.IsNull (ex.Response, "#A4");
  647. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#A5");
  648. // Cannot close stream until all bytes are written
  649. Exception inner = ex.InnerException;
  650. Assert.IsNotNull (inner, "#A6");
  651. Assert.AreEqual (typeof (IOException), inner.GetType (), "#A7");
  652. Assert.IsNull (inner.InnerException, "#A8");
  653. Assert.IsNotNull (inner.Message, "#A9");
  654. }
  655. req = (HttpWebRequest) WebRequest.Create (url);
  656. req.Method = "POST";
  657. req.ContentLength = 2;
  658. rs = req.GetRequestStream ();
  659. rs.WriteByte (0x0d);
  660. try {
  661. rs.Close ();
  662. Assert.Fail ("#B1");
  663. } catch (WebException ex) {
  664. // The request was aborted: The request was canceled
  665. Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
  666. Assert.IsNotNull (ex.Message, "#B3");
  667. Assert.IsNull (ex.Response, "#B4");
  668. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#B5");
  669. // Cannot close stream until all bytes are written
  670. Exception inner = ex.InnerException;
  671. Assert.IsNotNull (inner, "#B6");
  672. Assert.AreEqual (typeof (IOException), inner.GetType (), "#B7");
  673. Assert.IsNull (inner.InnerException, "#B8");
  674. Assert.IsNotNull (inner.Message, "#B9");
  675. }
  676. req = (HttpWebRequest) WebRequest.Create (url);
  677. req.Method = "POST";
  678. req.ContentLength = 2;
  679. rs = req.GetRequestStream ();
  680. rs.WriteByte (0x0d);
  681. rs.WriteByte (0x0d);
  682. rs.Close ();
  683. }
  684. }
  685. [Test] // bug #510642
  686. [Category ("NotWorking")] // #5842
  687. public void GetRequestStream_Write_Overflow ()
  688. {
  689. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  690. string url = "http://" + ep.ToString () + "/test/";
  691. // buffered, non-chunked
  692. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  693. HttpWebRequest req;
  694. Stream rs;
  695. byte [] buffer;
  696. req = (HttpWebRequest) WebRequest.Create (url);
  697. req.Method = "POST";
  698. req.Timeout = 1000;
  699. req.ReadWriteTimeout = 2000;
  700. req.ContentLength = 2;
  701. rs = req.GetRequestStream ();
  702. rs.WriteByte (0x2c);
  703. buffer = new byte [] { 0x2a, 0x1d };
  704. try {
  705. rs.Write (buffer, 0, buffer.Length);
  706. Assert.Fail ("#A1");
  707. } catch (ProtocolViolationException ex) {
  708. // Bytes to be written to the stream exceed
  709. // Content-Length bytes size specified
  710. Assert.IsNull (ex.InnerException, "#A2");
  711. Assert.IsNotNull (ex.Message, "#A3");
  712. } finally {
  713. req.Abort ();
  714. }
  715. req = (HttpWebRequest) WebRequest.Create (url);
  716. req.Method = "POST";
  717. req.Timeout = 1000;
  718. req.ReadWriteTimeout = 2000;
  719. req.ContentLength = 2;
  720. rs = req.GetRequestStream ();
  721. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  722. try {
  723. rs.Write (buffer, 0, buffer.Length);
  724. Assert.Fail ("#B1");
  725. } catch (ProtocolViolationException ex) {
  726. // Bytes to be written to the stream exceed
  727. // Content-Length bytes size specified
  728. Assert.IsNull (ex.InnerException, "#B2");
  729. Assert.IsNotNull (ex.Message, "#B3");
  730. } finally {
  731. req.Abort ();
  732. }
  733. }
  734. // buffered, chunked
  735. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  736. HttpWebRequest req;
  737. Stream rs;
  738. byte [] buffer;
  739. /*
  740. req = (HttpWebRequest) WebRequest.Create (url);
  741. req.Method = "POST";
  742. req.SendChunked = true;
  743. req.Timeout = 1000;
  744. req.ReadWriteTimeout = 2000;
  745. req.ContentLength = 2;
  746. rs = req.GetRequestStream ();
  747. rs.WriteByte (0x2c);
  748. buffer = new byte [] { 0x2a, 0x1d };
  749. rs.Write (buffer, 0, buffer.Length);
  750. req.Abort ();
  751. */
  752. req = (HttpWebRequest) WebRequest.Create (url);
  753. req.Method = "POST";
  754. req.SendChunked = true;
  755. req.Timeout = 1000;
  756. req.ReadWriteTimeout = 2000;
  757. req.ContentLength = 2;
  758. rs = req.GetRequestStream ();
  759. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  760. rs.Write (buffer, 0, buffer.Length);
  761. req.Abort ();
  762. }
  763. // non-buffered, non-chunked
  764. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  765. HttpWebRequest req;
  766. Stream rs;
  767. byte [] buffer;
  768. req = (HttpWebRequest) WebRequest.Create (url);
  769. req.AllowWriteStreamBuffering = false;
  770. req.Method = "POST";
  771. req.Timeout = 1000;
  772. req.ReadWriteTimeout = 2000;
  773. req.ContentLength = 2;
  774. rs = req.GetRequestStream ();
  775. rs.WriteByte (0x2c);
  776. buffer = new byte [] { 0x2a, 0x1d };
  777. try {
  778. rs.Write (buffer, 0, buffer.Length);
  779. Assert.Fail ("#C1");
  780. } catch (ProtocolViolationException ex) {
  781. // Bytes to be written to the stream exceed
  782. // Content-Length bytes size specified
  783. Assert.IsNull (ex.InnerException, "#C2");
  784. Assert.IsNotNull (ex.Message, "#3");
  785. } finally {
  786. req.Abort ();
  787. }
  788. req = (HttpWebRequest) WebRequest.Create (url);
  789. req.AllowWriteStreamBuffering = false;
  790. req.Method = "POST";
  791. req.Timeout = 1000;
  792. req.ReadWriteTimeout = 2000;
  793. req.ContentLength = 2;
  794. rs = req.GetRequestStream ();
  795. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  796. try {
  797. rs.Write (buffer, 0, buffer.Length);
  798. Assert.Fail ("#D1");
  799. } catch (ProtocolViolationException ex) {
  800. // Bytes to be written to the stream exceed
  801. // Content-Length bytes size specified
  802. Assert.IsNull (ex.InnerException, "#D2");
  803. Assert.IsNotNull (ex.Message, "#D3");
  804. } finally {
  805. req.Abort ();
  806. }
  807. }
  808. // non-buffered, chunked
  809. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  810. HttpWebRequest req;
  811. Stream rs;
  812. byte [] buffer;
  813. req = (HttpWebRequest) WebRequest.Create (url);
  814. req.AllowWriteStreamBuffering = false;
  815. req.Method = "POST";
  816. req.SendChunked = true;
  817. req.Timeout = 1000;
  818. req.ReadWriteTimeout = 2000;
  819. req.ContentLength = 2;
  820. rs = req.GetRequestStream ();
  821. rs.WriteByte (0x2c);
  822. buffer = new byte [] { 0x2a, 0x1d };
  823. rs.Write (buffer, 0, buffer.Length);
  824. req.Abort ();
  825. req = (HttpWebRequest) WebRequest.Create (url);
  826. req.AllowWriteStreamBuffering = false;
  827. req.Method = "POST";
  828. req.SendChunked = true;
  829. req.Timeout = 1000;
  830. req.ReadWriteTimeout = 2000;
  831. req.ContentLength = 2;
  832. rs = req.GetRequestStream ();
  833. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  834. rs.Write (buffer, 0, buffer.Length);
  835. req.Abort ();
  836. }
  837. }
  838. [Test]
  839. [Ignore ("This test asserts that our code violates RFC 2616")]
  840. public void GetRequestStream_Body_NotAllowed ()
  841. {
  842. string [] methods = new string [] { "GET", "HEAD", "CONNECT",
  843. "get", "HeAd", "ConNect" };
  844. foreach (string method in methods) {
  845. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (
  846. "http://localhost:8000");
  847. req.Method = method;
  848. try {
  849. req.GetRequestStream ();
  850. Assert.Fail ("#1:" + method);
  851. } catch (ProtocolViolationException ex) {
  852. Assert.AreEqual (typeof (ProtocolViolationException), ex.GetType (), "#2:" + method);
  853. Assert.IsNull (ex.InnerException, "#3:" + method);
  854. Assert.IsNotNull (ex.Message, "#4:" + method);
  855. }
  856. }
  857. }
  858. [Test] // bug #511851
  859. #if FEATURE_NO_BSD_SOCKETS
  860. [ExpectedException (typeof (PlatformNotSupportedException))]
  861. #endif
  862. public void GetResponse_Request_Aborted ()
  863. {
  864. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  865. string url = "http://" + ep.ToString () + "/test/";
  866. using (SocketResponder responder = new SocketResponder (ep, s => EchoRequestHandler (s))) {
  867. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  868. req.Method = "POST";
  869. req.Abort ();
  870. try {
  871. req.GetResponse ();
  872. Assert.Fail ("#1");
  873. } catch (WebException ex) {
  874. // The request was aborted: The request was canceled
  875. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  876. Assert.IsNull (ex.InnerException, "#3");
  877. Assert.IsNotNull (ex.Message, "#4");
  878. Assert.IsNull (ex.Response, "#5");
  879. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  880. }
  881. }
  882. }
  883. [Test]
  884. [Ignore ("This does not timeout any more. That's how MS works when reading small responses")]
  885. public void ReadTimeout ()
  886. {
  887. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  888. string url = "http://" + localEP.ToString () + "/original/";
  889. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  890. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  891. req.Method = "POST";
  892. req.AllowAutoRedirect = false;
  893. req.Timeout = 200;
  894. req.ReadWriteTimeout = 2000;
  895. req.KeepAlive = false;
  896. Stream rs = req.GetRequestStream ();
  897. rs.Close ();
  898. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  899. try {
  900. Stream s = resp.GetResponseStream ();
  901. s.ReadByte ();
  902. Assert.Fail ("#1");
  903. } catch (WebException ex) {
  904. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  905. Assert.IsNull (ex.InnerException, "#3");
  906. Assert.IsNull (ex.Response, "#4");
  907. Assert.AreEqual (WebExceptionStatus.Timeout, ex.Status, "#5");
  908. }
  909. }
  910. }
  911. }
  912. [Test] // bug #324300
  913. #if FEATURE_NO_BSD_SOCKETS
  914. [ExpectedException (typeof (PlatformNotSupportedException))]
  915. #endif
  916. public void AllowAutoRedirect ()
  917. {
  918. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  919. string url = "http://" + localEP.ToString () + "/original/";
  920. // allow autoredirect
  921. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  922. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  923. req.Method = "POST";
  924. req.Timeout = 2000;
  925. req.ReadWriteTimeout = 2000;
  926. req.KeepAlive = false;
  927. Stream rs = req.GetRequestStream ();
  928. rs.Close ();
  929. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  930. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  931. Encoding.UTF8);
  932. string body = sr.ReadToEnd ();
  933. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
  934. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  935. localEP.ToString () + "/moved/", "#A2");
  936. Assert.AreEqual ("GET", resp.Method, "#A3");
  937. Assert.AreEqual ("LOOKS OK", body, "#A4");
  938. }
  939. }
  940. // do not allow autoredirect
  941. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  942. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  943. req.Method = "POST";
  944. req.AllowAutoRedirect = false;
  945. req.Timeout = 1000;
  946. req.ReadWriteTimeout = 1000;
  947. req.KeepAlive = false;
  948. Stream rs = req.GetRequestStream ();
  949. rs.Close ();
  950. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  951. Assert.AreEqual (resp.StatusCode, HttpStatusCode.Found, "#B1");
  952. Assert.AreEqual (url, resp.ResponseUri.ToString (), "#B2");
  953. Assert.AreEqual ("POST", resp.Method, "#B3");
  954. }
  955. }
  956. }
  957. [Test]
  958. #if FEATURE_NO_BSD_SOCKETS
  959. [ExpectedException (typeof (PlatformNotSupportedException))]
  960. #endif
  961. public void PostAndRedirect_NoCL ()
  962. {
  963. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  964. string url = "http://" + localEP.ToString () + "/original/";
  965. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  966. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  967. req.Method = "POST";
  968. req.Timeout = 2000;
  969. req.ReadWriteTimeout = 2000;
  970. Stream rs = req.GetRequestStream ();
  971. rs.WriteByte (10);
  972. rs.Close ();
  973. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  974. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  975. Encoding.UTF8);
  976. string body = sr.ReadToEnd ();
  977. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
  978. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  979. localEP.ToString () + "/moved/", "#A2");
  980. Assert.AreEqual ("GET", resp.Method, "#A3");
  981. Assert.AreEqual ("LOOKS OK", body, "#A4");
  982. }
  983. }
  984. }
  985. [Test]
  986. #if FEATURE_NO_BSD_SOCKETS
  987. [ExpectedException (typeof (PlatformNotSupportedException))]
  988. #endif
  989. public void PostAndRedirect_CL ()
  990. {
  991. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  992. string url = "http://" + localEP.ToString () + "/original/";
  993. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  994. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  995. req.Method = "POST";
  996. req.Timeout = 2000;
  997. req.ReadWriteTimeout = 2000;
  998. req.ContentLength = 1;
  999. Stream rs = req.GetRequestStream ();
  1000. rs.WriteByte (10);
  1001. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  1002. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  1003. Encoding.UTF8);
  1004. string body = sr.ReadToEnd ();
  1005. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
  1006. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  1007. localEP.ToString () + "/moved/", "#A2");
  1008. Assert.AreEqual ("GET", resp.Method, "#A3");
  1009. Assert.AreEqual ("LOOKS OK", body, "#A4");
  1010. }
  1011. }
  1012. }
  1013. [Test]
  1014. #if FEATURE_NO_BSD_SOCKETS
  1015. [ExpectedException (typeof (PlatformNotSupportedException))]
  1016. #endif
  1017. public void PostAnd401 ()
  1018. {
  1019. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  1020. string url = "http://" + localEP.ToString () + "/original/";
  1021. using (SocketResponder responder = new SocketResponder (localEP, s => RedirectRequestHandler (s))) {
  1022. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1023. req.Method = "POST";
  1024. req.Timeout = 2000;
  1025. req.ReadWriteTimeout = 2000;
  1026. req.ContentLength = 1;
  1027. Stream rs = req.GetRequestStream ();
  1028. rs.WriteByte (10);
  1029. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  1030. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  1031. Encoding.UTF8);
  1032. string body = sr.ReadToEnd ();
  1033. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
  1034. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  1035. localEP.ToString () + "/moved/", "#A2");
  1036. Assert.AreEqual ("GET", resp.Method, "#A3");
  1037. Assert.AreEqual ("LOOKS OK", body, "#A4");
  1038. }
  1039. }
  1040. }
  1041. [Test] // bug #324347
  1042. [Category ("NotWorking")]
  1043. public void InternalServerError ()
  1044. {
  1045. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  1046. string url = "http://" + localEP.ToString () + "/original/";
  1047. // POST
  1048. using (SocketResponder responder = new SocketResponder (localEP, s => InternalErrorHandler (s))) {
  1049. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1050. req.Method = "POST";
  1051. req.Timeout = 2000;
  1052. req.ReadWriteTimeout = 2000;
  1053. req.KeepAlive = false;
  1054. Stream rs = req.GetRequestStream ();
  1055. rs.Close ();
  1056. try {
  1057. req.GetResponse ();
  1058. Assert.Fail ("#A1");
  1059. } catch (WebException ex) {
  1060. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  1061. Assert.IsNull (ex.InnerException, "#A3");
  1062. Assert.IsNotNull (ex.Message, "#A4");
  1063. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A5");
  1064. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  1065. Assert.IsNotNull (webResponse, "#A6");
  1066. Assert.AreEqual ("POST", webResponse.Method, "#A7");
  1067. webResponse.Close ();
  1068. }
  1069. }
  1070. // GET
  1071. using (SocketResponder responder = new SocketResponder (localEP, s => InternalErrorHandler (s))) {
  1072. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1073. req.Method = "GET";
  1074. req.Timeout = 2000;
  1075. req.ReadWriteTimeout = 2000;
  1076. req.KeepAlive = false;
  1077. try {
  1078. req.GetResponse ();
  1079. Assert.Fail ("#B1");
  1080. } catch (WebException ex) {
  1081. Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
  1082. Assert.IsNull (ex.InnerException, "#B3");
  1083. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
  1084. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  1085. Assert.IsNotNull (webResponse, "#B5");
  1086. Assert.AreEqual ("GET", webResponse.Method, "#B6");
  1087. webResponse.Close ();
  1088. }
  1089. }
  1090. }
  1091. [Test]
  1092. [Category ("NotWorking")] // #B3 fails; we get a SocketException: An existing connection was forcibly closed by the remote host
  1093. public void NoContentLength ()
  1094. {
  1095. IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
  1096. string url = "http://" + localEP.ToString () + "/original/";
  1097. // POST
  1098. using (SocketResponder responder = new SocketResponder (localEP, s => NoContentLengthHandler (s))) {
  1099. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1100. req.Method = "POST";
  1101. req.Timeout = 2000;
  1102. req.ReadWriteTimeout = 2000;
  1103. req.KeepAlive = false;
  1104. Stream rs = req.GetRequestStream ();
  1105. rs.Close ();
  1106. try {
  1107. req.GetResponse ();
  1108. Assert.Fail ("#A1");
  1109. } catch (WebException ex) {
  1110. // The underlying connection was closed:
  1111. // An unexpected error occurred on a
  1112. // receive
  1113. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  1114. Assert.IsNotNull (ex.InnerException, "#A3");
  1115. Assert.AreEqual (WebExceptionStatus.ReceiveFailure, ex.Status, "#A4");
  1116. Assert.AreEqual (typeof (IOException), ex.InnerException.GetType (), "#A5");
  1117. // Unable to read data from the transport connection:
  1118. // A connection attempt failed because the connected party
  1119. // did not properly respond after a period of time, or
  1120. // established connection failed because connected host has
  1121. // failed to respond
  1122. IOException ioe = (IOException) ex.InnerException;
  1123. Assert.IsNotNull (ioe.InnerException, "#A6");
  1124. Assert.IsNotNull (ioe.Message, "#A7");
  1125. Assert.AreEqual (typeof (SocketException), ioe.InnerException.GetType (), "#A8");
  1126. // An existing connection was forcibly
  1127. // closed by the remote host
  1128. SocketException soe = (SocketException) ioe.InnerException;
  1129. Assert.IsNull (soe.InnerException, "#A9");
  1130. Assert.IsNotNull (soe.Message, "#A10");
  1131. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  1132. Assert.IsNull (webResponse, "#A11");
  1133. }
  1134. }
  1135. // GET
  1136. using (SocketResponder responder = new SocketResponder (localEP, s => NoContentLengthHandler (s))) {
  1137. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1138. req.Method = "GET";
  1139. req.Timeout = 2000;
  1140. req.ReadWriteTimeout = 2000;
  1141. req.KeepAlive = false;
  1142. try {
  1143. req.GetResponse ();
  1144. Assert.Fail ("#B1");
  1145. } catch (WebException ex) {
  1146. // The remote server returned an error:
  1147. // (500) Internal Server Error
  1148. Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
  1149. Assert.IsNull (ex.InnerException, "#B3");
  1150. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
  1151. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  1152. Assert.IsNotNull (webResponse, "#B5");
  1153. Assert.AreEqual ("GET", webResponse.Method, "#B6");
  1154. webResponse.Close ();
  1155. }
  1156. }
  1157. }
  1158. [Test] // bug #513087
  1159. #if FEATURE_NO_BSD_SOCKETS
  1160. [ExpectedException (typeof (PlatformNotSupportedException))]
  1161. #endif
  1162. public void NonStandardVerb ()
  1163. {
  1164. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  1165. string url = "http://" + ep.ToString () + "/moved/";
  1166. using (SocketResponder responder = new SocketResponder (ep, s => VerbEchoHandler (s))) {
  1167. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1168. req.Method = "WhatEver";
  1169. req.KeepAlive = false;
  1170. req.Timeout = 20000;
  1171. req.ReadWriteTimeout = 20000;
  1172. Stream rs = req.GetRequestStream ();
  1173. rs.Close ();
  1174. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  1175. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  1176. Encoding.UTF8);
  1177. string body = sr.ReadToEnd ();
  1178. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#1");
  1179. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  1180. ep.ToString () + "/moved/", "#2");
  1181. Assert.AreEqual ("WhatEver", resp.Method, "#3");
  1182. Assert.AreEqual ("WhatEver", body, "#4");
  1183. }
  1184. }
  1185. }
  1186. [Test]
  1187. [Category ("NotWorking")] // Assert #2 fails
  1188. public void NotModifiedSince ()
  1189. {
  1190. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  1191. string url = "http://" + ep.ToString () + "/test/";
  1192. using (SocketResponder responder = new SocketResponder (ep, s => NotModifiedSinceHandler (s))) {
  1193. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1194. req.Method = "GET";
  1195. req.KeepAlive = false;
  1196. req.Timeout = 20000;
  1197. req.ReadWriteTimeout = 20000;
  1198. req.Headers.Add (HttpRequestHeader.IfNoneMatch, "898bbr2347056cc2e096afc66e104653");
  1199. req.IfModifiedSince = new DateTime (2010, 01, 04);
  1200. var sw = global::System.Diagnostics.Stopwatch.StartNew ();
  1201. HttpWebResponse response = null;
  1202. try {
  1203. req.GetResponse ();
  1204. Assert.Fail ("#1");
  1205. } catch (WebException e) {
  1206. response = (HttpWebResponse) e.Response;
  1207. }
  1208. Assert.IsNotNull (response, "#2");
  1209. using (Stream stream = response.GetResponseStream ()) {
  1210. byte [] buffer = new byte [4096];
  1211. int bytesRead = stream.Read (buffer, 0, buffer.Length);
  1212. Assert.AreEqual (0, bytesRead, "#3");
  1213. }
  1214. TimeSpan elapsed = sw.Elapsed;
  1215. Assert.IsTrue (elapsed.TotalMilliseconds < 2000, "#4");
  1216. }
  1217. }
  1218. [Test] // bug #353495
  1219. [Category ("NotWorking")]
  1220. public void LastModifiedKind ()
  1221. {
  1222. const string reqURL = "http://coffeefaq.com/site/node/25";
  1223. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (reqURL);
  1224. HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
  1225. DateTime lastMod = resp.LastModified;
  1226. //string rawLastMod = resp.Headers ["Last-Modified"];
  1227. resp.Close ();
  1228. //Assert.AreEqual ("Tue, 15 Jan 2008 08:59:59 GMT", rawLastMod, "#1");
  1229. Assert.AreEqual (DateTimeKind.Local, lastMod.Kind, "#2");
  1230. req = (HttpWebRequest) WebRequest.Create (reqURL);
  1231. req.IfModifiedSince = lastMod;
  1232. try {
  1233. resp = (HttpWebResponse) req.GetResponse ();
  1234. resp.Close ();
  1235. Assert.Fail ("Should result in 304");
  1236. } catch (WebException ex) {
  1237. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#3");
  1238. Assert.AreEqual (((HttpWebResponse) ex.Response).StatusCode, HttpStatusCode.NotModified, "#4");
  1239. }
  1240. }
  1241. #region Timeout_Bug // https://bugzilla.novell.com/show_bug.cgi?id=317553
  1242. class TimeoutTestHelper {
  1243. string url_to_test;
  1244. internal DateTime? Start { get; private set; }
  1245. internal DateTime? End { get; private set; }
  1246. internal Exception Exception { get; private set; }
  1247. internal string Body { get; private set; }
  1248. internal int TimeOutInMilliSeconds { get; private set; }
  1249. internal TimeoutTestHelper (string url, int timeoutInMilliseconds)
  1250. {
  1251. url_to_test = url;
  1252. TimeOutInMilliSeconds = timeoutInMilliseconds;
  1253. }
  1254. internal void LaunchWebRequest ()
  1255. {
  1256. try {
  1257. var req = (HttpWebRequest) WebRequest.Create (url_to_test);
  1258. req.Timeout = TimeOutInMilliSeconds;
  1259. Start = DateTime.UtcNow;
  1260. using (var resp = (HttpWebResponse) req.GetResponse ())
  1261. {
  1262. var sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
  1263. Body = sr.ReadToEnd ();
  1264. }
  1265. } catch (Exception e) {
  1266. End = DateTime.UtcNow;
  1267. Exception = e;
  1268. }
  1269. }
  1270. }
  1271. void TestTimeOut (string url, WebExceptionStatus expectedExceptionStatus)
  1272. {
  1273. var timeoutWorker = new TimeoutTestHelper (url, three_seconds_in_milliseconds);
  1274. var threadStart = new ThreadStart (timeoutWorker.LaunchWebRequest);
  1275. var thread = new Thread (threadStart);
  1276. thread.Start ();
  1277. Thread.Sleep (three_seconds_in_milliseconds * 3);
  1278. if (timeoutWorker.End == null) {
  1279. #if MONO_FEATURE_THREAD_ABORT
  1280. thread.Abort ();
  1281. #else
  1282. thread.Interrupt ();
  1283. #endif
  1284. Assert.Fail ("Thread finished after triple the timeout specified has passed");
  1285. }
  1286. if (!String.IsNullOrEmpty (timeoutWorker.Body)) {
  1287. if (timeoutWorker.Body == response_of_timeout_handler) {
  1288. Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve proper body");
  1289. }
  1290. Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve an incorrect body: " + timeoutWorker.Body);
  1291. }
  1292. Assert.IsNotNull (timeoutWorker.Exception, "Exception was not thrown");
  1293. var webEx = timeoutWorker.Exception as WebException;
  1294. Assert.IsNotNull (webEx, "Exception thrown should be WebException, but was: " +
  1295. timeoutWorker.Exception.GetType ().FullName);
  1296. Assert.AreEqual (expectedExceptionStatus, webEx.Status,
  1297. "WebException was thrown, but with a wrong status (should be " + expectedExceptionStatus + "): " + webEx.Status);
  1298. Assert.IsFalse (timeoutWorker.End > (timeoutWorker.Start + TimeSpan.FromMilliseconds (three_seconds_in_milliseconds + 500)),
  1299. "Timeout exception should have been thrown shortly after timeout is reached, however it was at least half-second late");
  1300. }
  1301. [Test] // 1st possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
  1302. #if FEATURE_NO_BSD_SOCKETS
  1303. [ExpectedException (typeof (PlatformNotSupportedException))]
  1304. #endif
  1305. public void TestTimeoutPropertyWithServerThatExistsAndRespondsButTooLate ()
  1306. {
  1307. var ep = NetworkHelpers.LocalEphemeralEndPoint ();
  1308. string url = "http://" + ep + "/foobar/";
  1309. using (var responder = new SocketResponder (ep, TimeOutHandler))
  1310. {
  1311. TestTimeOut (url, WebExceptionStatus.Timeout);
  1312. }
  1313. }
  1314. [Test] // 2nd possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
  1315. [Category ("RequiresBSDSockets")] // Requires some test refactoring to assert that a PlatformNotSupportedException is thrown, so don't bother (there's plenty of other tests asserting the PlatformNotSupported exceptions).
  1316. public void TestTimeoutWithEndpointThatDoesntExistThrowsConnectFailureBeforeTimeout ()
  1317. {
  1318. string url = "http://127.0.0.1:8271/"; // some endpoint that is unlikely to exist
  1319. // connecting to a non-existing endpoint should throw a ConnectFailure before the timeout is reached
  1320. TestTimeOut (url, WebExceptionStatus.ConnectFailure);
  1321. }
  1322. const string response_of_timeout_handler = "RESPONSE_OF_TIMEOUT_HANDLER";
  1323. const int three_seconds_in_milliseconds = 3000;
  1324. private static byte[] TimeOutHandler (Socket socket)
  1325. {
  1326. socket.Receive (new byte[4096]);
  1327. Thread.Sleep (three_seconds_in_milliseconds * 2);
  1328. var sw = new StringWriter ();
  1329. sw.WriteLine ("HTTP/1.1 200 OK");
  1330. sw.WriteLine ("Content-Type: text/plain");
  1331. sw.WriteLine ("Content-Length: " + response_of_timeout_handler.Length);
  1332. sw.WriteLine ();
  1333. sw.Write (response_of_timeout_handler);
  1334. sw.Flush ();
  1335. return Encoding.UTF8.GetBytes (sw.ToString ());
  1336. }
  1337. #endregion
  1338. internal static byte [] EchoRequestHandler (Socket socket)
  1339. {
  1340. MemoryStream ms = new MemoryStream ();
  1341. byte [] buffer = new byte [4096];
  1342. int bytesReceived = socket.Receive (buffer);
  1343. while (bytesReceived > 0) {
  1344. ms.Write (buffer, 0, bytesReceived);
  1345. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1346. // after sending the headers
  1347. Thread.Sleep (200);
  1348. if (socket.Available > 0) {
  1349. bytesReceived = socket.Receive (buffer);
  1350. } else {
  1351. bytesReceived = 0;
  1352. }
  1353. }
  1354. ms.Flush ();
  1355. ms.Position = 0;
  1356. StreamReader sr = new StreamReader (ms, Encoding.UTF8);
  1357. string request = sr.ReadToEnd ();
  1358. StringWriter sw = new StringWriter ();
  1359. sw.WriteLine ("HTTP/1.1 200 OK");
  1360. sw.WriteLine ("Content-Type: text/xml");
  1361. sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
  1362. sw.WriteLine ();
  1363. sw.Write (request);
  1364. sw.Flush ();
  1365. return Encoding.UTF8.GetBytes (sw.ToString ());
  1366. }
  1367. static byte [] RedirectRequestHandler (Socket socket)
  1368. {
  1369. MemoryStream ms = new MemoryStream ();
  1370. byte [] buffer = new byte [4096];
  1371. int bytesReceived = socket.Receive (buffer);
  1372. while (bytesReceived > 0) {
  1373. ms.Write (buffer, 0, bytesReceived);
  1374. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1375. // after sending the headers
  1376. Thread.Sleep (200);
  1377. if (socket.Available > 0) {
  1378. bytesReceived = socket.Receive (buffer);
  1379. } else {
  1380. bytesReceived = 0;
  1381. }
  1382. }
  1383. ms.Flush ();
  1384. ms.Position = 0;
  1385. string statusLine = null;
  1386. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  1387. statusLine = sr.ReadLine ();
  1388. }
  1389. StringWriter sw = new StringWriter ();
  1390. if (statusLine.StartsWith ("POST /original/")) {
  1391. sw.WriteLine ("HTTP/1.0 302 Found");
  1392. EndPoint ep = socket.LocalEndPoint;
  1393. sw.WriteLine ("Location: " + "http://" + ep.ToString () + "/moved/");
  1394. sw.WriteLine ();
  1395. sw.Flush ();
  1396. } else if (statusLine.StartsWith ("GET /moved/")) {
  1397. sw.WriteLine ("HTTP/1.0 200 OK");
  1398. sw.WriteLine ("Content-Type: text/plain");
  1399. sw.WriteLine ("Content-Length: 8");
  1400. sw.WriteLine ();
  1401. sw.Write ("LOOKS OK");
  1402. sw.Flush ();
  1403. } else {
  1404. sw.WriteLine ("HTTP/1.0 500 Too Lazy");
  1405. sw.WriteLine ();
  1406. sw.Flush ();
  1407. }
  1408. return Encoding.UTF8.GetBytes (sw.ToString ());
  1409. }
  1410. static byte [] InternalErrorHandler (Socket socket)
  1411. {
  1412. byte [] buffer = new byte [4096];
  1413. int bytesReceived = socket.Receive (buffer);
  1414. while (bytesReceived > 0) {
  1415. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1416. // after sending the headers
  1417. Thread.Sleep (200);
  1418. if (socket.Available > 0) {
  1419. bytesReceived = socket.Receive (buffer);
  1420. } else {
  1421. bytesReceived = 0;
  1422. }
  1423. }
  1424. StringWriter sw = new StringWriter ();
  1425. sw.WriteLine ("HTTP/1.1 500 Too Lazy");
  1426. sw.WriteLine ("Content-Length: 0");
  1427. sw.WriteLine ();
  1428. sw.Flush ();
  1429. return Encoding.UTF8.GetBytes (sw.ToString ());
  1430. }
  1431. static byte [] NoContentLengthHandler (Socket socket)
  1432. {
  1433. StringWriter sw = new StringWriter ();
  1434. sw.WriteLine ("HTTP/1.1 500 Too Lazy");
  1435. sw.WriteLine ();
  1436. sw.Flush ();
  1437. return Encoding.UTF8.GetBytes (sw.ToString ());
  1438. }
  1439. static byte [] NotModifiedSinceHandler (Socket socket)
  1440. {
  1441. StringWriter sw = new StringWriter ();
  1442. sw.WriteLine ("HTTP/1.1 304 Not Modified");
  1443. sw.WriteLine ("Date: Fri, 06 Feb 2009 12:50:26 GMT");
  1444. sw.WriteLine ("Server: Apache/2.2.6 (Debian) PHP/5.2.6-2+b1 with Suhosin-Patch mod_ssl/2.2.6 OpenSSL/0.9.8g");
  1445. sw.WriteLine ("Not-Modified-Since: Sun, 08 Feb 2009 08:49:26 GMT");
  1446. sw.WriteLine ("ETag: 898bbr2347056cc2e096afc66e104653");
  1447. sw.WriteLine ("Connection: close");
  1448. sw.WriteLine ();
  1449. sw.Flush ();
  1450. return Encoding.UTF8.GetBytes (sw.ToString ());
  1451. }
  1452. static byte [] VerbEchoHandler (Socket socket)
  1453. {
  1454. MemoryStream ms = new MemoryStream ();
  1455. byte [] buffer = new byte [4096];
  1456. int bytesReceived = socket.Receive (buffer);
  1457. while (bytesReceived > 0) {
  1458. ms.Write (buffer, 0, bytesReceived);
  1459. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1460. // after sending the headers
  1461. Thread.Sleep (200);
  1462. if (socket.Available > 0) {
  1463. bytesReceived = socket.Receive (buffer);
  1464. } else {
  1465. bytesReceived = 0;
  1466. }
  1467. }
  1468. ms.Flush ();
  1469. ms.Position = 0;
  1470. string statusLine = null;
  1471. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  1472. statusLine = sr.ReadLine ();
  1473. }
  1474. string verb = "DEFAULT";
  1475. if (statusLine != null) {
  1476. string [] parts = statusLine.Split (' ');
  1477. if (parts.Length > 0)
  1478. verb = parts [0];
  1479. }
  1480. StringWriter sw = new StringWriter ();
  1481. sw.WriteLine ("HTTP/1.1 200 OK");
  1482. sw.WriteLine ("Content-Type: text/plain");
  1483. sw.WriteLine ("Content-Length: " + verb.Length);
  1484. sw.WriteLine ();
  1485. sw.Write (verb);
  1486. sw.Flush ();
  1487. return Encoding.UTF8.GetBytes (sw.ToString ());
  1488. }
  1489. static byte [] PostAnd401Handler (Socket socket)
  1490. {
  1491. MemoryStream ms = new MemoryStream ();
  1492. byte [] buffer = new byte [4096];
  1493. int bytesReceived = socket.Receive (buffer);
  1494. while (bytesReceived > 0) {
  1495. ms.Write (buffer, 0, bytesReceived);
  1496. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  1497. // after sending the headers
  1498. Thread.Sleep (200);
  1499. if (socket.Available > 0) {
  1500. bytesReceived = socket.Receive (buffer);
  1501. } else {
  1502. bytesReceived = 0;
  1503. }
  1504. }
  1505. ms.Flush ();
  1506. ms.Position = 0;
  1507. string statusLine = null;
  1508. bool have_auth = false;
  1509. int cl = -1;
  1510. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  1511. string l;
  1512. while ((l = sr.ReadLine ()) != null) {
  1513. if (statusLine == null) {
  1514. statusLine = l;
  1515. } else if (l.StartsWith ("Authorization:")) {
  1516. have_auth = true;
  1517. } else if (l.StartsWith ("Content-Length:")) {
  1518. cl = Int32.Parse (l.Substring ("content-length: ".Length));
  1519. }
  1520. }
  1521. }
  1522. StringWriter sw = new StringWriter ();
  1523. if (!have_auth) {
  1524. sw.WriteLine ("HTTP/1.0 401 Invalid Credentials");
  1525. sw.WriteLine ("WWW-Authenticate: basic Yeah");
  1526. sw.WriteLine ();
  1527. sw.Flush ();
  1528. } else if (cl > 0 && statusLine.StartsWith ("POST ")) {
  1529. sw.WriteLine ("HTTP/1.0 200 OK");
  1530. sw.WriteLine ("Content-Type: text/plain");
  1531. sw.WriteLine ("Content-Length: 8");
  1532. sw.WriteLine ();
  1533. sw.Write ("LOOKS OK");
  1534. sw.Flush ();
  1535. } else {
  1536. sw.WriteLine ("HTTP/1.0 500 test failed");
  1537. sw.WriteLine ("Content-Length: 0");
  1538. sw.WriteLine ();
  1539. sw.Flush ();
  1540. }
  1541. return Encoding.UTF8.GetBytes (sw.ToString ());
  1542. }
  1543. [Test]
  1544. #if FEATURE_NO_BSD_SOCKETS
  1545. [ExpectedException (typeof (PlatformNotSupportedException))]
  1546. #endif
  1547. public void NtlmAuthentication ()
  1548. {
  1549. NtlmServer server = new NtlmServer ();
  1550. server.Start ();
  1551. string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
  1552. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  1553. request.Timeout = 5000;
  1554. request.Credentials = new NetworkCredential ("user", "password", "domain");
  1555. HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
  1556. string res = null;
  1557. using (StreamReader reader = new StreamReader (resp.GetResponseStream ())) {
  1558. res = reader.ReadToEnd ();
  1559. }
  1560. resp.Close ();
  1561. server.Stop ();
  1562. Assert.AreEqual ("OK", res);
  1563. }
  1564. class NtlmServer : HttpServer {
  1565. public string Where = "";
  1566. protected override void Run ()
  1567. {
  1568. Where = "before accept";
  1569. Socket client = sock.Accept ();
  1570. NetworkStream ns = new NetworkStream (client, false);
  1571. StreamReader reader = new StreamReader (ns, Encoding.ASCII);
  1572. string line;
  1573. Where = "first read";
  1574. while ((line = reader.ReadLine ()) != null) {
  1575. if (line.Trim () == String.Empty) {
  1576. break;
  1577. }
  1578. }
  1579. Where = "first write";
  1580. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  1581. writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
  1582. "WWW-Authenticate: ignore\r\n" +
  1583. "WWW-Authenticate: NTLM\r\n" +
  1584. "WWW-Authenticate: ignore,K\r\n" +
  1585. "Content-Length: 5\r\n\r\nWRONG");
  1586. writer.Flush ();
  1587. Where = "second read";
  1588. while ((line = reader.ReadLine ()) != null) {
  1589. if (line.Trim () == String.Empty) {
  1590. break;
  1591. }
  1592. }
  1593. Where = "second write";
  1594. writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
  1595. "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAADgAAAABggAC8GDhqIONH3sAAAAAAAAAAAAAAAA4AAAABQLODgAAAA8=\r\n" +
  1596. "Content-Length: 5\r\n\r\nWRONG");
  1597. writer.Flush ();
  1598. Where = "third read";
  1599. while ((line = reader.ReadLine ()) != null) {
  1600. if (line.Trim () == String.Empty) {
  1601. break;
  1602. }
  1603. }
  1604. Where = "third write";
  1605. writer.Write ( "HTTP/1.1 200 OK\r\n" +
  1606. "Keep-Alive: true\r\n" +
  1607. "Content-Length: 2\r\n\r\nOK");
  1608. writer.Flush ();
  1609. Thread.Sleep (1000);
  1610. writer.Close ();
  1611. reader.Close ();
  1612. client.Close ();
  1613. }
  1614. }
  1615. class BadChunkedServer : HttpServer {
  1616. protected override void Run ()
  1617. {
  1618. Socket client = sock.Accept ();
  1619. NetworkStream ns = new NetworkStream (client, true);
  1620. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  1621. writer.Write ( "HTTP/1.1 200 OK\r\n" +
  1622. "Transfer-Encoding: chunked\r\n" +
  1623. "Connection: close\r\n" +
  1624. "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
  1625. // This body lacks a 'last-chunk' (see RFC 2616)
  1626. writer.Write ("10\r\n1234567890123456\r\n");
  1627. writer.Flush ();
  1628. client.Shutdown (SocketShutdown.Send);
  1629. Thread.Sleep (1000);
  1630. writer.Close ();
  1631. }
  1632. }
  1633. class AcceptAllPolicy : ICertificatePolicy {
  1634. public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error)
  1635. {
  1636. return true;
  1637. }
  1638. }
  1639. abstract class HttpServer
  1640. {
  1641. protected Socket sock;
  1642. protected Exception error;
  1643. protected ManualResetEvent evt;
  1644. public HttpServer ()
  1645. {
  1646. sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  1647. sock.Bind (new IPEndPoint (IPAddress.Loopback, 0));
  1648. sock.Listen (1);
  1649. }
  1650. public void Start ()
  1651. {
  1652. evt = new ManualResetEvent (false);
  1653. Thread th = new Thread (new ThreadStart (Run));
  1654. th.Start ();
  1655. }
  1656. public void Stop ()
  1657. {
  1658. evt.Set ();
  1659. sock.Close ();
  1660. }
  1661. public IPAddress IPAddress {
  1662. get { return ((IPEndPoint) sock.LocalEndPoint).Address; }
  1663. }
  1664. public int Port {
  1665. get { return ((IPEndPoint) sock.LocalEndPoint).Port; }
  1666. }
  1667. public Exception Error {
  1668. get { return error; }
  1669. }
  1670. protected abstract void Run ();
  1671. }
  1672. [Test]
  1673. #if FEATURE_NO_BSD_SOCKETS
  1674. [ExpectedException (typeof (PlatformNotSupportedException))]
  1675. #endif
  1676. public void BeginGetRequestStream ()
  1677. {
  1678. this.DoRequest (
  1679. (r, c) =>
  1680. {
  1681. r.Method = "POST";
  1682. r.ContentLength = 0;
  1683. r.BeginGetRequestStream ((a) =>
  1684. {
  1685. using (Stream s = r.EndGetRequestStream (a)) { };
  1686. c.Set();
  1687. },
  1688. null);
  1689. },
  1690. (c) => { });
  1691. }
  1692. [Test]
  1693. #if FEATURE_NO_BSD_SOCKETS
  1694. [ExpectedException (typeof (PlatformNotSupportedException))]
  1695. #endif
  1696. public void BeginGetRequestStreamNoClose ()
  1697. {
  1698. this.DoRequest (
  1699. (r, c) => {
  1700. r.Method = "POST";
  1701. r.ContentLength = 1;
  1702. r.BeginGetRequestStream ((a) =>
  1703. {
  1704. r.EndGetRequestStream (a);
  1705. c.Set ();
  1706. },
  1707. null);
  1708. },
  1709. (c) => {});
  1710. }
  1711. [Test]
  1712. #if FEATURE_NO_BSD_SOCKETS
  1713. [ExpectedException (typeof (PlatformNotSupportedException))]
  1714. #endif
  1715. public void BeginGetRequestStreamCancelIfNotAllBytesWritten ()
  1716. {
  1717. this.DoRequest (
  1718. (r, c) =>
  1719. {
  1720. r.Method = "POST";
  1721. r.ContentLength = 10;
  1722. r.BeginGetRequestStream ((a) =>
  1723. {
  1724. WebException ex = ExceptionAssert.Throws<WebException> (() =>
  1725. {
  1726. using (Stream s = r.EndGetRequestStream (a)) {
  1727. }
  1728. }
  1729. );
  1730. Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
  1731. c.Set();
  1732. },
  1733. null);
  1734. },
  1735. (c) => { });
  1736. }
  1737. [Test]
  1738. #if FEATURE_NO_BSD_SOCKETS
  1739. [ExpectedException (typeof (PlatformNotSupportedException))]
  1740. #endif
  1741. public void GetRequestStream2 ()
  1742. {
  1743. this.DoRequest (
  1744. (r, c) =>
  1745. {
  1746. r.Method = "POST";
  1747. r.ContentLength = data64KB.Length;
  1748. using (Stream s = r.GetRequestStream ()) {
  1749. s.Write (data64KB, 0, data64KB.Length);
  1750. }
  1751. c.Set ();
  1752. },
  1753. (c) => { });
  1754. }
  1755. [Test]
  1756. #if FEATURE_NO_BSD_SOCKETS
  1757. [ExpectedException (typeof (PlatformNotSupportedException))]
  1758. #endif
  1759. public void GetRequestStreamNotAllBytesWritten ()
  1760. {
  1761. this.DoRequest (
  1762. (r, c) =>
  1763. {
  1764. r.Method = "POST";
  1765. r.ContentLength = data64KB.Length;
  1766. WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ().Close ());
  1767. Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
  1768. c.Set ();
  1769. },
  1770. (c) => {});
  1771. }
  1772. [Test]
  1773. #if FEATURE_NO_BSD_SOCKETS
  1774. [ExpectedException (typeof (PlatformNotSupportedException))]
  1775. #endif
  1776. public void GetRequestStreamTimeout ()
  1777. {
  1778. this.DoRequest (
  1779. (r, c) =>
  1780. {
  1781. r.Method = "POST";
  1782. r.ContentLength = data64KB.Length;
  1783. r.Timeout = 100;
  1784. WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ());
  1785. Assert.IsTrue (ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure);
  1786. c.Set();
  1787. });
  1788. }
  1789. [Test]
  1790. #if FEATURE_NO_BSD_SOCKETS
  1791. [ExpectedException (typeof (PlatformNotSupportedException))]
  1792. #endif
  1793. public void BeginWrite ()
  1794. {
  1795. byte[] received = new byte[data64KB.Length];
  1796. this.DoRequest (
  1797. (r, c) =>
  1798. {
  1799. r.Method = "POST";
  1800. r.ContentLength = data64KB.Length;
  1801. Stream s = r.GetRequestStream ();
  1802. s.BeginWrite (data64KB, 0, data64KB.Length,
  1803. (a) =>
  1804. {
  1805. s.EndWrite (a);
  1806. s.Close ();
  1807. r.GetResponse ().Close ();
  1808. c.Set();
  1809. },
  1810. null);
  1811. },
  1812. (c) =>
  1813. {
  1814. c.Request.InputStream.ReadAll (received, 0, received.Length);
  1815. c.Response.StatusCode = 204;
  1816. c.Response.Close ();
  1817. });
  1818. Assert.AreEqual (data64KB, received);
  1819. }
  1820. [Test]
  1821. #if FEATURE_NO_BSD_SOCKETS
  1822. [ExpectedException (typeof (PlatformNotSupportedException))]
  1823. #endif
  1824. public void BeginWriteAfterAbort ()
  1825. {
  1826. byte [] received = new byte [data64KB.Length];
  1827. this.DoRequest (
  1828. (r, c) =>
  1829. {
  1830. r.Method = "POST";
  1831. r.ContentLength = data64KB.Length;
  1832. Stream s = r.GetRequestStream ();
  1833. r.Abort();
  1834. WebException ex = ExceptionAssert.Throws<WebException> (() => s.BeginWrite (data64KB, 0, data64KB.Length, null, null));
  1835. Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
  1836. c.Set();
  1837. },
  1838. (c) =>
  1839. {
  1840. //c.Request.InputStream.ReadAll (received, 0, received.Length);
  1841. //c.Response.StatusCode = 204;
  1842. //c.Response.Close();
  1843. });
  1844. }
  1845. [Test]
  1846. #if FEATURE_NO_BSD_SOCKETS
  1847. [ExpectedException (typeof (PlatformNotSupportedException))]
  1848. #endif
  1849. public void PrematureStreamCloseAborts ()
  1850. {
  1851. byte [] received = new byte [data64KB.Length];
  1852. this.DoRequest (
  1853. (r, c) =>
  1854. {
  1855. r.Method = "POST";
  1856. r.ContentLength = data64KB.Length * 2;
  1857. Stream s = r.GetRequestStream ();
  1858. s.Write (data64KB, 0, data64KB.Length);
  1859. WebException ex = ExceptionAssert.Throws<WebException>(() => s.Close());
  1860. Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
  1861. c.Set();
  1862. },
  1863. (c) =>
  1864. {
  1865. c.Request.InputStream.ReadAll (received, 0, received.Length);
  1866. // c.Response.StatusCode = 204;
  1867. // c.Response.Close ();
  1868. });
  1869. }
  1870. [Test]
  1871. #if FEATURE_NO_BSD_SOCKETS
  1872. [ExpectedException (typeof (PlatformNotSupportedException))]
  1873. #endif
  1874. public void Write ()
  1875. {
  1876. byte [] received = new byte [data64KB.Length];
  1877. this.DoRequest (
  1878. (r, c) =>
  1879. {
  1880. r.Method = "POST";
  1881. r.ContentLength = data64KB.Length;
  1882. using (Stream s = r.GetRequestStream ()) {
  1883. s.Write (data64KB, 0, data64KB.Length);
  1884. }
  1885. r.GetResponse ().Close ();
  1886. c.Set ();
  1887. },
  1888. (c) =>
  1889. {
  1890. c.Request.InputStream.ReadAll (received, 0, received.Length);
  1891. c.Response.StatusCode = 204;
  1892. c.Response.Close ();
  1893. });
  1894. Assert.AreEqual(data64KB, received);
  1895. }
  1896. /*
  1897. Invalid test: it does not work on linux.
  1898. [pid 30973] send(9, "POST / HTTP/1.1\r\nContent-Length:"..., 89, 0) = 89
  1899. Abort set
  1900. [pid 30970] send(16, "HTTP/1.1 200 OK\r\nServer: Mono-HT"..., 133, 0) = 133
  1901. Calling abort
  1902. [pid 30970] close(16) = 0
  1903. Closing!!!
  1904. [pid 30980] send(9, "\213t\326\350\312u\36n\234\351\225L\r\243a\200\226\371\350F\271~oZ\32\270\24\226z4\211\345"..., 65536, 0) = 65536
  1905. Writing...
  1906. [pid 30966] close(4) = 0
  1907. OK
  1908. *
  1909. The server sideis closed (FD 16) and the send on the client side (FD 9) succeeds.
  1910. [Test]
  1911. [Category("NotWorking")]
  1912. public void WriteServerAborts ()
  1913. {
  1914. ManualResetEvent abort = new ManualResetEvent (false);
  1915. byte [] received = new byte [data64KB.Length];
  1916. this.DoRequest (
  1917. (r, c) =>
  1918. {
  1919. r.Method = "POST";
  1920. r.ContentLength = data64KB.Length;
  1921. using (Stream s = r.GetRequestStream()) {
  1922. abort.Set();
  1923. Thread.Sleep(100);
  1924. IOException ex = ExceptionAssert.Throws<IOException> (() => s.Write(data64KB, 0, data64KB.Length));
  1925. }
  1926. c.Set();
  1927. },
  1928. (c) =>
  1929. {
  1930. abort.WaitOne();
  1931. c.Response.Abort();
  1932. });
  1933. }
  1934. **/
  1935. [Test]
  1936. #if FEATURE_NO_BSD_SOCKETS
  1937. [ExpectedException (typeof (PlatformNotSupportedException))]
  1938. #endif
  1939. public void Read ()
  1940. {
  1941. byte [] received = new byte [data64KB.Length];
  1942. this.DoRequest (
  1943. (r, c) =>
  1944. {
  1945. using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
  1946. using (Stream s = x.GetResponseStream()) {
  1947. s.ReadAll (received, 0, received.Length);
  1948. }
  1949. c.Set ();
  1950. },
  1951. (c) =>
  1952. {
  1953. c.Response.StatusCode = 200;
  1954. c.Response.ContentLength64 = data64KB.Length;
  1955. c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
  1956. c.Response.OutputStream.Close ();
  1957. c.Response.Close ();
  1958. });
  1959. Assert.AreEqual (data64KB, received);
  1960. }
  1961. [Test]
  1962. #if FEATURE_NO_BSD_SOCKETS
  1963. [ExpectedException (typeof (PlatformNotSupportedException))]
  1964. #endif
  1965. public void ReadTimeout2 ()
  1966. {
  1967. byte [] received = new byte [data64KB.Length];
  1968. this.DoRequest (
  1969. (r, c) =>
  1970. {
  1971. r.ReadWriteTimeout = 10;
  1972. using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
  1973. using (Stream s = x.GetResponseStream ()) {
  1974. WebException ex = ExceptionAssert.Throws<WebException> (() => s.ReadAll (received, 0, received.Length));
  1975. Assert.AreEqual (ex.Status, WebExceptionStatus.Timeout);
  1976. }
  1977. c.Set();
  1978. },
  1979. (c) =>
  1980. {
  1981. c.Response.StatusCode = 200;
  1982. c.Response.ContentLength64 = data64KB.Length;
  1983. c.Response.OutputStream.Write (data64KB, 0, data64KB.Length / 2);
  1984. Thread.Sleep (1000);
  1985. // c.Response.OutputStream.Write (data64KB, data64KB.Length / 2, data64KB.Length / 2);
  1986. c.Response.OutputStream.Close ();
  1987. c.Response.Close ();
  1988. });
  1989. }
  1990. [Test]
  1991. #if FEATURE_NO_BSD_SOCKETS
  1992. [ExpectedException (typeof (PlatformNotSupportedException))]
  1993. #endif
  1994. public void ReadServerAborted ()
  1995. {
  1996. byte [] received = new byte [data64KB.Length];
  1997. this.DoRequest (
  1998. (r, c) =>
  1999. {
  2000. using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
  2001. using (Stream s = x.GetResponseStream ()) {
  2002. Assert.AreEqual (1, s.ReadAll (received, 0, received.Length));
  2003. }
  2004. c.Set();
  2005. },
  2006. (c) =>
  2007. {
  2008. c.Response.StatusCode = 200;
  2009. c.Response.ContentLength64 = data64KB.Length;
  2010. c.Response.OutputStream.Write (data64KB, 0, 1);
  2011. c.Response.Abort ();
  2012. });
  2013. }
  2014. [Test]
  2015. #if FEATURE_NO_BSD_SOCKETS
  2016. [ExpectedException (typeof (PlatformNotSupportedException))]
  2017. #endif
  2018. public void BeginGetResponse2 ()
  2019. {
  2020. byte [] received = new byte [data64KB.Length];
  2021. this.DoRequest (
  2022. (r, c) =>
  2023. {
  2024. r.BeginGetResponse ((a) =>
  2025. {
  2026. using (HttpWebResponse x = (HttpWebResponse) r.EndGetResponse (a))
  2027. using (Stream s = x.GetResponseStream ()) {
  2028. s.ReadAll (received, 0, received.Length);
  2029. }
  2030. c.Set();
  2031. }, null);
  2032. },
  2033. (c) =>
  2034. {
  2035. c.Response.StatusCode = 200;
  2036. c.Response.ContentLength64 = data64KB.Length;
  2037. c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
  2038. c.Response.OutputStream.Close ();
  2039. c.Response.Close ();
  2040. });
  2041. Assert.AreEqual (data64KB, received);
  2042. }
  2043. [Test]
  2044. #if FEATURE_NO_BSD_SOCKETS
  2045. [ExpectedException (typeof (PlatformNotSupportedException))]
  2046. #endif
  2047. public void BeginGetResponseAborts ()
  2048. {
  2049. ManualResetEvent aborted = new ManualResetEvent(false);
  2050. this.DoRequest (
  2051. (r, c) =>
  2052. {
  2053. r.BeginGetResponse((a) =>
  2054. {
  2055. WebException ex = ExceptionAssert.Throws<WebException> (() => r.EndGetResponse (a));
  2056. Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
  2057. c.Set ();
  2058. }, null);
  2059. aborted.WaitOne ();
  2060. r.Abort ();
  2061. },
  2062. (c) =>
  2063. {
  2064. aborted.Set ();
  2065. // Thread.Sleep (100);
  2066. // c.Response.StatusCode = 200;
  2067. // c.Response.ContentLength64 = 0;
  2068. // c.Response.Close ();
  2069. });
  2070. return;
  2071. }
  2072. [Test]
  2073. #if FEATURE_NO_BSD_SOCKETS
  2074. [ExpectedException (typeof (PlatformNotSupportedException))]
  2075. #endif
  2076. public void TestLargeDataReading ()
  2077. {
  2078. int near2GBStartPosition = rand.Next (int.MaxValue - 500, int.MaxValue);
  2079. AutoResetEvent readyGetLastPortionEvent = new AutoResetEvent (false);
  2080. Exception testException = null;
  2081. DoRequest (
  2082. (request, waitHandle) =>
  2083. {
  2084. try
  2085. {
  2086. const int timeoutMs = 5000;
  2087. request.Timeout = timeoutMs;
  2088. request.ReadWriteTimeout = timeoutMs;
  2089. WebResponse webResponse = request.GetResponse ();
  2090. Stream webResponseStream = webResponse.GetResponseStream ();
  2091. Assert.IsNotNull (webResponseStream, null, "#1");
  2092. Type webConnectionStreamType = webResponseStream.GetType ();
  2093. FieldInfo totalReadField = webConnectionStreamType.GetField ("totalRead", BindingFlags.NonPublic | BindingFlags.Instance);
  2094. Assert.IsNotNull (totalReadField, "#2");
  2095. totalReadField.SetValue (webResponseStream, near2GBStartPosition);
  2096. byte[] readBuffer = new byte[int.MaxValue - near2GBStartPosition];
  2097. Assert.AreEqual (webResponseStream.Read (readBuffer, 0, readBuffer.Length), readBuffer.Length, "#3");
  2098. readyGetLastPortionEvent.Set ();
  2099. Assert.IsTrue (webResponseStream.Read (readBuffer, 0, readBuffer.Length) > 0);
  2100. readyGetLastPortionEvent.Set ();
  2101. webResponse.Close();
  2102. }
  2103. catch (Exception e)
  2104. {
  2105. testException = e;
  2106. }
  2107. finally
  2108. {
  2109. waitHandle.Set ();
  2110. }
  2111. },
  2112. processor =>
  2113. {
  2114. processor.Request.InputStream.Close ();
  2115. HttpListenerResponse response = processor.Response;
  2116. response.SendChunked = true;
  2117. Stream outputStream = response.OutputStream;
  2118. var writeBuffer = new byte[int.MaxValue - near2GBStartPosition];
  2119. outputStream.Write (writeBuffer, 0, writeBuffer.Length);
  2120. readyGetLastPortionEvent.WaitOne ();
  2121. outputStream.Write (writeBuffer, 0, writeBuffer.Length);
  2122. readyGetLastPortionEvent.WaitOne ();
  2123. response.Close();
  2124. });
  2125. if (testException != null)
  2126. throw testException;
  2127. }
  2128. void DoRequest (Action<HttpWebRequest, EventWaitHandle> request)
  2129. {
  2130. int port = NetworkHelpers.FindFreePort ();
  2131. ManualResetEvent completed = new ManualResetEvent (false);
  2132. Uri address = new Uri (string.Format ("http://localhost:{0}", port));
  2133. HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
  2134. request (client, completed);
  2135. if (!completed.WaitOne (10000))
  2136. Assert.Fail ("Test hung");
  2137. }
  2138. void DoRequest (Action<HttpWebRequest, EventWaitHandle> request, Action<HttpListenerContext> processor)
  2139. {
  2140. int port = NetworkHelpers.FindFreePort ();
  2141. ManualResetEvent [] completed = new ManualResetEvent [2];
  2142. completed [0] = new ManualResetEvent (false);
  2143. completed [1] = new ManualResetEvent (false);
  2144. using (ListenerScope scope = new ListenerScope (processor, port, completed [0])) {
  2145. Uri address = new Uri (string.Format ("http://localhost:{0}", port));
  2146. HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
  2147. ThreadPool.QueueUserWorkItem ((o) => request (client, completed [1]));
  2148. if (!WaitHandle.WaitAll (completed, 10000))
  2149. Assert.Fail ("Test hung.");
  2150. }
  2151. }
  2152. [Test]
  2153. #if FEATURE_NO_BSD_SOCKETS
  2154. [ExpectedException (typeof (PlatformNotSupportedException))]
  2155. #else
  2156. [ExpectedException (typeof (ArgumentNullException))]
  2157. #endif
  2158. public void NullHost ()
  2159. {
  2160. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2161. req.Host = null;
  2162. }
  2163. [Test]
  2164. #if FEATURE_NO_BSD_SOCKETS
  2165. [ExpectedException (typeof (PlatformNotSupportedException))]
  2166. #endif
  2167. public void NoHost ()
  2168. {
  2169. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2170. Assert.AreEqual (req.Host, "go-mono.com");
  2171. }
  2172. [Test]
  2173. #if FEATURE_NO_BSD_SOCKETS
  2174. [ExpectedException (typeof (PlatformNotSupportedException))]
  2175. #else
  2176. [ExpectedException (typeof (ArgumentException))]
  2177. #endif
  2178. public void EmptyHost ()
  2179. {
  2180. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2181. req.Host = "";
  2182. }
  2183. [Test]
  2184. #if FEATURE_NO_BSD_SOCKETS
  2185. [ExpectedException (typeof (PlatformNotSupportedException))]
  2186. #endif
  2187. public void HostAndPort ()
  2188. {
  2189. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:80");
  2190. Assert.AreEqual ("go-mono.com", req.Host, "#01");
  2191. req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:9000");
  2192. Assert.AreEqual ("go-mono.com:9000", req.Host, "#02");
  2193. }
  2194. [Test]
  2195. #if FEATURE_NO_BSD_SOCKETS
  2196. [ExpectedException (typeof (PlatformNotSupportedException))]
  2197. #endif
  2198. public void PortRange ()
  2199. {
  2200. for (int i = 0; i < 65536; i++) {
  2201. if (i == 80)
  2202. continue;
  2203. string s = i.ToString ();
  2204. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:" + s);
  2205. Assert.AreEqual ("go-mono.com:" + s, req.Host, "#" + s);
  2206. }
  2207. }
  2208. [Test]
  2209. #if FEATURE_NO_BSD_SOCKETS
  2210. [ExpectedException (typeof (PlatformNotSupportedException))]
  2211. #else
  2212. [ExpectedException (typeof (ArgumentException))]
  2213. #endif
  2214. public void PortBelow ()
  2215. {
  2216. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2217. req.Host = "go-mono.com:-1";
  2218. }
  2219. [Test]
  2220. #if FEATURE_NO_BSD_SOCKETS
  2221. [ExpectedException (typeof (PlatformNotSupportedException))]
  2222. #else
  2223. [ExpectedException (typeof (ArgumentException))]
  2224. #endif
  2225. public void PortAbove ()
  2226. {
  2227. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2228. req.Host = "go-mono.com:65536";
  2229. }
  2230. [Test]
  2231. #if FEATURE_NO_BSD_SOCKETS
  2232. [ExpectedException (typeof (PlatformNotSupportedException))]
  2233. #else
  2234. [ExpectedException (typeof (ArgumentException))]
  2235. #endif
  2236. public void HostTooLong ()
  2237. {
  2238. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2239. string s = new string ('a', 100);
  2240. req.Host = s + "." + s + "." + s + "." + s + "." + s + "." + s; // Over 255 bytes
  2241. }
  2242. [Test]
  2243. [Category ("NotWorking")] // #5490
  2244. public void InvalidNamesThatWork ()
  2245. {
  2246. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2247. req.Host = "-";
  2248. req.Host = "-.-";
  2249. req.Host = "á";
  2250. req.Host = new string ('a', 64); // Should fail. Max. is 63.
  2251. }
  2252. [Test]
  2253. #if FEATURE_NO_BSD_SOCKETS
  2254. [ExpectedException (typeof (PlatformNotSupportedException))]
  2255. #endif
  2256. public void NoDate ()
  2257. {
  2258. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2259. Assert.AreEqual (DateTime.MinValue, req.Date);
  2260. }
  2261. [Test]
  2262. #if FEATURE_NO_BSD_SOCKETS
  2263. [ExpectedException (typeof (PlatformNotSupportedException))]
  2264. #endif
  2265. public void UtcDate ()
  2266. {
  2267. HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
  2268. req.Date = DateTime.UtcNow;
  2269. DateTime date = req.Date;
  2270. Assert.AreEqual (DateTimeKind.Local, date.Kind);
  2271. }
  2272. [Test]
  2273. #if FEATURE_NO_BSD_SOCKETS
  2274. [ExpectedException (typeof (PlatformNotSupportedException))]
  2275. #endif
  2276. public void AddAndRemoveDate ()
  2277. {
  2278. // Neil Armstrong set his foot on Moon
  2279. var landing = new DateTime (1969, 7, 21, 2, 56, 0, DateTimeKind.Utc);
  2280. Assert.AreEqual (621214377600000000, landing.Ticks);
  2281. var unspecified = new DateTime (1969, 7, 21, 2, 56, 0);
  2282. var local = landing.ToLocalTime ();
  2283. var req = (HttpWebRequest)WebRequest.Create ("http://www.mono-project.com/");
  2284. req.Date = landing;
  2285. Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
  2286. Assert.AreEqual (local.Ticks, req.Date.Ticks);
  2287. Assert.AreEqual (local, req.Date);
  2288. req.Date = unspecified;
  2289. Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
  2290. Assert.AreEqual (unspecified.Ticks, req.Date.Ticks);
  2291. Assert.AreEqual (unspecified, req.Date);
  2292. req.Date = local;
  2293. Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
  2294. Assert.AreEqual (local.Ticks, req.Date.Ticks);
  2295. Assert.AreEqual (local, req.Date);
  2296. req.Date = DateTime.MinValue;
  2297. Assert.AreEqual (DateTimeKind.Unspecified, DateTime.MinValue.Kind);
  2298. Assert.AreEqual (DateTimeKind.Unspecified, req.Date.Kind);
  2299. Assert.AreEqual (0, req.Date.Ticks);
  2300. Assert.AreEqual (null, req.Headers.Get ("Date"));
  2301. }
  2302. [Test]
  2303. #if FEATURE_NO_BSD_SOCKETS
  2304. [ExpectedException (typeof (PlatformNotSupportedException))]
  2305. #endif
  2306. // Bug #12393
  2307. public void TestIPv6Host ()
  2308. {
  2309. var address = "2001:0000:0000:0001:0001:0001:0157:0000";
  2310. var address2 = '[' + address + ']';
  2311. var uri = new Uri (string.Format ("http://{0}/test.css", address2));
  2312. var hwr = (HttpWebRequest)WebRequest.Create (uri);
  2313. hwr.Host = address2;
  2314. Assert.AreEqual (address2, hwr.Host, "#1");
  2315. }
  2316. [Test]
  2317. // Bug #12393
  2318. [Category ("NotWorking")]
  2319. public void TestIPv6Host2 ()
  2320. {
  2321. var address = "2001:0000:0000:0001:0001:0001:0157:0000";
  2322. var address2 = '[' + address + ']';
  2323. var uri = new Uri (string.Format ("http://{0}/test.css", address2));
  2324. var hwr = (HttpWebRequest)WebRequest.Create (uri);
  2325. try {
  2326. hwr.Host = address;
  2327. Assert.Fail ("#1");
  2328. } catch (ArgumentException) {
  2329. ;
  2330. }
  2331. }
  2332. [Test]
  2333. #if FEATURE_NO_BSD_SOCKETS
  2334. [ExpectedException (typeof (PlatformNotSupportedException))]
  2335. #endif
  2336. public void AllowReadStreamBuffering ()
  2337. {
  2338. var hr = WebRequest.CreateHttp ("http://www.google.com");
  2339. Assert.IsFalse (hr.AllowReadStreamBuffering, "#1");
  2340. try {
  2341. hr.AllowReadStreamBuffering = true;
  2342. Assert.Fail ("#2");
  2343. } catch (InvalidOperationException) {
  2344. }
  2345. }
  2346. class ListenerScope : IDisposable {
  2347. EventWaitHandle completed;
  2348. public HttpListener listener;
  2349. Action<HttpListenerContext> processor;
  2350. public ListenerScope (Action<HttpListenerContext> processor, int port, EventWaitHandle completed)
  2351. {
  2352. this.processor = processor;
  2353. this.completed = completed;
  2354. this.listener = new HttpListener ();
  2355. this.listener.Prefixes.Add (string.Format ("http://localhost:{0}/", port));
  2356. this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  2357. this.listener.Start ();
  2358. this.listener.BeginGetContext (this.RequestHandler, null);
  2359. }
  2360. void RequestHandler (IAsyncResult result)
  2361. {
  2362. HttpListenerContext context = null;
  2363. try {
  2364. context = this.listener.EndGetContext (result);
  2365. } catch (HttpListenerException ex) {
  2366. // check if the thread has been aborted as in the case when we are shutting down.
  2367. if (ex.ErrorCode == 995)
  2368. return;
  2369. } catch (ObjectDisposedException) {
  2370. return;
  2371. }
  2372. ThreadPool.QueueUserWorkItem ((o) =>
  2373. {
  2374. try {
  2375. this.processor (context);
  2376. } catch (HttpListenerException) {
  2377. }
  2378. });
  2379. this.completed.Set ();
  2380. }
  2381. public void Dispose ()
  2382. {
  2383. this.listener.Stop ();
  2384. }
  2385. }
  2386. #if !MOBILE && !MONOMAC
  2387. class SslHttpServer : HttpServer {
  2388. X509Certificate _certificate;
  2389. protected override void Run ()
  2390. {
  2391. try {
  2392. Socket client = sock.Accept ();
  2393. NetworkStream ns = new NetworkStream (client, true);
  2394. SslServerStream s = new SslServerStream (ns, Certificate, false, false);
  2395. s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
  2396. StreamReader reader = new StreamReader (s);
  2397. StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
  2398. string line;
  2399. string hello = "<html><body><h1>Hello World!</h1></body></html>";
  2400. string answer = "HTTP/1.0 200\r\n" +
  2401. "Connection: close\r\n" +
  2402. "Content-Type: text/html\r\n" +
  2403. "Content-Encoding: " + Encoding.ASCII.WebName + "\r\n" +
  2404. "Content-Length: " + hello.Length + "\r\n" +
  2405. "\r\n" + hello;
  2406. // Read the headers
  2407. do {
  2408. line = reader.ReadLine ();
  2409. } while (line != "" && line != null && line.Length > 0);
  2410. // Now the content. We know it's 100 bytes.
  2411. // This makes BeginRead in sslclientstream block.
  2412. char [] cs = new char [100];
  2413. reader.Read (cs, 0, 100);
  2414. writer.Write (answer);
  2415. writer.Flush ();
  2416. if (evt.WaitOne (5000, false))
  2417. error = new Exception ("Timeout when stopping the server");
  2418. } catch (Exception e) {
  2419. error = e;
  2420. }
  2421. }
  2422. X509Certificate Certificate {
  2423. get {
  2424. if (_certificate == null)
  2425. _certificate = new X509Certificate (CertData.Certificate);
  2426. return _certificate;
  2427. }
  2428. }
  2429. AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost)
  2430. {
  2431. PrivateKey key = new PrivateKey (CertData.PrivateKey, null);
  2432. return key.RSA;
  2433. }
  2434. }
  2435. class CertData {
  2436. public readonly static byte [] Certificate = {
  2437. 48, 130, 1, 191, 48, 130, 1, 40, 160, 3, 2, 1, 2, 2, 16, 36,
  2438. 14, 97, 190, 146, 132, 208, 71, 175, 6, 87, 168, 185, 175, 55, 43, 48,
  2439. 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 48, 18,
  2440. 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103, 111, 110, 122, 97,
  2441. 108, 111, 48, 30, 23, 13, 48, 53, 48, 54, 50, 50, 49, 57, 51, 48,
  2442. 52, 54, 90, 23, 13, 51, 57, 49, 50, 51, 49, 50, 51, 53, 57, 53,
  2443. 57, 90, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103,
  2444. 111, 110, 122, 97, 108, 111, 48, 129, 158, 48, 13, 6, 9, 42, 134, 72,
  2445. 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 140, 0, 48, 129, 136, 2,
  2446. 129, 129, 0, 138, 9, 38, 25, 166, 252, 59, 26, 39, 184, 128, 216, 38,
  2447. 73, 41, 86, 30, 228, 160, 205, 41, 135, 115, 223, 44, 62, 42, 198, 178,
  2448. 190, 81, 11, 25, 21, 216, 49, 179, 130, 246, 52, 97, 175, 212, 94, 157,
  2449. 231, 162, 66, 161, 103, 63, 204, 83, 141, 172, 119, 97, 225, 206, 98, 101,
  2450. 210, 106, 2, 206, 81, 90, 173, 47, 41, 199, 209, 241, 177, 177, 96, 207,
  2451. 254, 220, 190, 66, 180, 153, 0, 209, 14, 178, 69, 194, 3, 37, 116, 239,
  2452. 49, 23, 185, 245, 255, 126, 35, 85, 246, 56, 244, 107, 117, 24, 14, 57,
  2453. 9, 111, 147, 189, 220, 142, 57, 104, 153, 193, 205, 19, 14, 22, 157, 16,
  2454. 24, 80, 201, 2, 2, 0, 17, 163, 23, 48, 21, 48, 19, 6, 3, 85,
  2455. 29, 37, 4, 12, 48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1,
  2456. 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 3,
  2457. 129, 129, 0, 64, 49, 57, 253, 218, 198, 229, 51, 189, 12, 154, 225, 183,
  2458. 160, 147, 90, 113, 172, 69, 122, 28, 77, 97, 215, 231, 194, 150, 29, 196,
  2459. 65, 95, 218, 99, 142, 111, 79, 205, 109, 76, 32, 92, 220, 76, 88, 53,
  2460. 237, 80, 11, 85, 44, 91, 21, 210, 12, 34, 223, 234, 18, 187, 136, 62,
  2461. 26, 240, 103, 180, 12, 226, 221, 250, 247, 129, 51, 23, 129, 165, 56, 67,
  2462. 43, 83, 244, 110, 207, 24, 253, 195, 16, 46, 80, 113, 80, 18, 2, 254,
  2463. 120, 147, 151, 164, 23, 210, 230, 100, 19, 197, 179, 28, 194, 48, 106, 159,
  2464. 155, 144, 37, 82, 44, 160, 40, 52, 146, 174, 77, 188, 160, 230, 75, 172,
  2465. 123, 3, 254,
  2466. };
  2467. public readonly static byte [] PrivateKey = {
  2468. 30, 241, 181, 176, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
  2469. 0, 0, 0, 0, 84, 2, 0, 0, 7, 2, 0, 0, 0, 36, 0, 0,
  2470. 82, 83, 65, 50, 0, 4, 0, 0, 17, 0, 0, 0, 201, 80, 24, 16,
  2471. 157, 22, 14, 19, 205, 193, 153, 104, 57, 142, 220, 189, 147, 111, 9, 57,
  2472. 14, 24, 117, 107, 244, 56, 246, 85, 35, 126, 255, 245, 185, 23, 49, 239,
  2473. 116, 37, 3, 194, 69, 178, 14, 209, 0, 153, 180, 66, 190, 220, 254, 207,
  2474. 96, 177, 177, 241, 209, 199, 41, 47, 173, 90, 81, 206, 2, 106, 210, 101,
  2475. 98, 206, 225, 97, 119, 172, 141, 83, 204, 63, 103, 161, 66, 162, 231, 157,
  2476. 94, 212, 175, 97, 52, 246, 130, 179, 49, 216, 21, 25, 11, 81, 190, 178,
  2477. 198, 42, 62, 44, 223, 115, 135, 41, 205, 160, 228, 30, 86, 41, 73, 38,
  2478. 216, 128, 184, 39, 26, 59, 252, 166, 25, 38, 9, 138, 175, 88, 190, 223,
  2479. 27, 24, 224, 123, 190, 69, 164, 234, 129, 59, 108, 229, 248, 62, 187, 15,
  2480. 235, 147, 162, 83, 47, 123, 170, 190, 224, 31, 215, 110, 143, 31, 227, 216,
  2481. 85, 88, 154, 83, 207, 229, 41, 28, 237, 116, 181, 17, 37, 141, 224, 185,
  2482. 164, 144, 141, 233, 164, 138, 177, 241, 115, 181, 230, 150, 7, 92, 139, 141,
  2483. 113, 95, 57, 191, 211, 165, 217, 250, 197, 68, 164, 184, 168, 43, 48, 65,
  2484. 177, 237, 173, 144, 148, 221, 62, 189, 147, 63, 216, 188, 206, 103, 226, 171,
  2485. 32, 20, 230, 116, 144, 192, 1, 39, 202, 87, 74, 250, 6, 142, 188, 23,
  2486. 45, 4, 112, 191, 253, 67, 69, 70, 128, 143, 44, 234, 41, 96, 195, 82,
  2487. 202, 35, 158, 149, 240, 151, 23, 25, 166, 179, 85, 144, 58, 120, 149, 229,
  2488. 205, 34, 8, 110, 86, 119, 130, 210, 37, 173, 65, 71, 169, 67, 8, 51,
  2489. 20, 96, 51, 155, 3, 39, 85, 187, 40, 193, 57, 19, 99, 78, 173, 28,
  2490. 129, 154, 108, 175, 8, 138, 237, 71, 27, 148, 129, 35, 47, 57, 101, 237,
  2491. 168, 178, 227, 221, 212, 63, 124, 254, 253, 215, 183, 159, 49, 103, 74, 49,
  2492. 67, 160, 171, 72, 194, 215, 108, 251, 178, 18, 184, 100, 211, 105, 21, 186,
  2493. 39, 66, 218, 154, 72, 222, 90, 237, 179, 251, 51, 224, 212, 56, 251, 6,
  2494. 209, 151, 198, 176, 89, 110, 35, 141, 248, 237, 223, 68, 135, 206, 207, 169,
  2495. 254, 219, 243, 130, 71, 11, 94, 113, 233, 92, 63, 156, 169, 72, 215, 110,
  2496. 95, 94, 191, 50, 59, 89, 187, 59, 183, 99, 161, 146, 233, 245, 219, 80,
  2497. 87, 113, 251, 50, 144, 195, 158, 46, 189, 232, 119, 91, 75, 22, 6, 176,
  2498. 39, 206, 25, 196, 213, 195, 219, 24, 28, 103, 104, 36, 137, 128, 4, 119,
  2499. 163, 40, 126, 87, 18, 86, 128, 243, 213, 101, 2, 237, 78, 64, 160, 55,
  2500. 199, 93, 90, 126, 175, 199, 55, 89, 234, 190, 5, 16, 196, 88, 28, 208,
  2501. 28, 92, 32, 115, 204, 9, 202, 101, 15, 123, 43, 75, 90, 144, 95, 179,
  2502. 102, 249, 57, 150, 204, 99, 147, 203, 16, 63, 81, 244, 226, 237, 82, 204,
  2503. 20, 200, 140, 65, 83, 217, 161, 23, 123, 37, 115, 12, 100, 73, 70, 190,
  2504. 32, 235, 174, 140, 148, 157, 47, 238, 40, 208, 228, 80, 54, 187, 156, 252,
  2505. 253, 230, 231, 156, 138, 125, 96, 79, 3, 27, 143, 55, 146, 169, 165, 61,
  2506. 238, 60, 227, 77, 217, 93, 117, 122, 111, 46, 173, 113,
  2507. };
  2508. }
  2509. #endif
  2510. [Test]
  2511. #if FEATURE_NO_BSD_SOCKETS
  2512. [ExpectedException (typeof (PlatformNotSupportedException))]
  2513. #endif
  2514. public void CookieContainerTest ()
  2515. {
  2516. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2517. string url = "http://" + ep.ToString ();
  2518. using (SocketResponder responder = new SocketResponder (ep, s => CookieRequestHandler (s))) {
  2519. CookieContainer container = new CookieContainer ();
  2520. container.Add(new Uri (url), new Cookie ("foo", "bar"));
  2521. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  2522. request.CookieContainer = container;
  2523. WebHeaderCollection headers = request.Headers;
  2524. headers.Add("Cookie", "foo=baz");
  2525. HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
  2526. string responseString = null;
  2527. using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
  2528. responseString = reader.ReadToEnd ();
  2529. }
  2530. response.Close ();
  2531. Assert.AreEqual (1, response.Cookies.Count, "#01");
  2532. Assert.AreEqual ("foo=bar", response.Headers.Get("Set-Cookie"), "#02");
  2533. }
  2534. using (SocketResponder responder = new SocketResponder (ep, s => CookieRequestHandler (s))) {
  2535. CookieContainer container = new CookieContainer ();
  2536. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  2537. request.CookieContainer = container;
  2538. WebHeaderCollection headers = request.Headers;
  2539. headers.Add("Cookie", "foo=baz");
  2540. HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
  2541. string responseString = null;
  2542. using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
  2543. responseString = reader.ReadToEnd ();
  2544. }
  2545. response.Close ();
  2546. Assert.AreEqual (0, response.Cookies.Count, "#03");
  2547. Assert.AreEqual ("", response.Headers.Get("Set-Cookie"), "#04");
  2548. }
  2549. }
  2550. internal static byte[] CookieRequestHandler (Socket socket)
  2551. {
  2552. MemoryStream ms = new MemoryStream ();
  2553. byte[] buffer = new byte[4096];
  2554. int bytesReceived = socket.Receive (buffer);
  2555. while (bytesReceived > 0) {
  2556. ms.Write(buffer, 0, bytesReceived);
  2557. // We don't check for Content-Length or anything else here, so we give the client a little time to write
  2558. // after sending the headers
  2559. Thread.Sleep(200);
  2560. if (socket.Available > 0) {
  2561. bytesReceived = socket.Receive (buffer);
  2562. } else {
  2563. bytesReceived = 0;
  2564. }
  2565. }
  2566. ms.Flush();
  2567. ms.Position = 0;
  2568. string cookies = string.Empty;
  2569. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  2570. string line;
  2571. while ((line = sr.ReadLine ()) != null) {
  2572. if (line.StartsWith ("Cookie:")) {
  2573. cookies = line.Substring ("cookie: ".Length);
  2574. }
  2575. }
  2576. }
  2577. StringWriter sw = new StringWriter ();
  2578. sw.WriteLine ("HTTP/1.1 200 OK");
  2579. sw.WriteLine ("Content-Type: text/xml");
  2580. sw.WriteLine ("Set-Cookie: " + cookies);
  2581. sw.WriteLine ("Content-Length: " + cookies.Length.ToString (CultureInfo.InvariantCulture));
  2582. sw.WriteLine ();
  2583. sw.Write (cookies);
  2584. sw.Flush ();
  2585. return Encoding.UTF8.GetBytes (sw.ToString ());
  2586. }
  2587. }
  2588. [TestFixture]
  2589. public class HttpRequestStreamTest
  2590. {
  2591. [Test]
  2592. #if FEATURE_NO_BSD_SOCKETS
  2593. [ExpectedException (typeof (PlatformNotSupportedException))]
  2594. #endif
  2595. public void BeginRead ()
  2596. {
  2597. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2598. string url = "http://" + ep.ToString () + "/test/";
  2599. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2600. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2601. req.Method = "POST";
  2602. using (Stream rs = req.GetRequestStream ()) {
  2603. byte [] buffer = new byte [10];
  2604. try {
  2605. rs.BeginRead (buffer, 0, buffer.Length, null, null);
  2606. Assert.Fail ("#1");
  2607. } catch (NotSupportedException ex) {
  2608. // The stream does not support reading
  2609. Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
  2610. Assert.IsNull (ex.InnerException, "#3");
  2611. Assert.IsNotNull (ex.Message, "#4");
  2612. } finally {
  2613. req.Abort ();
  2614. }
  2615. }
  2616. }
  2617. }
  2618. [Test]
  2619. [Category("MobileNotWorking")]
  2620. public void BeginWrite_Request_Aborted ()
  2621. {
  2622. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2623. string url = "http://" + ep.ToString () + "/test/";
  2624. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2625. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2626. req.Method = "POST";
  2627. using (Stream rs = req.GetRequestStream ()) {
  2628. req.Abort ();
  2629. try {
  2630. rs.BeginWrite (new byte [] { 0x2a, 0x2f }, 0, 2, null, null);
  2631. Assert.Fail ("#1");
  2632. } catch (WebException ex) {
  2633. // The request was aborted: The request was canceled
  2634. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  2635. Assert.IsNull (ex.InnerException, "#3");
  2636. Assert.IsNotNull (ex.Message, "#4");
  2637. Assert.IsNull (ex.Response, "#5");
  2638. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  2639. }
  2640. }
  2641. }
  2642. }
  2643. [Test]
  2644. #if FEATURE_NO_BSD_SOCKETS
  2645. [ExpectedException (typeof (PlatformNotSupportedException))]
  2646. #endif
  2647. public void CanRead ()
  2648. {
  2649. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2650. string url = "http://" + ep.ToString () + "/test/";
  2651. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2652. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2653. req.Method = "POST";
  2654. Stream rs = req.GetRequestStream ();
  2655. try {
  2656. Assert.IsFalse (rs.CanRead, "#1");
  2657. rs.Close ();
  2658. Assert.IsFalse (rs.CanRead, "#2");
  2659. } finally {
  2660. rs.Close ();
  2661. req.Abort ();
  2662. }
  2663. }
  2664. }
  2665. [Test]
  2666. #if FEATURE_NO_BSD_SOCKETS
  2667. [ExpectedException (typeof (PlatformNotSupportedException))]
  2668. #endif
  2669. public void CanSeek ()
  2670. {
  2671. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2672. string url = "http://" + ep.ToString () + "/test/";
  2673. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2674. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2675. req.Method = "POST";
  2676. Stream rs = req.GetRequestStream ();
  2677. try {
  2678. Assert.IsFalse (rs.CanSeek, "#1");
  2679. rs.Close ();
  2680. Assert.IsFalse (rs.CanSeek, "#2");
  2681. } finally {
  2682. rs.Close ();
  2683. req.Abort ();
  2684. }
  2685. }
  2686. }
  2687. [Test] // bug #324182
  2688. #if FEATURE_NO_BSD_SOCKETS
  2689. [ExpectedException (typeof (PlatformNotSupportedException))]
  2690. #endif
  2691. public void CanTimeout ()
  2692. {
  2693. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2694. string url = "http://" + ep.ToString () + "/test/";
  2695. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2696. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2697. req.Method = "POST";
  2698. Stream rs = req.GetRequestStream ();
  2699. try {
  2700. Assert.IsTrue (rs.CanTimeout, "#1");
  2701. rs.Close ();
  2702. Assert.IsTrue (rs.CanTimeout, "#2");
  2703. } finally {
  2704. rs.Close ();
  2705. req.Abort ();
  2706. }
  2707. }
  2708. }
  2709. [Test]
  2710. #if FEATURE_NO_BSD_SOCKETS
  2711. [ExpectedException (typeof (PlatformNotSupportedException))]
  2712. #endif
  2713. public void CanWrite ()
  2714. {
  2715. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2716. string url = "http://" + ep.ToString () + "/test/";
  2717. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2718. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2719. req.Method = "POST";
  2720. Stream rs = req.GetRequestStream ();
  2721. try {
  2722. Assert.IsTrue (rs.CanWrite, "#1");
  2723. rs.Close ();
  2724. // CanRead and CanWrite do not change status after closing.
  2725. Assert.IsTrue (rs.CanWrite, "#2");
  2726. } finally {
  2727. rs.Close ();
  2728. req.Abort ();
  2729. }
  2730. }
  2731. }
  2732. [Test]
  2733. #if FEATURE_NO_BSD_SOCKETS
  2734. [ExpectedException (typeof (PlatformNotSupportedException))]
  2735. #endif
  2736. public void Read ()
  2737. {
  2738. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2739. string url = "http://" + ep.ToString () + "/test/";
  2740. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2741. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2742. req.Method = "POST";
  2743. using (Stream rs = req.GetRequestStream ()) {
  2744. byte [] buffer = new byte [10];
  2745. try {
  2746. rs.Read (buffer, 0, buffer.Length);
  2747. Assert.Fail ("#1");
  2748. } catch (NotSupportedException ex) {
  2749. // The stream does not support reading
  2750. Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
  2751. Assert.IsNull (ex.InnerException, "#3");
  2752. Assert.IsNotNull (ex.Message, "#4");
  2753. } finally {
  2754. req.Abort ();
  2755. }
  2756. }
  2757. }
  2758. }
  2759. [Test]
  2760. #if FEATURE_NO_BSD_SOCKETS
  2761. [ExpectedException (typeof (PlatformNotSupportedException))]
  2762. #endif
  2763. public void ReadByte ()
  2764. {
  2765. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2766. string url = "http://" + ep.ToString () + "/test/";
  2767. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2768. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2769. req.Method = "POST";
  2770. using (Stream rs = req.GetRequestStream ()) {
  2771. try {
  2772. rs.ReadByte ();
  2773. Assert.Fail ("#1");
  2774. } catch (NotSupportedException ex) {
  2775. // The stream does not support reading
  2776. Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
  2777. Assert.IsNull (ex.InnerException, "#3");
  2778. Assert.IsNotNull (ex.Message, "#4");
  2779. } finally {
  2780. req.Abort ();
  2781. }
  2782. }
  2783. }
  2784. }
  2785. [Test]
  2786. #if FEATURE_NO_BSD_SOCKETS
  2787. [ExpectedException (typeof (PlatformNotSupportedException))]
  2788. #endif
  2789. public void ReadTimeout ()
  2790. {
  2791. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2792. string url = "http://" + ep.ToString () + "/test/";
  2793. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2794. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2795. req.Method = "POST";
  2796. Stream rs = req.GetRequestStream ();
  2797. try {
  2798. Assert.AreEqual (300000, rs.ReadTimeout, "#1");
  2799. rs.Close ();
  2800. Assert.AreEqual (300000, rs.ReadTimeout, "#2");
  2801. } finally {
  2802. rs.Close ();
  2803. req.Abort ();
  2804. }
  2805. }
  2806. }
  2807. [Test]
  2808. #if FEATURE_NO_BSD_SOCKETS
  2809. [ExpectedException (typeof (PlatformNotSupportedException))]
  2810. #endif
  2811. public void Seek ()
  2812. {
  2813. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2814. string url = "http://" + ep.ToString () + "/test/";
  2815. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2816. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2817. req.Method = "POST";
  2818. using (Stream rs = req.GetRequestStream ()) {
  2819. try {
  2820. rs.Seek (0, SeekOrigin.Current);
  2821. Assert.Fail ("#1");
  2822. } catch (NotSupportedException ex) {
  2823. // This stream does not support seek operations
  2824. Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
  2825. Assert.IsNull (ex.InnerException, "#3");
  2826. Assert.IsNotNull (ex.Message, "#4");
  2827. } finally {
  2828. req.Abort ();
  2829. }
  2830. }
  2831. }
  2832. }
  2833. [Test]
  2834. #if FEATURE_NO_BSD_SOCKETS
  2835. [ExpectedException (typeof (PlatformNotSupportedException))]
  2836. #endif
  2837. public void Write_Buffer_Null ()
  2838. {
  2839. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2840. string url = "http://" + ep.ToString () + "/test/";
  2841. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2842. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2843. req.Method = "POST";
  2844. using (Stream rs = req.GetRequestStream ()) {
  2845. try {
  2846. rs.Write ((byte []) null, -1, -1);
  2847. Assert.Fail ("#1");
  2848. } catch (ArgumentNullException ex) {
  2849. Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
  2850. Assert.IsNull (ex.InnerException, "#3");
  2851. Assert.IsNotNull (ex.Message, "#4");
  2852. Assert.AreEqual ("buffer", ex.ParamName, "#5");
  2853. }
  2854. }
  2855. req.Abort ();
  2856. }
  2857. }
  2858. [Test]
  2859. #if FEATURE_NO_BSD_SOCKETS
  2860. [ExpectedException (typeof (PlatformNotSupportedException))]
  2861. #endif
  2862. public void Write_Count_Negative ()
  2863. {
  2864. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2865. string url = "http://" + ep.ToString () + "/test/";
  2866. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2867. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2868. req.Method = "POST";
  2869. using (Stream rs = req.GetRequestStream ()) {
  2870. byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
  2871. try {
  2872. rs.Write (buffer, 1, -1);
  2873. Assert.Fail ("#1");
  2874. } catch (ArgumentOutOfRangeException ex) {
  2875. // Specified argument was out of the range of valid values
  2876. Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
  2877. Assert.IsNull (ex.InnerException, "#A3");
  2878. Assert.IsNotNull (ex.Message, "#A4");
  2879. Assert.AreEqual ("size", ex.ParamName, "#A5");
  2880. }
  2881. }
  2882. req.Abort ();
  2883. }
  2884. }
  2885. [Test]
  2886. #if FEATURE_NO_BSD_SOCKETS
  2887. [ExpectedException (typeof (PlatformNotSupportedException))]
  2888. #endif
  2889. public void Write_Count_Overflow ()
  2890. {
  2891. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2892. string url = "http://" + ep.ToString () + "/test/";
  2893. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2894. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2895. req.Method = "POST";
  2896. using (Stream rs = req.GetRequestStream ()) {
  2897. byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
  2898. try {
  2899. rs.Write (buffer, buffer.Length - 2, 3);
  2900. Assert.Fail ("#1");
  2901. } catch (ArgumentOutOfRangeException ex) {
  2902. // Specified argument was out of the range of valid values
  2903. Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
  2904. Assert.IsNull (ex.InnerException, "#3");
  2905. Assert.IsNotNull (ex.Message, "#4");
  2906. Assert.AreEqual ("size", ex.ParamName, "#5");
  2907. }
  2908. }
  2909. req.Abort ();
  2910. }
  2911. }
  2912. [Test]
  2913. #if FEATURE_NO_BSD_SOCKETS
  2914. [ExpectedException (typeof (PlatformNotSupportedException))]
  2915. #endif
  2916. public void Write_Offset_Negative ()
  2917. {
  2918. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2919. string url = "http://" + ep.ToString () + "/test/";
  2920. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2921. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2922. req.Method = "POST";
  2923. using (Stream rs = req.GetRequestStream ()) {
  2924. byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
  2925. try {
  2926. rs.Write (buffer, -1, 0);
  2927. Assert.Fail ("#1");
  2928. } catch (ArgumentOutOfRangeException ex) {
  2929. // Specified argument was out of the range of valid values
  2930. Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
  2931. Assert.IsNull (ex.InnerException, "#3");
  2932. Assert.IsNotNull (ex.Message, "#4");
  2933. Assert.AreEqual ("offset", ex.ParamName, "#5");
  2934. }
  2935. }
  2936. req.Abort ();
  2937. }
  2938. }
  2939. [Test]
  2940. #if FEATURE_NO_BSD_SOCKETS
  2941. [ExpectedException (typeof (PlatformNotSupportedException))]
  2942. #endif
  2943. public void Write_Offset_Overflow ()
  2944. {
  2945. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2946. string url = "http://" + ep.ToString () + "/test/";
  2947. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2948. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2949. req.Method = "POST";
  2950. using (Stream rs = req.GetRequestStream ()) {
  2951. byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
  2952. try {
  2953. rs.Write (buffer, buffer.Length + 1, 0);
  2954. Assert.Fail ("#1");
  2955. } catch (ArgumentOutOfRangeException ex) {
  2956. // Specified argument was out of the range of valid values
  2957. Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
  2958. Assert.IsNull (ex.InnerException, "#3");
  2959. Assert.IsNotNull (ex.Message, "#4");
  2960. Assert.AreEqual ("offset", ex.ParamName, "#5");
  2961. }
  2962. }
  2963. req.Abort ();
  2964. }
  2965. }
  2966. [Test]
  2967. #if FEATURE_NO_BSD_SOCKETS
  2968. [ExpectedException (typeof (PlatformNotSupportedException))]
  2969. #endif
  2970. public void Write_Request_Aborted ()
  2971. {
  2972. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2973. string url = "http://" + ep.ToString () + "/test/";
  2974. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  2975. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  2976. req.Method = "POST";
  2977. using (Stream rs = req.GetRequestStream ()) {
  2978. req.Abort ();
  2979. try {
  2980. rs.Write (new byte [0], 0, 0);
  2981. Assert.Fail ("#1");
  2982. } catch (WebException ex) {
  2983. // The request was aborted: The request was canceled
  2984. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  2985. Assert.IsNull (ex.InnerException, "#3");
  2986. Assert.IsNotNull (ex.Message, "#4");
  2987. Assert.IsNull (ex.Response, "#5");
  2988. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  2989. }
  2990. }
  2991. }
  2992. }
  2993. [Test]
  2994. [Category ("NotWorking")]
  2995. public void Write_Stream_Closed ()
  2996. {
  2997. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  2998. string url = "http://" + ep.ToString () + "/test/";
  2999. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  3000. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  3001. req.Method = "POST";
  3002. using (Stream rs = req.GetRequestStream ()) {
  3003. rs.Close ();
  3004. try {
  3005. rs.Write (new byte [0], 0, 0);
  3006. Assert.Fail ("#1");
  3007. } catch (WebException ex) {
  3008. // The request was aborted: The connection was closed unexpectedly
  3009. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  3010. Assert.IsNull (ex.InnerException, "#3");
  3011. Assert.IsNotNull (ex.Message, "#4");
  3012. Assert.IsNull (ex.Response, "#5");
  3013. Assert.AreEqual (WebExceptionStatus.ConnectionClosed, ex.Status, "#6");
  3014. }
  3015. }
  3016. }
  3017. }
  3018. [Test]
  3019. #if FEATURE_NO_BSD_SOCKETS
  3020. [ExpectedException (typeof (PlatformNotSupportedException))]
  3021. #endif
  3022. public void WriteByte_Request_Aborted ()
  3023. {
  3024. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  3025. string url = "http://" + ep.ToString () + "/test/";
  3026. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  3027. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  3028. req.Method = "POST";
  3029. using (Stream rs = req.GetRequestStream ()) {
  3030. req.Abort ();
  3031. try {
  3032. rs.WriteByte (0x2a);
  3033. Assert.Fail ("#1");
  3034. } catch (WebException ex) {
  3035. // The request was aborted: The request was canceled
  3036. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  3037. Assert.IsNull (ex.InnerException, "#3");
  3038. Assert.IsNotNull (ex.Message, "#4");
  3039. Assert.IsNull (ex.Response, "#5");
  3040. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
  3041. }
  3042. }
  3043. }
  3044. }
  3045. [Test]
  3046. #if FEATURE_NO_BSD_SOCKETS
  3047. [ExpectedException (typeof (PlatformNotSupportedException))]
  3048. #endif
  3049. public void WriteTimeout ()
  3050. {
  3051. IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
  3052. string url = "http://" + ep.ToString () + "/test/";
  3053. using (SocketResponder responder = new SocketResponder (ep, s => HttpWebRequestTest.EchoRequestHandler (s))) {
  3054. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  3055. req.Method = "POST";
  3056. Stream rs = req.GetRequestStream ();
  3057. try {
  3058. Assert.AreEqual (300000, rs.WriteTimeout, "#1");
  3059. rs.Close ();
  3060. Assert.AreEqual (300000, rs.WriteTimeout, "#2");
  3061. } finally {
  3062. rs.Close ();
  3063. req.Abort ();
  3064. }
  3065. }
  3066. }
  3067. [Test]
  3068. #if FEATURE_NO_BSD_SOCKETS
  3069. [ExpectedException (typeof (PlatformNotSupportedException))]
  3070. #endif
  3071. // Bug6737
  3072. // This test is supposed to fail prior to .NET 4.0
  3073. public void Post_EmptyRequestStream ()
  3074. {
  3075. var wr = HttpWebRequest.Create ("http://google.com");
  3076. wr.Method = "POST";
  3077. wr.GetRequestStream ();
  3078. var gr = wr.BeginGetResponse (delegate { }, null);
  3079. Assert.AreEqual (true, gr.AsyncWaitHandle.WaitOne (5000), "#1");
  3080. }
  3081. }
  3082. static class StreamExtensions {
  3083. public static int ReadAll(this Stream stream, byte[] buffer, int offset, int count)
  3084. {
  3085. int totalRead = 0;
  3086. while (totalRead < count) {
  3087. int bytesRead = stream.Read (buffer, offset + totalRead, count - totalRead);
  3088. if (bytesRead == 0)
  3089. break;
  3090. totalRead += bytesRead;
  3091. }
  3092. return totalRead;
  3093. }
  3094. }
  3095. static class ExceptionAssert {
  3096. /// <summary>
  3097. /// Asserts that the function throws an exception.
  3098. /// </summary>
  3099. /// <param name="f">A function execute that is expected to raise an exception.</param>
  3100. /// <typeparam name="T">The type of exception that is expected.</typeparam>
  3101. /// <returns>The exception thrown.</returns>
  3102. /// <exception cref="AssertFailedException">If the function does not throw an exception
  3103. /// or throws a different exception.</exception>
  3104. /// <example><![CDATA[
  3105. /// ExceptionAssert.Throws(typeof(ArgumentNullException), delegate {
  3106. /// myObject.myFunction(null); });
  3107. /// ]]></example>
  3108. public static T Throws<T> (Action f) where T : Exception {
  3109. Exception actualException = null;
  3110. try {
  3111. f ();
  3112. } catch (Exception ex) {
  3113. actualException = ex;
  3114. }
  3115. if (actualException == null)
  3116. throw new AssertionException (string.Format (
  3117. "No exception thrown. Expected '{0}'",
  3118. typeof (T).FullName));
  3119. else if (typeof(T) != actualException.GetType())
  3120. throw new AssertionException (string.Format (
  3121. "Caught exception of type '{0}'. Expected '{1}':{2}",
  3122. actualException.GetType().FullName,
  3123. typeof (T).FullName,
  3124. Environment.NewLine + actualException));
  3125. return (T) actualException;
  3126. }
  3127. }
  3128. }