HttpWebRequestTest.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208
  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://" + IPAddress.Loopback.ToString () + ":8000/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. string x = 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://" + IPAddress.Loopback.ToString () + ":8000/test/";
  248. foreach (DictionaryEntry de in methods) {
  249. SocketResponder responder = new SocketResponder (new IPEndPoint (IPAddress.Loopback, 8000),
  250. new SocketRequestHandler (EchoRequestHandler));
  251. responder.Start ();
  252. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  253. req.Method = (string) de.Key;
  254. req.Timeout = 2000;
  255. req.ReadWriteTimeout = 2000;
  256. req.KeepAlive = false;
  257. Stream rs = req.GetRequestStream ();
  258. rs.Close ();
  259. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  260. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  261. Encoding.UTF8);
  262. string line = sr.ReadLine ();
  263. sr.Close ();
  264. Assert.AreEqual (((string) de.Value) + " /test/ HTTP/1.1",
  265. line, req.Method);
  266. resp.Close ();
  267. }
  268. responder.Stop ();
  269. }
  270. }
  271. [Test]
  272. public void BeginGetRequestStream_Body_NotAllowed ()
  273. {
  274. IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8000);
  275. string url = "http://" + IPAddress.Loopback.ToString () + ":8000/test/";
  276. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
  277. responder.Start ();
  278. HttpWebRequest request;
  279. request = (HttpWebRequest) WebRequest.Create (url);
  280. request.Method = "GET";
  281. try {
  282. request.BeginGetRequestStream (null, null);
  283. Assert.Fail ("#A1");
  284. } catch (ProtocolViolationException ex) {
  285. // Cannot send a content-body with this
  286. // verb-type
  287. Assert.IsNull (ex.InnerException, "#A2");
  288. Assert.IsNotNull (ex.Message, "#A3");
  289. }
  290. request = (HttpWebRequest) WebRequest.Create (url);
  291. request.Method = "HEAD";
  292. try {
  293. request.BeginGetRequestStream (null, null);
  294. Assert.Fail ("#B1");
  295. } catch (ProtocolViolationException ex) {
  296. // Cannot send a content-body with this
  297. // verb-type
  298. Assert.IsNull (ex.InnerException, "#B2");
  299. Assert.IsNotNull (ex.Message, "#B3");
  300. }
  301. }
  302. }
  303. [Test] // bug #465613
  304. public void BeginGetRequestStream_NoBuffering ()
  305. {
  306. IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8002);
  307. string url = "http://" + IPAddress.Loopback.ToString () + ":8002/test/";
  308. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
  309. responder.Start ();
  310. HttpWebRequest req;
  311. Stream rs;
  312. IAsyncResult ar;
  313. req = (HttpWebRequest) WebRequest.Create (url);
  314. req.Method = "POST";
  315. req.SendChunked = false;
  316. req.KeepAlive = false;
  317. req.AllowWriteStreamBuffering = false;
  318. ar = req.BeginGetRequestStream (null, null);
  319. rs = req.EndGetRequestStream (ar);
  320. rs.Close ();
  321. req = (HttpWebRequest) WebRequest.Create (url);
  322. req.Method = "POST";
  323. req.SendChunked = false;
  324. req.KeepAlive = true;
  325. req.AllowWriteStreamBuffering = false;
  326. try {
  327. req.BeginGetRequestStream (null, null);
  328. Assert.Fail ("#A1");
  329. } catch (ProtocolViolationException ex) {
  330. // When performing a write operation with
  331. // AllowWriteStreamBuffering set to false,
  332. // you must either set ContentLength to a
  333. // non-negative number or set SendChunked
  334. // to true
  335. Assert.IsNull (ex.InnerException, "#A2");
  336. Assert.IsNotNull (ex.Message, "#A3");
  337. }
  338. req = (HttpWebRequest) WebRequest.Create (url);
  339. req.Method = "POST";
  340. req.SendChunked = false;
  341. req.KeepAlive = true;
  342. req.AllowWriteStreamBuffering = false;
  343. req.ContentLength = 0;
  344. ar = req.BeginGetRequestStream (null, null);
  345. rs = req.EndGetRequestStream (ar);
  346. rs.Close ();
  347. }
  348. }
  349. [Test] // bug #508027
  350. public void BeginGetResponse ()
  351. {
  352. IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8003);
  353. string url = "http://" + IPAddress.Loopback.ToString () + ":8003/test/";
  354. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
  355. responder.Start ();
  356. HttpWebRequest req;
  357. req = (HttpWebRequest) WebRequest.Create (url);
  358. req.Method = "POST";
  359. req.SendChunked = false;
  360. req.KeepAlive = false;
  361. req.AllowWriteStreamBuffering = false;
  362. req.BeginGetResponse (null, null);
  363. req.Abort ();
  364. req = (HttpWebRequest) WebRequest.Create (url);
  365. req.Method = "POST";
  366. req.SendChunked = true;
  367. req.KeepAlive = false;
  368. req.AllowWriteStreamBuffering = false;
  369. req.BeginGetResponse (null, null);
  370. req.Abort ();
  371. req = (HttpWebRequest) WebRequest.Create (url);
  372. req.Method = "POST";
  373. req.ContentLength = 5;
  374. req.SendChunked = false;
  375. req.KeepAlive = false;
  376. req.AllowWriteStreamBuffering = false;
  377. req.BeginGetResponse (null, null);
  378. req.Abort ();
  379. req = (HttpWebRequest) WebRequest.Create (url);
  380. req.Method = "POST";
  381. req.SendChunked = false;
  382. req.KeepAlive = true;
  383. req.AllowWriteStreamBuffering = false;
  384. #if NET_2_0
  385. req.BeginGetResponse (null, null);
  386. req.Abort ();
  387. #else
  388. try {
  389. req.BeginGetResponse (null, null);
  390. } catch (ProtocolViolationException ex) {
  391. // Either ContentLength must be set to a non-negative
  392. // number, or SendChunked set to true in order to perform
  393. // the write operation when AllowWriteStreamBuffering
  394. // is disabled
  395. Assert.IsNull (ex.InnerException, "#A2");
  396. Assert.IsNotNull (ex.Message, "#A3");
  397. } finally {
  398. req.Abort ();
  399. }
  400. #endif
  401. req = (HttpWebRequest) WebRequest.Create (url);
  402. req.Method = "POST";
  403. req.SendChunked = false;
  404. req.KeepAlive = false;
  405. req.AllowWriteStreamBuffering = false;
  406. req.ContentLength = 5;
  407. req.BeginGetResponse (null, null);
  408. req.Abort ();
  409. req = (HttpWebRequest) WebRequest.Create (url);
  410. req.Method = "POST";
  411. req.SendChunked = false;
  412. req.KeepAlive = true;
  413. req.AllowWriteStreamBuffering = false;
  414. req.ContentLength = 5;
  415. req.BeginGetResponse (null, null);
  416. req.Abort ();
  417. req = (HttpWebRequest) WebRequest.Create (url);
  418. req.Method = "GET";
  419. req.SendChunked = true;
  420. #if NET_2_0
  421. req.BeginGetResponse (null, null);
  422. req.Abort ();
  423. #else
  424. try {
  425. req.BeginGetResponse (null, null);
  426. Assert.Fail ("#B1");
  427. } catch (ProtocolViolationException ex) {
  428. // Content-Length cannot be set for a
  429. // non-write operation
  430. Assert.IsNull (ex.InnerException, "#B2");
  431. Assert.IsNotNull (ex.Message, "#B3");
  432. } finally {
  433. req.Abort ();
  434. }
  435. #endif
  436. req = (HttpWebRequest) WebRequest.Create (url);
  437. req.Method = "GET";
  438. req.ContentLength = 5;
  439. #if NET_2_0
  440. req.BeginGetResponse (null, null);
  441. req.Abort ();
  442. #else
  443. try {
  444. req.BeginGetResponse (null, null);
  445. Assert.Fail ("#C1");
  446. } catch (ProtocolViolationException ex) {
  447. // Content-Length cannot be set for a
  448. // non-write operation
  449. Assert.IsNull (ex.InnerException, "#C2");
  450. Assert.IsNotNull (ex.Message, "#C3");
  451. } finally {
  452. req.Abort ();
  453. }
  454. #endif
  455. req = (HttpWebRequest) WebRequest.Create (url);
  456. req.Method = "GET";
  457. req.ContentLength = 0;
  458. #if NET_2_0
  459. req.BeginGetResponse (null, null);
  460. req.Abort ();
  461. #else
  462. try {
  463. req.BeginGetResponse (null, null);
  464. Assert.Fail ("#D1");
  465. } catch (ProtocolViolationException ex) {
  466. // Content-Length cannot be set for a
  467. // non-write operation
  468. Assert.IsNull (ex.InnerException, "#D2");
  469. Assert.IsNotNull (ex.Message, "#D3");
  470. } finally {
  471. req.Abort ();
  472. }
  473. #endif
  474. }
  475. }
  476. [Test] // bug #429200
  477. public void GetRequestStream ()
  478. {
  479. IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8000);
  480. string url = "http://" + IPAddress.Loopback.ToString () + ":8000/test/";
  481. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
  482. responder.Start ();
  483. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  484. req.Method = "POST";
  485. req.Timeout = 2000;
  486. req.ReadWriteTimeout = 2000;
  487. Stream rs1 = req.GetRequestStream ();
  488. Stream rs2 = req.GetRequestStream ();
  489. Assert.IsNotNull (rs1, "#1");
  490. Assert.AreSame (rs1, rs2, "#2");
  491. rs1.Close ();
  492. }
  493. }
  494. [Test] // bug #510661 and #514996
  495. [Category ("NotWorking")]
  496. public void GetRequestStream_Close_NotAllBytesWritten ()
  497. {
  498. IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8000);
  499. string url = "http://" + IPAddress.Loopback.ToString () + ":8000/test/";
  500. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
  501. responder.Start ();
  502. HttpWebRequest req;
  503. Stream rs;
  504. req = (HttpWebRequest) WebRequest.Create (url);
  505. req.Method = "POST";
  506. req.ContentLength = 2;
  507. rs = req.GetRequestStream ();
  508. try {
  509. rs.Close ();
  510. Assert.Fail ("#A1");
  511. } catch (WebException ex) {
  512. // The request was aborted: The request was canceled
  513. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  514. Assert.IsNotNull (ex.Message, "#A3");
  515. Assert.IsNull (ex.Response, "#A4");
  516. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#A5");
  517. // Cannot close stream until all bytes are written
  518. Exception inner = ex.InnerException;
  519. Assert.IsNotNull (inner, "#A6");
  520. Assert.AreEqual (typeof (IOException), inner.GetType (), "#A7");
  521. Assert.IsNull (inner.InnerException, "#A8");
  522. Assert.IsNotNull (inner.Message, "#A9");
  523. }
  524. req = (HttpWebRequest) WebRequest.Create (url);
  525. req.Method = "POST";
  526. req.ContentLength = 2;
  527. rs = req.GetRequestStream ();
  528. rs.WriteByte (0x0d);
  529. try {
  530. rs.Close ();
  531. Assert.Fail ("#B1");
  532. } catch (WebException ex) {
  533. // The request was aborted: The request was canceled
  534. Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
  535. Assert.IsNotNull (ex.Message, "#B3");
  536. Assert.IsNull (ex.Response, "#B4");
  537. Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#B5");
  538. // Cannot close stream until all bytes are written
  539. Exception inner = ex.InnerException;
  540. Assert.IsNotNull (inner, "#B6");
  541. Assert.AreEqual (typeof (IOException), inner.GetType (), "#B7");
  542. Assert.IsNull (inner.InnerException, "#B8");
  543. Assert.IsNotNull (inner.Message, "#B9");
  544. }
  545. req = (HttpWebRequest) WebRequest.Create (url);
  546. req.Method = "POST";
  547. req.ContentLength = 2;
  548. rs = req.GetRequestStream ();
  549. rs.WriteByte (0x0d);
  550. rs.WriteByte (0x0d);
  551. rs.Close ();
  552. }
  553. }
  554. [Test] // bug #510642
  555. public void GetRequestStream_Write_Overflow ()
  556. {
  557. IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8001);
  558. string url = "http://" + IPAddress.Loopback.ToString () + ":8001/test/";
  559. // buffered, non-chunked
  560. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
  561. responder.Start ();
  562. HttpWebRequest req;
  563. Stream rs;
  564. byte [] buffer;
  565. req = (HttpWebRequest) WebRequest.Create (url);
  566. req.ProtocolVersion = HttpVersion.Version11;
  567. req.Method = "POST";
  568. req.Timeout = 1000;
  569. req.ReadWriteTimeout = 100;
  570. req.ContentLength = 2;
  571. rs = req.GetRequestStream ();
  572. rs.WriteByte (0x2c);
  573. buffer = new byte [] { 0x2a, 0x1d };
  574. try {
  575. rs.Write (buffer, 0, buffer.Length);
  576. Assert.Fail ("#A1");
  577. } catch (ProtocolViolationException ex) {
  578. // Bytes to be written to the stream exceed
  579. // Content-Length bytes size specified
  580. Assert.IsNull (ex.InnerException, "#A2");
  581. Assert.IsNotNull (ex.Message, "#A3");
  582. } finally {
  583. req.Abort ();
  584. }
  585. req = (HttpWebRequest) WebRequest.Create (url);
  586. req.ProtocolVersion = HttpVersion.Version11;
  587. req.Method = "POST";
  588. req.Timeout = 1000;
  589. req.ReadWriteTimeout = 100;
  590. req.ContentLength = 2;
  591. rs = req.GetRequestStream ();
  592. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  593. try {
  594. rs.Write (buffer, 0, buffer.Length);
  595. Assert.Fail ("#B1");
  596. } catch (ProtocolViolationException ex) {
  597. // Bytes to be written to the stream exceed
  598. // Content-Length bytes size specified
  599. Assert.IsNull (ex.InnerException, "#B2");
  600. Assert.IsNotNull (ex.Message, "#B3");
  601. } finally {
  602. req.Abort ();
  603. }
  604. }
  605. // buffered, chunked
  606. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
  607. responder.Start ();
  608. HttpWebRequest req;
  609. Stream rs;
  610. byte [] buffer;
  611. /*
  612. req = (HttpWebRequest) WebRequest.Create (url);
  613. req.ProtocolVersion = HttpVersion.Version11;
  614. req.Method = "POST";
  615. req.SendChunked = true;
  616. req.Timeout = 1000;
  617. req.ReadWriteTimeout = 100;
  618. req.ContentLength = 2;
  619. rs = req.GetRequestStream ();
  620. rs.WriteByte (0x2c);
  621. buffer = new byte [] { 0x2a, 0x1d };
  622. rs.Write (buffer, 0, buffer.Length);
  623. req.Abort ();
  624. */
  625. req = (HttpWebRequest) WebRequest.Create (url);
  626. req.ProtocolVersion = HttpVersion.Version11;
  627. req.Method = "POST";
  628. req.SendChunked = true;
  629. req.Timeout = 1000;
  630. req.ReadWriteTimeout = 100;
  631. req.ContentLength = 2;
  632. rs = req.GetRequestStream ();
  633. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  634. rs.Write (buffer, 0, buffer.Length);
  635. req.Abort ();
  636. }
  637. // non-buffered, non-chunked
  638. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
  639. responder.Start ();
  640. HttpWebRequest req;
  641. Stream rs;
  642. byte [] buffer;
  643. req = (HttpWebRequest) WebRequest.Create (url);
  644. req.AllowWriteStreamBuffering = false;
  645. req.ProtocolVersion = HttpVersion.Version11;
  646. req.Method = "POST";
  647. req.Timeout = 1000;
  648. req.ReadWriteTimeout = 100;
  649. req.ContentLength = 2;
  650. rs = req.GetRequestStream ();
  651. rs.WriteByte (0x2c);
  652. buffer = new byte [] { 0x2a, 0x1d };
  653. try {
  654. rs.Write (buffer, 0, buffer.Length);
  655. Assert.Fail ("#C1");
  656. } catch (ProtocolViolationException ex) {
  657. // Bytes to be written to the stream exceed
  658. // Content-Length bytes size specified
  659. Assert.IsNull (ex.InnerException, "#C2");
  660. Assert.IsNotNull (ex.Message, "#3");
  661. } finally {
  662. req.Abort ();
  663. }
  664. req = (HttpWebRequest) WebRequest.Create (url);
  665. req.AllowWriteStreamBuffering = false;
  666. req.ProtocolVersion = HttpVersion.Version11;
  667. req.Method = "POST";
  668. req.Timeout = 1000;
  669. req.ReadWriteTimeout = 100;
  670. req.ContentLength = 2;
  671. rs = req.GetRequestStream ();
  672. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  673. try {
  674. rs.Write (buffer, 0, buffer.Length);
  675. Assert.Fail ("#D1");
  676. } catch (ProtocolViolationException ex) {
  677. // Bytes to be written to the stream exceed
  678. // Content-Length bytes size specified
  679. Assert.IsNull (ex.InnerException, "#D2");
  680. Assert.IsNotNull (ex.Message, "#D3");
  681. } finally {
  682. req.Abort ();
  683. }
  684. }
  685. // non-buffered, chunked
  686. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
  687. responder.Start ();
  688. HttpWebRequest req;
  689. Stream rs;
  690. byte [] buffer;
  691. req = (HttpWebRequest) WebRequest.Create (url);
  692. req.AllowWriteStreamBuffering = false;
  693. req.ProtocolVersion = HttpVersion.Version11;
  694. req.Method = "POST";
  695. req.SendChunked = true;
  696. req.Timeout = 1000;
  697. req.ReadWriteTimeout = 100;
  698. req.ContentLength = 2;
  699. rs = req.GetRequestStream ();
  700. rs.WriteByte (0x2c);
  701. buffer = new byte [] { 0x2a, 0x1d };
  702. rs.Write (buffer, 0, buffer.Length);
  703. req.Abort ();
  704. req = (HttpWebRequest) WebRequest.Create (url);
  705. req.AllowWriteStreamBuffering = false;
  706. req.ProtocolVersion = HttpVersion.Version11;
  707. req.Method = "POST";
  708. req.SendChunked = true;
  709. req.Timeout = 1000;
  710. req.ReadWriteTimeout = 100;
  711. req.ContentLength = 2;
  712. rs = req.GetRequestStream ();
  713. buffer = new byte [] { 0x2a, 0x2c, 0x1d };
  714. rs.Write (buffer, 0, buffer.Length);
  715. req.Abort ();
  716. }
  717. }
  718. [Test]
  719. [Ignore ("This test asserts that our code violates RFC 2616")]
  720. public void GetRequestStream_Body_NotAllowed ()
  721. {
  722. string [] methods = new string [] { "GET", "HEAD", "CONNECT",
  723. "get", "HeAd", "ConNect" };
  724. foreach (string method in methods) {
  725. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (
  726. "http://localhost:8000");
  727. req.Method = method;
  728. try {
  729. req.GetRequestStream ();
  730. Assert.Fail ("#1:" + method);
  731. } catch (ProtocolViolationException ex) {
  732. Assert.AreEqual (typeof (ProtocolViolationException), ex.GetType (), "#2:" + method);
  733. Assert.IsNull (ex.InnerException, "#3:" + method);
  734. Assert.IsNotNull (ex.Message, "#4:" + method);
  735. }
  736. }
  737. }
  738. [Test]
  739. #if TARGET_JVM
  740. [Category("NotWorking")]
  741. #endif
  742. [Ignore ("This does not timeout any more. That's how MS works when reading small responses")]
  743. public void ReadTimeout ()
  744. {
  745. IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8764);
  746. string url = "http://" + localEP.ToString () + "/original/";
  747. using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
  748. responder.Start ();
  749. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  750. req.Method = "POST";
  751. req.AllowAutoRedirect = false;
  752. req.Timeout = 200;
  753. req.ReadWriteTimeout = 100;
  754. req.KeepAlive = false;
  755. Stream rs = req.GetRequestStream ();
  756. rs.Close ();
  757. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  758. try {
  759. Stream s = resp.GetResponseStream ();
  760. s.ReadByte ();
  761. Assert.Fail ("#1");
  762. } catch (WebException ex) {
  763. Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
  764. Assert.IsNull (ex.InnerException, "#3");
  765. Assert.IsNull (ex.Response, "#4");
  766. Assert.AreEqual (WebExceptionStatus.Timeout, ex.Status, "#5");
  767. }
  768. }
  769. responder.Stop ();
  770. }
  771. }
  772. [Test] // bug #324300
  773. #if TARGET_JVM
  774. [Category("NotWorking")]
  775. #endif
  776. public void AllowAutoRedirect ()
  777. {
  778. IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8764);
  779. string url = "http://" + localEP.ToString () + "/original/";
  780. // allow autoredirect
  781. using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
  782. responder.Start ();
  783. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  784. req.Method = "POST";
  785. req.Timeout = 2000;
  786. req.ReadWriteTimeout = 2000;
  787. req.KeepAlive = false;
  788. Stream rs = req.GetRequestStream ();
  789. rs.Close ();
  790. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  791. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  792. Encoding.UTF8);
  793. string body = sr.ReadToEnd ();
  794. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
  795. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  796. localEP.ToString () + "/moved/", "#A2");
  797. Assert.AreEqual ("GET", resp.Method, "#A3");
  798. Assert.AreEqual ("LOOKS OK", body, "#A4");
  799. }
  800. responder.Stop ();
  801. }
  802. // do not allow autoredirect
  803. using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
  804. responder.Start ();
  805. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  806. req.Method = "POST";
  807. req.AllowAutoRedirect = false;
  808. req.Timeout = 1000;
  809. req.ReadWriteTimeout = 1000;
  810. req.KeepAlive = false;
  811. Stream rs = req.GetRequestStream ();
  812. rs.Close ();
  813. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  814. Assert.AreEqual (resp.StatusCode, HttpStatusCode.Found, "#B1");
  815. Assert.AreEqual (url, resp.ResponseUri.ToString (), "#B2");
  816. Assert.AreEqual ("POST", resp.Method, "#B3");
  817. }
  818. responder.Stop ();
  819. }
  820. }
  821. [Test] // bug #324347
  822. [Category ("NotWorking")]
  823. public void InternalServerError ()
  824. {
  825. IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8764);
  826. string url = "http://" + localEP.ToString () + "/original/";
  827. // POST
  828. using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
  829. responder.Start ();
  830. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  831. req.Method = "POST";
  832. req.Timeout = 2000;
  833. req.ReadWriteTimeout = 2000;
  834. req.KeepAlive = false;
  835. Stream rs = req.GetRequestStream ();
  836. rs.Close ();
  837. try {
  838. req.GetResponse ();
  839. Assert.Fail ("#A1");
  840. } catch (WebException ex) {
  841. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  842. Assert.IsNull (ex.InnerException, "#A3");
  843. Assert.IsNotNull (ex.Message, "#A4");
  844. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A5");
  845. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  846. Assert.IsNotNull (webResponse, "#A6");
  847. Assert.AreEqual ("POST", webResponse.Method, "#A7");
  848. webResponse.Close ();
  849. }
  850. responder.Stop ();
  851. }
  852. // GET
  853. using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
  854. responder.Start ();
  855. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  856. req.Method = "GET";
  857. req.Timeout = 2000;
  858. req.ReadWriteTimeout = 2000;
  859. req.KeepAlive = false;
  860. try {
  861. req.GetResponse ();
  862. Assert.Fail ("#B1");
  863. } catch (WebException ex) {
  864. Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
  865. Assert.IsNull (ex.InnerException, "#B3");
  866. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
  867. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  868. Assert.IsNotNull (webResponse, "#B5");
  869. Assert.AreEqual ("GET", webResponse.Method, "#B6");
  870. webResponse.Close ();
  871. }
  872. responder.Stop ();
  873. }
  874. }
  875. [Test]
  876. [Category ("NotWorking")] // #B3 fails; we get a SocketException: An existing connection was forcibly closed by the remote host
  877. public void NoContentLength ()
  878. {
  879. IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8764);
  880. string url = "http://" + localEP.ToString () + "/original/";
  881. // POST
  882. using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
  883. responder.Start ();
  884. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  885. req.Method = "POST";
  886. req.Timeout = 2000;
  887. req.ReadWriteTimeout = 2000;
  888. req.KeepAlive = false;
  889. Stream rs = req.GetRequestStream ();
  890. rs.Close ();
  891. try {
  892. req.GetResponse ();
  893. Assert.Fail ("#A1");
  894. } catch (WebException ex) {
  895. #if NET_2_0
  896. // The underlying connection was closed:
  897. // An unexpected error occurred on a
  898. // receive
  899. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  900. Assert.IsNotNull (ex.InnerException, "#A3");
  901. Assert.AreEqual (WebExceptionStatus.ReceiveFailure, ex.Status, "#A4");
  902. Assert.AreEqual (typeof (IOException), ex.InnerException.GetType (), "#A5");
  903. // Unable to read data from the transport connection:
  904. // A connection attempt failed because the connected party
  905. // did not properly respond after a period of time, or
  906. // established connection failed because connected host has
  907. // failed to respond
  908. IOException ioe = (IOException) ex.InnerException;
  909. Assert.IsNotNull (ioe.InnerException, "#A6");
  910. Assert.IsNotNull (ioe.Message, "#A7");
  911. Assert.AreEqual (typeof (SocketException), ioe.InnerException.GetType (), "#A8");
  912. // An existing connection was forcibly
  913. // closed by the remote host
  914. SocketException soe = (SocketException) ioe.InnerException;
  915. Assert.IsNull (soe.InnerException, "#A9");
  916. Assert.IsNotNull (soe.Message, "#A10");
  917. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  918. Assert.IsNull (webResponse, "#A11");
  919. #else
  920. // The remote server returned an error:
  921. // (500) Internal Server Error
  922. Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
  923. Assert.IsNull (ex.InnerException, "#A3");
  924. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A4");
  925. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  926. Assert.IsNotNull (webResponse, "#A5");
  927. Assert.AreEqual ("POST", webResponse.Method, "#A6");
  928. webResponse.Close ();
  929. #endif
  930. }
  931. responder.Stop ();
  932. }
  933. // GET
  934. using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
  935. responder.Start ();
  936. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  937. req.Method = "GET";
  938. req.Timeout = 2000;
  939. req.ReadWriteTimeout = 2000;
  940. req.KeepAlive = false;
  941. try {
  942. req.GetResponse ();
  943. Assert.Fail ("#B1");
  944. } catch (WebException ex) {
  945. // The remote server returned an error:
  946. // (500) Internal Server Error
  947. Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
  948. Assert.IsNull (ex.InnerException, "#B3");
  949. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
  950. HttpWebResponse webResponse = ex.Response as HttpWebResponse;
  951. Assert.IsNotNull (webResponse, "#B5");
  952. Assert.AreEqual ("GET", webResponse.Method, "#B6");
  953. webResponse.Close ();
  954. }
  955. responder.Stop ();
  956. }
  957. }
  958. [Test] // bug #513087
  959. public void NonStandardVerb ()
  960. {
  961. IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8000);
  962. string url = "http://" + IPAddress.Loopback.ToString () + ":8000/moved/";
  963. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (VerbEchoHandler))) {
  964. responder.Start ();
  965. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  966. req.Method = "WhatEver";
  967. req.KeepAlive = false;
  968. req.Timeout = 20000;
  969. req.ReadWriteTimeout = 20000;
  970. Stream rs = req.GetRequestStream ();
  971. rs.Close ();
  972. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  973. StreamReader sr = new StreamReader (resp.GetResponseStream (),
  974. Encoding.UTF8);
  975. string body = sr.ReadToEnd ();
  976. Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#1");
  977. Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
  978. ep.ToString () + "/moved/", "#2");
  979. Assert.AreEqual ("WhatEver", resp.Method, "#3");
  980. Assert.AreEqual ("WhatEver", body, "#4");
  981. }
  982. responder.Stop ();
  983. }
  984. }
  985. [Test]
  986. [Category ("NotWorking")] // Assert #2 fails
  987. public void NotModifiedSince ()
  988. {
  989. IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8000);
  990. string url = "http://" + IPAddress.Loopback.ToString () + ":8000/test/";
  991. using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (NotModifiedSinceHandler))) {
  992. responder.Start ();
  993. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  994. req.Method = "GET";
  995. req.KeepAlive = false;
  996. req.Timeout = 20000;
  997. req.ReadWriteTimeout = 20000;
  998. #if NET_2_0
  999. req.Headers.Add (HttpRequestHeader.IfNoneMatch, "898bbr2347056cc2e096afc66e104653");
  1000. #else
  1001. req.Headers.Add ("If-None-Match", "898bbr2347056cc2e096afc66e104653");
  1002. #endif
  1003. req.IfModifiedSince = new DateTime (2010, 01, 04);
  1004. DateTime start = DateTime.Now;
  1005. HttpWebResponse response = null;
  1006. try {
  1007. req.GetResponse ();
  1008. Assert.Fail ("#1");
  1009. } catch (WebException e) {
  1010. response = (HttpWebResponse) e.Response;
  1011. }
  1012. Assert.IsNotNull (response, "#2");
  1013. using (Stream stream = response.GetResponseStream ()) {
  1014. byte [] buffer = new byte [4096];
  1015. int bytesRead = stream.Read (buffer, 0, buffer.Length);
  1016. Assert.AreEqual (0, bytesRead, "#3");
  1017. }
  1018. TimeSpan elapsed = DateTime.Now - start;
  1019. Assert.IsTrue (elapsed.TotalMilliseconds < 2000, "#4");
  1020. responder.Stop ();
  1021. }
  1022. }
  1023. #if NET_2_0
  1024. [Test] // bug #324182
  1025. #if TARGET_JVM
  1026. [Category ("NotWorking")]
  1027. #endif
  1028. public void Stream_CanTimeout ()
  1029. {
  1030. IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8764);
  1031. string url = "http://" + localEP.ToString () + "/original/";
  1032. // allow autoredirect
  1033. using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
  1034. responder.Start ();
  1035. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
  1036. req.Method = "POST";
  1037. req.Timeout = 2000;
  1038. req.ReadWriteTimeout = 2000;
  1039. req.KeepAlive = false;
  1040. Stream rs = req.GetRequestStream ();
  1041. Assert.IsTrue (rs.CanTimeout, "#1");
  1042. rs.Close ();
  1043. using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
  1044. Stream os = resp.GetResponseStream ();
  1045. Assert.IsTrue (os.CanTimeout, "#2");
  1046. os.Close ();
  1047. }
  1048. responder.Stop ();
  1049. }
  1050. }
  1051. #endif
  1052. [Test] // bug #353495
  1053. [Category ("NotWorking")]
  1054. public void LastModifiedKind ()
  1055. {
  1056. const string reqURL = "http://coffeefaq.com/site/node/25";
  1057. HttpWebRequest req = (HttpWebRequest) WebRequest.Create (reqURL);
  1058. HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
  1059. DateTime lastMod = resp.LastModified;
  1060. string rawLastMod = resp.Headers ["Last-Modified"];
  1061. resp.Close ();
  1062. //Assert.AreEqual ("Tue, 15 Jan 2008 08:59:59 GMT", rawLastMod, "#1");
  1063. #if NET_2_0
  1064. Assert.AreEqual (DateTimeKind.Local, lastMod.Kind, "#2");
  1065. #endif
  1066. req = (HttpWebRequest) WebRequest.Create (reqURL);
  1067. req.IfModifiedSince = lastMod;
  1068. try {
  1069. resp = (HttpWebResponse) req.GetResponse ();
  1070. resp.Close ();
  1071. Assert.Fail ("Should result in 304");
  1072. } catch (WebException ex) {
  1073. Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#3");
  1074. Assert.AreEqual (((HttpWebResponse) ex.Response).StatusCode, HttpStatusCode.NotModified, "#4");
  1075. }
  1076. }
  1077. static byte [] EchoRequestHandler (Socket socket)
  1078. {
  1079. MemoryStream ms = new MemoryStream ();
  1080. byte [] buffer = new byte [4096];
  1081. int bytesReceived = socket.Receive (buffer);
  1082. while (bytesReceived > 0) {
  1083. ms.Write (buffer, 0, bytesReceived);
  1084. if (socket.Available > 0) {
  1085. bytesReceived = socket.Receive (buffer);
  1086. } else {
  1087. bytesReceived = 0;
  1088. }
  1089. }
  1090. ms.Flush ();
  1091. ms.Position = 0;
  1092. StreamReader sr = new StreamReader (ms, Encoding.UTF8);
  1093. string request = sr.ReadToEnd ();
  1094. StringWriter sw = new StringWriter ();
  1095. sw.WriteLine ("HTTP/1.1 200 OK");
  1096. sw.WriteLine ("Content-Type: text/xml");
  1097. sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
  1098. sw.WriteLine ();
  1099. sw.Write (request);
  1100. sw.Flush ();
  1101. return Encoding.UTF8.GetBytes (sw.ToString ());
  1102. }
  1103. static byte [] RedirectRequestHandler (Socket socket)
  1104. {
  1105. MemoryStream ms = new MemoryStream ();
  1106. byte [] buffer = new byte [4096];
  1107. int bytesReceived = socket.Receive (buffer);
  1108. while (bytesReceived > 0) {
  1109. ms.Write (buffer, 0, bytesReceived);
  1110. if (socket.Available > 0) {
  1111. bytesReceived = socket.Receive (buffer);
  1112. } else {
  1113. bytesReceived = 0;
  1114. }
  1115. }
  1116. ms.Flush ();
  1117. ms.Position = 0;
  1118. string statusLine = null;
  1119. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  1120. statusLine = sr.ReadLine ();
  1121. }
  1122. StringWriter sw = new StringWriter ();
  1123. if (statusLine.StartsWith ("POST /original/")) {
  1124. sw.WriteLine ("HTTP/1.0 302 Found");
  1125. sw.WriteLine ("Location: " + "http://" + IPAddress.Loopback.ToString () + ":8764/moved/");
  1126. sw.WriteLine ();
  1127. sw.Flush ();
  1128. } else if (statusLine.StartsWith ("GET /moved/")) {
  1129. sw.WriteLine ("HTTP/1.0 200 OK");
  1130. sw.WriteLine ("Content-Type: text/plain");
  1131. sw.WriteLine ("Content-Length: 8");
  1132. sw.WriteLine ();
  1133. sw.Write ("LOOKS OK");
  1134. sw.Flush ();
  1135. } else {
  1136. sw.WriteLine ("HTTP/1.0 500 Too Lazy");
  1137. sw.WriteLine ();
  1138. sw.Flush ();
  1139. }
  1140. return Encoding.UTF8.GetBytes (sw.ToString ());
  1141. }
  1142. static byte [] InternalErrorHandler (Socket socket)
  1143. {
  1144. StringWriter sw = new StringWriter ();
  1145. sw.WriteLine ("HTTP/1.1 500 Too Lazy");
  1146. sw.WriteLine ("Content-Length: 0");
  1147. sw.WriteLine ();
  1148. sw.Flush ();
  1149. return Encoding.UTF8.GetBytes (sw.ToString ());
  1150. }
  1151. static byte [] NoContentLengthHandler (Socket socket)
  1152. {
  1153. StringWriter sw = new StringWriter ();
  1154. sw.WriteLine ("HTTP/1.1 500 Too Lazy");
  1155. sw.WriteLine ();
  1156. sw.Flush ();
  1157. return Encoding.UTF8.GetBytes (sw.ToString ());
  1158. }
  1159. static byte [] NotModifiedSinceHandler (Socket socket)
  1160. {
  1161. StringWriter sw = new StringWriter ();
  1162. sw.WriteLine ("HTTP/1.1 304 Not Modified");
  1163. sw.WriteLine ("Date: Fri, 06 Feb 2009 12:50:26 GMT");
  1164. 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");
  1165. sw.WriteLine ("Not-Modified-Since: Sun, 08 Feb 2009 08:49:26 GMT");
  1166. sw.WriteLine ("ETag: 898bbr2347056cc2e096afc66e104653");
  1167. sw.WriteLine ("Connection: close");
  1168. sw.WriteLine ();
  1169. sw.Flush ();
  1170. return Encoding.UTF8.GetBytes (sw.ToString ());
  1171. }
  1172. static byte [] VerbEchoHandler (Socket socket)
  1173. {
  1174. MemoryStream ms = new MemoryStream ();
  1175. byte [] buffer = new byte [4096];
  1176. int bytesReceived = socket.Receive (buffer);
  1177. while (bytesReceived > 0) {
  1178. ms.Write (buffer, 0, bytesReceived);
  1179. if (socket.Available > 0) {
  1180. bytesReceived = socket.Receive (buffer);
  1181. } else {
  1182. bytesReceived = 0;
  1183. }
  1184. }
  1185. ms.Flush ();
  1186. ms.Position = 0;
  1187. string statusLine = null;
  1188. using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
  1189. statusLine = sr.ReadLine ();
  1190. }
  1191. string verb = "DEFAULT";
  1192. if (statusLine != null) {
  1193. string [] parts = statusLine.Split (' ');
  1194. if (parts.Length > 0)
  1195. verb = parts [0];
  1196. }
  1197. StringWriter sw = new StringWriter ();
  1198. sw.WriteLine ("HTTP/1.1 200 OK");
  1199. sw.WriteLine ("Content-Type: text/plain");
  1200. sw.WriteLine ("Content-Length: " + verb.Length);
  1201. sw.WriteLine ();
  1202. sw.Write (verb);
  1203. sw.Flush ();
  1204. return Encoding.UTF8.GetBytes (sw.ToString ());
  1205. }
  1206. [Test]
  1207. public void NtlmAuthentication ()
  1208. {
  1209. NtlmServer server = new NtlmServer ();
  1210. server.Start ();
  1211. string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
  1212. HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
  1213. request.Timeout = 5000;
  1214. request.Credentials = new NetworkCredential ("user", "password", "domain");
  1215. HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
  1216. string res = null;
  1217. using (StreamReader reader = new StreamReader (resp.GetResponseStream ())) {
  1218. res = reader.ReadToEnd ();
  1219. }
  1220. resp.Close ();
  1221. server.Stop ();
  1222. Assert.AreEqual ("OK", res);
  1223. }
  1224. class NtlmServer : HttpServer {
  1225. public string Where = "";
  1226. protected override void Run ()
  1227. {
  1228. Where = "before accept";
  1229. Socket client = sock.Accept ();
  1230. NetworkStream ns = new NetworkStream (client, false);
  1231. StreamReader reader = new StreamReader (ns, Encoding.ASCII);
  1232. string line;
  1233. Where = "first read";
  1234. while ((line = reader.ReadLine ()) != null) {
  1235. if (line.Trim () == String.Empty) {
  1236. break;
  1237. }
  1238. }
  1239. Where = "first write";
  1240. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  1241. writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
  1242. "WWW-Authenticate: NTLM\r\n" +
  1243. "Content-Length: 5\r\n\r\nWRONG");
  1244. writer.Flush ();
  1245. Where = "second read";
  1246. while ((line = reader.ReadLine ()) != null) {
  1247. if (line.Trim () == String.Empty) {
  1248. break;
  1249. }
  1250. }
  1251. Where = "second write";
  1252. writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
  1253. "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAADgAAAABggAC8GDhqIONH3sAAAAAAAAAAAAAAAA4AAAABQLODgAAAA8=\r\n" +
  1254. "Content-Length: 5\r\n\r\nWRONG");
  1255. writer.Flush ();
  1256. Where = "third read";
  1257. while ((line = reader.ReadLine ()) != null) {
  1258. if (line.Trim () == String.Empty) {
  1259. break;
  1260. }
  1261. }
  1262. Where = "third write";
  1263. writer.Write ( "HTTP/1.1 200 OK\r\n" +
  1264. "Keep-Alive: true\r\n" +
  1265. "Content-Length: 2\r\n\r\nOK");
  1266. writer.Flush ();
  1267. Thread.Sleep (1000);
  1268. writer.Close ();
  1269. reader.Close ();
  1270. client.Close ();
  1271. }
  1272. }
  1273. class BadChunkedServer : HttpServer {
  1274. protected override void Run ()
  1275. {
  1276. Socket client = sock.Accept ();
  1277. NetworkStream ns = new NetworkStream (client, true);
  1278. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  1279. writer.Write ( "HTTP/1.1 200 OK\r\n" +
  1280. "Transfer-Encoding: chunked\r\n" +
  1281. "Connection: close\r\n" +
  1282. "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
  1283. // This body lacks a 'last-chunk' (see RFC 2616)
  1284. writer.Write ("10\r\n1234567890123456\r\n");
  1285. writer.Flush ();
  1286. client.Shutdown (SocketShutdown.Send);
  1287. Thread.Sleep (1000);
  1288. writer.Close ();
  1289. }
  1290. }
  1291. class AcceptAllPolicy : ICertificatePolicy {
  1292. public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error)
  1293. {
  1294. return true;
  1295. }
  1296. }
  1297. abstract class HttpServer
  1298. {
  1299. protected Socket sock;
  1300. protected Exception error;
  1301. protected ManualResetEvent evt;
  1302. public HttpServer ()
  1303. {
  1304. sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  1305. sock.Bind (new IPEndPoint (IPAddress.Loopback, 0));
  1306. sock.Listen (1);
  1307. }
  1308. public void Start ()
  1309. {
  1310. evt = new ManualResetEvent (false);
  1311. Thread th = new Thread (new ThreadStart (Run));
  1312. th.Start ();
  1313. }
  1314. public void Stop ()
  1315. {
  1316. evt.Set ();
  1317. sock.Close ();
  1318. }
  1319. public IPAddress IPAddress {
  1320. get { return ((IPEndPoint) sock.LocalEndPoint).Address; }
  1321. }
  1322. public int Port {
  1323. get { return ((IPEndPoint) sock.LocalEndPoint).Port; }
  1324. }
  1325. public Exception Error {
  1326. get { return error; }
  1327. }
  1328. protected abstract void Run ();
  1329. }
  1330. #if NET_2_0
  1331. [Test]
  1332. public void BeginGetRequestStream()
  1333. {
  1334. this.DoRequest(
  1335. (r, c) =>
  1336. {
  1337. r.Method = "POST";
  1338. r.ContentLength = 0;
  1339. r.BeginGetRequestStream((a) =>
  1340. {
  1341. using (Stream s = r.EndGetRequestStream(a)) { };
  1342. c.Set();
  1343. },
  1344. null);
  1345. },
  1346. (c) => { });
  1347. }
  1348. [Test]
  1349. public void BeginGetRequestStreamNoClose()
  1350. {
  1351. this.DoRequest(
  1352. (r, c) => {
  1353. r.Method = "POST";
  1354. r.ContentLength = 1;
  1355. r.BeginGetRequestStream((a) =>
  1356. {
  1357. r.EndGetRequestStream(a);
  1358. c.Set();
  1359. },
  1360. null);
  1361. },
  1362. (c) => {});
  1363. }
  1364. [Test]
  1365. public void BeginGetRequestStreamCancelIfNotAllBytesWritten()
  1366. {
  1367. this.DoRequest(
  1368. (r, c) =>
  1369. {
  1370. r.Method = "POST";
  1371. r.ContentLength = 10;
  1372. r.BeginGetRequestStream((a) =>
  1373. {
  1374. WebException ex = ExceptionAssert.Throws<WebException>(() =>
  1375. { using (Stream s = r.EndGetRequestStream(a)) { }; }
  1376. );
  1377. Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
  1378. c.Set();
  1379. },
  1380. null);
  1381. },
  1382. (c) => { });
  1383. }
  1384. [Test]
  1385. public void GetRequestStream2()
  1386. {
  1387. this.DoRequest(
  1388. (r, c) =>
  1389. {
  1390. r.Method = "POST";
  1391. r.ContentLength = data64KB.Length;
  1392. using (Stream s = r.GetRequestStream())
  1393. {
  1394. s.Write(data64KB, 0, data64KB.Length);
  1395. }
  1396. c.Set();
  1397. },
  1398. (c) => { });
  1399. }
  1400. [Test]
  1401. public void GetRequestStreamNotAllBytesWritten()
  1402. {
  1403. this.DoRequest(
  1404. (r, c) =>
  1405. {
  1406. r.Method = "POST";
  1407. r.ContentLength = data64KB.Length;
  1408. WebException ex = ExceptionAssert.Throws<WebException>(() => r.GetRequestStream().Close());
  1409. Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
  1410. c.Set();
  1411. },
  1412. (c) => {});
  1413. }
  1414. [Test]
  1415. public void GetRequestStreamTimeout()
  1416. {
  1417. this.DoRequest(
  1418. (r, c) =>
  1419. {
  1420. r.Method = "POST";
  1421. r.ContentLength = data64KB.Length;
  1422. r.Timeout = 100;
  1423. WebException ex = ExceptionAssert.Throws<WebException>(() => r.GetRequestStream());
  1424. Assert.IsTrue(ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure);
  1425. c.Set();
  1426. });
  1427. }
  1428. [Test]
  1429. public void BeginWrite()
  1430. {
  1431. byte[] received = new byte[data64KB.Length];
  1432. this.DoRequest(
  1433. (r, c) =>
  1434. {
  1435. r.Method = "POST";
  1436. r.ContentLength = data64KB.Length;
  1437. Stream s = r.GetRequestStream();
  1438. s.BeginWrite(data64KB, 0, data64KB.Length,
  1439. (a) =>
  1440. {
  1441. s.EndWrite(a);
  1442. s.Close();
  1443. r.GetResponse().Close();
  1444. c.Set();
  1445. },
  1446. null);
  1447. },
  1448. (c) =>
  1449. {
  1450. c.Request.InputStream.ReadAll(received, 0, received.Length);
  1451. c.Response.StatusCode = 204;
  1452. c.Response.Close();
  1453. });
  1454. Assert.AreEqual(data64KB, received);
  1455. }
  1456. [Test]
  1457. public void BeginWriteAfterAbort()
  1458. {
  1459. byte[] received = new byte[data64KB.Length];
  1460. this.DoRequest(
  1461. (r, c) =>
  1462. {
  1463. r.Method = "POST";
  1464. r.ContentLength = data64KB.Length;
  1465. Stream s = r.GetRequestStream();
  1466. r.Abort();
  1467. WebException ex = ExceptionAssert.Throws<WebException>(() => s.BeginWrite(data64KB, 0, data64KB.Length, null, null));
  1468. Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
  1469. c.Set();
  1470. },
  1471. (c) =>
  1472. {
  1473. c.Request.InputStream.ReadAll(received, 0, received.Length);
  1474. c.Response.StatusCode = 204;
  1475. c.Response.Close();
  1476. });
  1477. }
  1478. [Test]
  1479. public void PrematureStreamCloseAborts()
  1480. {
  1481. byte[] received = new byte[data64KB.Length];
  1482. this.DoRequest(
  1483. (r, c) =>
  1484. {
  1485. r.Method = "POST";
  1486. r.ContentLength = data64KB.Length * 2;
  1487. Stream s = r.GetRequestStream();
  1488. s.Write(data64KB, 0, data64KB.Length);
  1489. WebException ex = ExceptionAssert.Throws<WebException>(() => s.Close());
  1490. Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
  1491. c.Set();
  1492. },
  1493. (c) =>
  1494. {
  1495. c.Request.InputStream.ReadAll(received, 0, received.Length);
  1496. c.Response.StatusCode = 204;
  1497. c.Response.Close();
  1498. });
  1499. }
  1500. [Test]
  1501. public void Write()
  1502. {
  1503. byte[] received = new byte[data64KB.Length];
  1504. this.DoRequest(
  1505. (r, c) =>
  1506. {
  1507. r.Method = "POST";
  1508. r.ContentLength = data64KB.Length;
  1509. using (Stream s = r.GetRequestStream())
  1510. {
  1511. s.Write(data64KB, 0, data64KB.Length);
  1512. }
  1513. r.GetResponse().Close();
  1514. c.Set();
  1515. },
  1516. (c) =>
  1517. {
  1518. c.Request.InputStream.ReadAll(received, 0, received.Length);
  1519. c.Response.StatusCode = 204;
  1520. c.Response.Close();
  1521. });
  1522. Assert.AreEqual(data64KB, received);
  1523. }
  1524. [Test]
  1525. public void WriteServerAborts()
  1526. {
  1527. ManualResetEvent abort = new ManualResetEvent(false);
  1528. byte[] received = new byte[data64KB.Length];
  1529. this.DoRequest(
  1530. (r, c) =>
  1531. {
  1532. r.Method = "POST";
  1533. r.ContentLength = data64KB.Length;
  1534. using (Stream s = r.GetRequestStream())
  1535. {
  1536. abort.Set();
  1537. Thread.Sleep(100);
  1538. IOException ex = ExceptionAssert.Throws<IOException>(() => s.Write(data64KB, 0, data64KB.Length));
  1539. }
  1540. c.Set();
  1541. },
  1542. (c) =>
  1543. {
  1544. abort.WaitOne();
  1545. c.Response.Abort();
  1546. });
  1547. }
  1548. [Test]
  1549. public void Read()
  1550. {
  1551. byte[] received = new byte[data64KB.Length];
  1552. this.DoRequest(
  1553. (r, c) =>
  1554. {
  1555. using (HttpWebResponse x = (HttpWebResponse)r.GetResponse())
  1556. using (Stream s = x.GetResponseStream())
  1557. {
  1558. s.ReadAll(received, 0, received.Length);
  1559. }
  1560. c.Set();
  1561. },
  1562. (c) =>
  1563. {
  1564. c.Response.StatusCode = 200;
  1565. c.Response.ContentLength64 = data64KB.Length;
  1566. c.Response.OutputStream.Write(data64KB, 0, data64KB.Length);
  1567. c.Response.OutputStream.Close();
  1568. c.Response.Close();
  1569. });
  1570. Assert.AreEqual(data64KB, received);
  1571. }
  1572. [Test]
  1573. public void ReadTimeout2()
  1574. {
  1575. byte[] received = new byte[data64KB.Length];
  1576. this.DoRequest(
  1577. (r, c) =>
  1578. {
  1579. r.ReadWriteTimeout = 10;
  1580. using (HttpWebResponse x = (HttpWebResponse)r.GetResponse())
  1581. using (Stream s = x.GetResponseStream())
  1582. {
  1583. WebException ex = ExceptionAssert.Throws<WebException>(
  1584. () => s.ReadAll(received, 0, received.Length));
  1585. Assert.AreEqual(ex.Status, WebExceptionStatus.Timeout);
  1586. }
  1587. c.Set();
  1588. },
  1589. (c) =>
  1590. {
  1591. c.Response.StatusCode = 200;
  1592. c.Response.ContentLength64 = data64KB.Length;
  1593. c.Response.OutputStream.Write(data64KB, 0, data64KB.Length / 2);
  1594. Thread.Sleep(1000);
  1595. c.Response.OutputStream.Write(data64KB, data64KB.Length / 2, data64KB.Length / 2);
  1596. c.Response.OutputStream.Close();
  1597. c.Response.Close();
  1598. });
  1599. }
  1600. [Test]
  1601. public void ReadServerAborted()
  1602. {
  1603. byte[] received = new byte[data64KB.Length];
  1604. this.DoRequest(
  1605. (r, c) =>
  1606. {
  1607. using (HttpWebResponse x = (HttpWebResponse)r.GetResponse())
  1608. using (Stream s = x.GetResponseStream())
  1609. {
  1610. Assert.AreEqual(1, s.ReadAll(received, 0, received.Length));
  1611. }
  1612. c.Set();
  1613. },
  1614. (c) =>
  1615. {
  1616. c.Response.StatusCode = 200;
  1617. c.Response.ContentLength64 = data64KB.Length;
  1618. c.Response.OutputStream.Write(data64KB, 0, 1);
  1619. c.Response.Abort();
  1620. });
  1621. }
  1622. [Test]
  1623. public void BeginGetResponse2()
  1624. {
  1625. byte[] received = new byte[data64KB.Length];
  1626. this.DoRequest(
  1627. (r, c) =>
  1628. {
  1629. r.BeginGetResponse((a) =>
  1630. {
  1631. using (HttpWebResponse x = (HttpWebResponse)r.EndGetResponse(a))
  1632. using (Stream s = x.GetResponseStream())
  1633. {
  1634. s.ReadAll(received, 0, received.Length);
  1635. }
  1636. c.Set();
  1637. }, null);
  1638. },
  1639. (c) =>
  1640. {
  1641. c.Response.StatusCode = 200;
  1642. c.Response.ContentLength64 = data64KB.Length;
  1643. c.Response.OutputStream.Write(data64KB, 0, data64KB.Length);
  1644. c.Response.OutputStream.Close();
  1645. c.Response.Close();
  1646. });
  1647. Assert.AreEqual(data64KB, received);
  1648. }
  1649. [Test]
  1650. public void BeginGetResponseAborts()
  1651. {
  1652. ManualResetEvent aborted = new ManualResetEvent(false);
  1653. this.DoRequest(
  1654. (r, c) =>
  1655. {
  1656. r.BeginGetResponse((a) =>
  1657. {
  1658. WebException ex = ExceptionAssert.Throws<WebException>(() => r.EndGetResponse(a));
  1659. Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
  1660. c.Set();
  1661. }, null);
  1662. aborted.WaitOne();
  1663. r.Abort();
  1664. },
  1665. (c) =>
  1666. {
  1667. aborted.Set();
  1668. c.Response.StatusCode = 200;
  1669. c.Response.ContentLength64 = 0;
  1670. c.Response.Close();
  1671. });
  1672. }
  1673. private void DoRequest(Action<HttpWebRequest, EventWaitHandle> request)
  1674. {
  1675. int port = rand.Next(20000, 65535);
  1676. ManualResetEvent completed = new ManualResetEvent(false);
  1677. Uri address = new Uri(string.Format("http://localhost:{0}", port));
  1678. HttpWebRequest client = (HttpWebRequest)WebRequest.Create(address);
  1679. request(client, completed);
  1680. if (!completed.WaitOne(10000))
  1681. {
  1682. Assert.Fail("Test hung");
  1683. }
  1684. }
  1685. private void DoRequest(Action<HttpWebRequest, EventWaitHandle> request, Action<HttpListenerContext> processor)
  1686. {
  1687. int port = rand.Next(20000, 65535);
  1688. ManualResetEvent[] completed = new ManualResetEvent[2];
  1689. completed[0] = new ManualResetEvent(false);
  1690. completed[1] = new ManualResetEvent(false);
  1691. using (ListenerScope scope = new ListenerScope(processor, port, completed[0]))
  1692. {
  1693. ManualResetEvent clientCompleted = new ManualResetEvent(false);
  1694. Uri address = new Uri(string.Format("http://localhost:{0}", port));
  1695. HttpWebRequest client = (HttpWebRequest)WebRequest.Create(address);
  1696. ThreadPool.QueueUserWorkItem((o) => request(client, completed[1]));
  1697. if (!WaitHandle.WaitAll(completed, 10000))
  1698. {
  1699. Assert.Fail("Test hung.");
  1700. }
  1701. }
  1702. }
  1703. private class ListenerScope : IDisposable
  1704. {
  1705. EventWaitHandle completed;
  1706. public HttpListener listener;
  1707. Action<HttpListenerContext> processor;
  1708. public ListenerScope(Action<HttpListenerContext> processor, int port, EventWaitHandle completed)
  1709. {
  1710. this.processor = processor;
  1711. this.completed = completed;
  1712. this.listener = new HttpListener();
  1713. this.listener.Prefixes.Add(string.Format("http://localhost:{0}/", port));
  1714. this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  1715. this.listener.Start();
  1716. this.listener.BeginGetContext(this.RequestHandler, null);
  1717. }
  1718. private void RequestHandler(IAsyncResult result)
  1719. {
  1720. HttpListenerContext context = null;
  1721. try
  1722. {
  1723. context = this.listener.EndGetContext(result);
  1724. }
  1725. catch (HttpListenerException ex)
  1726. {
  1727. // check if the thread has been aborted as in the case when we are shutting down.
  1728. if (ex.ErrorCode == 995)
  1729. {
  1730. return;
  1731. }
  1732. }
  1733. catch (ObjectDisposedException)
  1734. {
  1735. return;
  1736. }
  1737. ThreadPool.QueueUserWorkItem(
  1738. (o) => { try { this.processor(context); } catch (HttpListenerException) {} });
  1739. this.completed.Set();
  1740. }
  1741. public void Dispose()
  1742. {
  1743. this.listener.Stop();
  1744. }
  1745. }
  1746. #endif
  1747. #if !TARGET_JVM
  1748. class SslHttpServer : HttpServer {
  1749. X509Certificate _certificate;
  1750. protected override void Run ()
  1751. {
  1752. try {
  1753. Socket client = sock.Accept ();
  1754. NetworkStream ns = new NetworkStream (client, true);
  1755. SslServerStream s = new SslServerStream (ns, Certificate, false, false);
  1756. s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
  1757. StreamReader reader = new StreamReader (s);
  1758. StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
  1759. string line;
  1760. string hello = "<html><body><h1>Hello World!</h1></body></html>";
  1761. string answer = "HTTP/1.0 200\r\n" +
  1762. "Connection: close\r\n" +
  1763. "Content-Type: text/html\r\n" +
  1764. "Content-Encoding: " + Encoding.ASCII.WebName + "\r\n" +
  1765. "Content-Length: " + hello.Length + "\r\n" +
  1766. "\r\n" + hello;
  1767. // Read the headers
  1768. do {
  1769. line = reader.ReadLine ();
  1770. } while (line != "" && line != null && line.Length > 0);
  1771. // Now the content. We know it's 100 bytes.
  1772. // This makes BeginRead in sslclientstream block.
  1773. char [] cs = new char [100];
  1774. reader.Read (cs, 0, 100);
  1775. writer.Write (answer);
  1776. writer.Flush ();
  1777. evt.WaitOne (50000, false);
  1778. } catch (Exception e) {
  1779. error = e;
  1780. }
  1781. }
  1782. X509Certificate Certificate {
  1783. get {
  1784. if (_certificate == null)
  1785. _certificate = new X509Certificate (CertData.Certificate);
  1786. return _certificate;
  1787. }
  1788. }
  1789. AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost)
  1790. {
  1791. PrivateKey key = new PrivateKey (CertData.PrivateKey, null);
  1792. return key.RSA;
  1793. }
  1794. }
  1795. class CertData {
  1796. public readonly static byte [] Certificate = {
  1797. 48, 130, 1, 191, 48, 130, 1, 40, 160, 3, 2, 1, 2, 2, 16, 36,
  1798. 14, 97, 190, 146, 132, 208, 71, 175, 6, 87, 168, 185, 175, 55, 43, 48,
  1799. 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 48, 18,
  1800. 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103, 111, 110, 122, 97,
  1801. 108, 111, 48, 30, 23, 13, 48, 53, 48, 54, 50, 50, 49, 57, 51, 48,
  1802. 52, 54, 90, 23, 13, 51, 57, 49, 50, 51, 49, 50, 51, 53, 57, 53,
  1803. 57, 90, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103,
  1804. 111, 110, 122, 97, 108, 111, 48, 129, 158, 48, 13, 6, 9, 42, 134, 72,
  1805. 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 140, 0, 48, 129, 136, 2,
  1806. 129, 129, 0, 138, 9, 38, 25, 166, 252, 59, 26, 39, 184, 128, 216, 38,
  1807. 73, 41, 86, 30, 228, 160, 205, 41, 135, 115, 223, 44, 62, 42, 198, 178,
  1808. 190, 81, 11, 25, 21, 216, 49, 179, 130, 246, 52, 97, 175, 212, 94, 157,
  1809. 231, 162, 66, 161, 103, 63, 204, 83, 141, 172, 119, 97, 225, 206, 98, 101,
  1810. 210, 106, 2, 206, 81, 90, 173, 47, 41, 199, 209, 241, 177, 177, 96, 207,
  1811. 254, 220, 190, 66, 180, 153, 0, 209, 14, 178, 69, 194, 3, 37, 116, 239,
  1812. 49, 23, 185, 245, 255, 126, 35, 85, 246, 56, 244, 107, 117, 24, 14, 57,
  1813. 9, 111, 147, 189, 220, 142, 57, 104, 153, 193, 205, 19, 14, 22, 157, 16,
  1814. 24, 80, 201, 2, 2, 0, 17, 163, 23, 48, 21, 48, 19, 6, 3, 85,
  1815. 29, 37, 4, 12, 48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1,
  1816. 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 3,
  1817. 129, 129, 0, 64, 49, 57, 253, 218, 198, 229, 51, 189, 12, 154, 225, 183,
  1818. 160, 147, 90, 113, 172, 69, 122, 28, 77, 97, 215, 231, 194, 150, 29, 196,
  1819. 65, 95, 218, 99, 142, 111, 79, 205, 109, 76, 32, 92, 220, 76, 88, 53,
  1820. 237, 80, 11, 85, 44, 91, 21, 210, 12, 34, 223, 234, 18, 187, 136, 62,
  1821. 26, 240, 103, 180, 12, 226, 221, 250, 247, 129, 51, 23, 129, 165, 56, 67,
  1822. 43, 83, 244, 110, 207, 24, 253, 195, 16, 46, 80, 113, 80, 18, 2, 254,
  1823. 120, 147, 151, 164, 23, 210, 230, 100, 19, 197, 179, 28, 194, 48, 106, 159,
  1824. 155, 144, 37, 82, 44, 160, 40, 52, 146, 174, 77, 188, 160, 230, 75, 172,
  1825. 123, 3, 254,
  1826. };
  1827. public readonly static byte [] PrivateKey = {
  1828. 30, 241, 181, 176, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
  1829. 0, 0, 0, 0, 84, 2, 0, 0, 7, 2, 0, 0, 0, 36, 0, 0,
  1830. 82, 83, 65, 50, 0, 4, 0, 0, 17, 0, 0, 0, 201, 80, 24, 16,
  1831. 157, 22, 14, 19, 205, 193, 153, 104, 57, 142, 220, 189, 147, 111, 9, 57,
  1832. 14, 24, 117, 107, 244, 56, 246, 85, 35, 126, 255, 245, 185, 23, 49, 239,
  1833. 116, 37, 3, 194, 69, 178, 14, 209, 0, 153, 180, 66, 190, 220, 254, 207,
  1834. 96, 177, 177, 241, 209, 199, 41, 47, 173, 90, 81, 206, 2, 106, 210, 101,
  1835. 98, 206, 225, 97, 119, 172, 141, 83, 204, 63, 103, 161, 66, 162, 231, 157,
  1836. 94, 212, 175, 97, 52, 246, 130, 179, 49, 216, 21, 25, 11, 81, 190, 178,
  1837. 198, 42, 62, 44, 223, 115, 135, 41, 205, 160, 228, 30, 86, 41, 73, 38,
  1838. 216, 128, 184, 39, 26, 59, 252, 166, 25, 38, 9, 138, 175, 88, 190, 223,
  1839. 27, 24, 224, 123, 190, 69, 164, 234, 129, 59, 108, 229, 248, 62, 187, 15,
  1840. 235, 147, 162, 83, 47, 123, 170, 190, 224, 31, 215, 110, 143, 31, 227, 216,
  1841. 85, 88, 154, 83, 207, 229, 41, 28, 237, 116, 181, 17, 37, 141, 224, 185,
  1842. 164, 144, 141, 233, 164, 138, 177, 241, 115, 181, 230, 150, 7, 92, 139, 141,
  1843. 113, 95, 57, 191, 211, 165, 217, 250, 197, 68, 164, 184, 168, 43, 48, 65,
  1844. 177, 237, 173, 144, 148, 221, 62, 189, 147, 63, 216, 188, 206, 103, 226, 171,
  1845. 32, 20, 230, 116, 144, 192, 1, 39, 202, 87, 74, 250, 6, 142, 188, 23,
  1846. 45, 4, 112, 191, 253, 67, 69, 70, 128, 143, 44, 234, 41, 96, 195, 82,
  1847. 202, 35, 158, 149, 240, 151, 23, 25, 166, 179, 85, 144, 58, 120, 149, 229,
  1848. 205, 34, 8, 110, 86, 119, 130, 210, 37, 173, 65, 71, 169, 67, 8, 51,
  1849. 20, 96, 51, 155, 3, 39, 85, 187, 40, 193, 57, 19, 99, 78, 173, 28,
  1850. 129, 154, 108, 175, 8, 138, 237, 71, 27, 148, 129, 35, 47, 57, 101, 237,
  1851. 168, 178, 227, 221, 212, 63, 124, 254, 253, 215, 183, 159, 49, 103, 74, 49,
  1852. 67, 160, 171, 72, 194, 215, 108, 251, 178, 18, 184, 100, 211, 105, 21, 186,
  1853. 39, 66, 218, 154, 72, 222, 90, 237, 179, 251, 51, 224, 212, 56, 251, 6,
  1854. 209, 151, 198, 176, 89, 110, 35, 141, 248, 237, 223, 68, 135, 206, 207, 169,
  1855. 254, 219, 243, 130, 71, 11, 94, 113, 233, 92, 63, 156, 169, 72, 215, 110,
  1856. 95, 94, 191, 50, 59, 89, 187, 59, 183, 99, 161, 146, 233, 245, 219, 80,
  1857. 87, 113, 251, 50, 144, 195, 158, 46, 189, 232, 119, 91, 75, 22, 6, 176,
  1858. 39, 206, 25, 196, 213, 195, 219, 24, 28, 103, 104, 36, 137, 128, 4, 119,
  1859. 163, 40, 126, 87, 18, 86, 128, 243, 213, 101, 2, 237, 78, 64, 160, 55,
  1860. 199, 93, 90, 126, 175, 199, 55, 89, 234, 190, 5, 16, 196, 88, 28, 208,
  1861. 28, 92, 32, 115, 204, 9, 202, 101, 15, 123, 43, 75, 90, 144, 95, 179,
  1862. 102, 249, 57, 150, 204, 99, 147, 203, 16, 63, 81, 244, 226, 237, 82, 204,
  1863. 20, 200, 140, 65, 83, 217, 161, 23, 123, 37, 115, 12, 100, 73, 70, 190,
  1864. 32, 235, 174, 140, 148, 157, 47, 238, 40, 208, 228, 80, 54, 187, 156, 252,
  1865. 253, 230, 231, 156, 138, 125, 96, 79, 3, 27, 143, 55, 146, 169, 165, 61,
  1866. 238, 60, 227, 77, 217, 93, 117, 122, 111, 46, 173, 113,
  1867. };
  1868. }
  1869. #endif
  1870. }
  1871. #if NET_2_0
  1872. public static class StreamExtensions
  1873. {
  1874. public static int ReadAll(this Stream stream, byte[] buffer, int offset, int count)
  1875. {
  1876. int totalRead = 0;
  1877. while (totalRead < count)
  1878. {
  1879. int bytesRead = stream.Read(buffer, offset + totalRead, count - totalRead);
  1880. if (bytesRead == 0)
  1881. {
  1882. break;
  1883. }
  1884. totalRead += bytesRead;
  1885. }
  1886. return totalRead;
  1887. }
  1888. }
  1889. public class ExceptionAssert
  1890. {
  1891. /// <summary>
  1892. /// Asserts that the function throws an exception.
  1893. /// </summary>
  1894. /// <param name="f">A function execute that is expected to raise an exception.</param>
  1895. /// <typeparam name="T">The type of exception that is expected.</typeparam>
  1896. /// <returns>The exception thrown.</returns>
  1897. /// <exception cref="AssertFailedException">If the function does not throw an exception
  1898. /// or throws a different exception.</exception>
  1899. /// <example><![CDATA[
  1900. /// ExceptionAssert.Throws(typeof(ArgumentNullException), delegate {
  1901. /// myObject.myFunction(null); });
  1902. /// ]]></example>
  1903. public static T Throws<T>(Action f) where T : Exception
  1904. {
  1905. Exception actualException = null;
  1906. try
  1907. {
  1908. f();
  1909. }
  1910. catch (Exception ex)
  1911. {
  1912. actualException = ex;
  1913. }
  1914. if (actualException == null)
  1915. {
  1916. throw new AssertionException(string.Format(
  1917. "No exception thrown. Expected '{0}'",
  1918. typeof(T).FullName));
  1919. }
  1920. else if (typeof(T) != actualException.GetType())
  1921. {
  1922. throw new AssertionException(string.Format(
  1923. "Caught exception of type '{0}'. Expected '{1}':{2}",
  1924. actualException.GetType().FullName,
  1925. typeof(T).FullName,
  1926. Environment.NewLine + actualException));
  1927. }
  1928. return (T)actualException;
  1929. }
  1930. }
  1931. #endif
  1932. }