2
0

HttpWebRequestTest.cs 108 KB

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