HttpWebRequestTest.cs 93 KB

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