HttpWebRequestTest.cs 92 KB

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