2
0

WebConnectionStream.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. //
  2. // System.Net.WebConnectionStream
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  8. // (C) 2004 Novell, Inc (http://www.novell.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.IO;
  31. using System.Text;
  32. using System.Threading;
  33. namespace System.Net
  34. {
  35. class WebConnectionStream : Stream
  36. {
  37. static byte [] crlf = new byte [] { 13, 10 };
  38. bool isRead;
  39. WebConnection cnc;
  40. HttpWebRequest request;
  41. byte [] readBuffer;
  42. int readBufferOffset;
  43. int readBufferSize;
  44. int stream_length; // -1 when CL not present
  45. int contentLength;
  46. int totalRead;
  47. internal long totalWritten;
  48. bool nextReadCalled;
  49. int pendingReads;
  50. int pendingWrites;
  51. ManualResetEvent pending;
  52. bool allowBuffering;
  53. bool sendChunked;
  54. MemoryStream writeBuffer;
  55. bool requestWritten;
  56. byte [] headers;
  57. bool disposed;
  58. bool headersSent;
  59. object locker = new object ();
  60. bool initRead;
  61. bool read_eof;
  62. bool complete_request_written;
  63. int read_timeout;
  64. int write_timeout;
  65. AsyncCallback cb_wrapper; // Calls to ReadCallbackWrapper or WriteCallbacWrapper
  66. internal bool IgnoreIOErrors;
  67. public WebConnectionStream (WebConnection cnc, WebConnectionData data)
  68. {
  69. if (data == null)
  70. throw new InvalidOperationException ("data was not initialized");
  71. if (data.Headers == null)
  72. throw new InvalidOperationException ("data.Headers was not initialized");
  73. if (data.request == null)
  74. throw new InvalidOperationException ("data.request was not initialized");
  75. isRead = true;
  76. cb_wrapper = new AsyncCallback (ReadCallbackWrapper);
  77. pending = new ManualResetEvent (true);
  78. this.request = data.request;
  79. read_timeout = request.ReadWriteTimeout;
  80. write_timeout = read_timeout;
  81. this.cnc = cnc;
  82. string contentType = data.Headers ["Transfer-Encoding"];
  83. bool chunkedRead = (contentType != null && contentType.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
  84. string clength = data.Headers ["Content-Length"];
  85. if (!chunkedRead && clength != null && clength != "") {
  86. try {
  87. contentLength = Int32.Parse (clength);
  88. if (contentLength == 0 && !IsNtlmAuth ()) {
  89. ReadAll ();
  90. }
  91. } catch {
  92. contentLength = Int32.MaxValue;
  93. }
  94. } else {
  95. contentLength = Int32.MaxValue;
  96. }
  97. // Negative numbers?
  98. if (!Int32.TryParse (clength, out stream_length))
  99. stream_length = -1;
  100. }
  101. public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
  102. {
  103. read_timeout = request.ReadWriteTimeout;
  104. write_timeout = read_timeout;
  105. isRead = false;
  106. cb_wrapper = new AsyncCallback (WriteCallbackWrapper);
  107. this.cnc = cnc;
  108. this.request = request;
  109. allowBuffering = request.InternalAllowBuffering;
  110. sendChunked = request.SendChunked;
  111. if (sendChunked)
  112. pending = new ManualResetEvent (true);
  113. else if (allowBuffering)
  114. writeBuffer = new MemoryStream ();
  115. }
  116. bool CheckAuthHeader (string headerName)
  117. {
  118. var authHeader = cnc.Data.Headers [headerName];
  119. return (authHeader != null && authHeader.IndexOf ("NTLM", StringComparison.Ordinal) != -1);
  120. }
  121. bool IsNtlmAuth ()
  122. {
  123. bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.Address));
  124. if (isProxy && CheckAuthHeader ("Proxy-Authenticate"))
  125. return true;
  126. return CheckAuthHeader ("WWW-Authenticate");
  127. }
  128. internal void CheckResponseInBuffer ()
  129. {
  130. if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
  131. if (!IsNtlmAuth ())
  132. ReadAll ();
  133. }
  134. }
  135. internal HttpWebRequest Request {
  136. get { return request; }
  137. }
  138. internal WebConnection Connection {
  139. get { return cnc; }
  140. }
  141. public override bool CanTimeout {
  142. get { return true; }
  143. }
  144. public override int ReadTimeout {
  145. get {
  146. return read_timeout;
  147. }
  148. set {
  149. if (value < -1)
  150. throw new ArgumentOutOfRangeException ("value");
  151. read_timeout = value;
  152. }
  153. }
  154. public override int WriteTimeout {
  155. get {
  156. return write_timeout;
  157. }
  158. set {
  159. if (value < -1)
  160. throw new ArgumentOutOfRangeException ("value");
  161. write_timeout = value;
  162. }
  163. }
  164. internal bool CompleteRequestWritten {
  165. get { return complete_request_written; }
  166. }
  167. internal bool SendChunked {
  168. set { sendChunked = value; }
  169. }
  170. internal byte [] ReadBuffer {
  171. set { readBuffer = value; }
  172. }
  173. internal int ReadBufferOffset {
  174. set { readBufferOffset = value; }
  175. }
  176. internal int ReadBufferSize {
  177. set { readBufferSize = value; }
  178. }
  179. internal byte[] WriteBuffer {
  180. get { return writeBuffer.GetBuffer (); }
  181. }
  182. internal int WriteBufferLength {
  183. get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
  184. }
  185. internal void ForceCompletion ()
  186. {
  187. if (!nextReadCalled) {
  188. if (contentLength == Int32.MaxValue)
  189. contentLength = 0;
  190. nextReadCalled = true;
  191. cnc.NextRead ();
  192. }
  193. }
  194. internal void CheckComplete ()
  195. {
  196. bool nrc = nextReadCalled;
  197. if (!nrc && readBufferSize - readBufferOffset == contentLength) {
  198. nextReadCalled = true;
  199. cnc.NextRead ();
  200. }
  201. }
  202. internal void ReadAll ()
  203. {
  204. if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
  205. if (isRead && !nextReadCalled) {
  206. nextReadCalled = true;
  207. cnc.NextRead ();
  208. }
  209. return;
  210. }
  211. pending.WaitOne ();
  212. lock (locker) {
  213. if (totalRead >= contentLength)
  214. return;
  215. byte [] b = null;
  216. int diff = readBufferSize - readBufferOffset;
  217. int new_size;
  218. if (contentLength == Int32.MaxValue) {
  219. MemoryStream ms = new MemoryStream ();
  220. byte [] buffer = null;
  221. if (readBuffer != null && diff > 0) {
  222. ms.Write (readBuffer, readBufferOffset, diff);
  223. if (readBufferSize >= 8192)
  224. buffer = readBuffer;
  225. }
  226. if (buffer == null)
  227. buffer = new byte [8192];
  228. int read;
  229. while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
  230. ms.Write (buffer, 0, read);
  231. b = ms.GetBuffer ();
  232. new_size = (int) ms.Length;
  233. contentLength = new_size;
  234. } else {
  235. new_size = contentLength - totalRead;
  236. b = new byte [new_size];
  237. if (readBuffer != null && diff > 0) {
  238. if (diff > new_size)
  239. diff = new_size;
  240. Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
  241. }
  242. int remaining = new_size - diff;
  243. int r = -1;
  244. while (remaining > 0 && r != 0) {
  245. r = cnc.Read (request, b, diff, remaining);
  246. remaining -= r;
  247. diff += r;
  248. }
  249. }
  250. readBuffer = b;
  251. readBufferOffset = 0;
  252. readBufferSize = new_size;
  253. totalRead = 0;
  254. nextReadCalled = true;
  255. }
  256. cnc.NextRead ();
  257. }
  258. void WriteCallbackWrapper (IAsyncResult r)
  259. {
  260. WebAsyncResult result = r as WebAsyncResult;
  261. if (result != null && result.AsyncWriteAll)
  262. return;
  263. if (r.AsyncState != null) {
  264. result = (WebAsyncResult) r.AsyncState;
  265. result.InnerAsyncResult = r;
  266. result.DoCallback ();
  267. } else {
  268. try {
  269. EndWrite (r);
  270. } catch {
  271. }
  272. }
  273. }
  274. void ReadCallbackWrapper (IAsyncResult r)
  275. {
  276. WebAsyncResult result;
  277. if (r.AsyncState != null) {
  278. result = (WebAsyncResult) r.AsyncState;
  279. result.InnerAsyncResult = r;
  280. result.DoCallback ();
  281. } else {
  282. try {
  283. EndRead (r);
  284. } catch {
  285. }
  286. }
  287. }
  288. public override int Read (byte [] buffer, int offset, int size)
  289. {
  290. AsyncCallback cb = cb_wrapper;
  291. WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
  292. if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
  293. nextReadCalled = true;
  294. cnc.Close (true);
  295. throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
  296. }
  297. return EndRead (res);
  298. }
  299. public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
  300. AsyncCallback cb, object state)
  301. {
  302. if (!isRead)
  303. throw new NotSupportedException ("this stream does not allow reading");
  304. if (buffer == null)
  305. throw new ArgumentNullException ("buffer");
  306. int length = buffer.Length;
  307. if (offset < 0 || length < offset)
  308. throw new ArgumentOutOfRangeException ("offset");
  309. if (size < 0 || (length - offset) < size)
  310. throw new ArgumentOutOfRangeException ("size");
  311. lock (locker) {
  312. pendingReads++;
  313. pending.Reset ();
  314. }
  315. WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
  316. if (totalRead >= contentLength) {
  317. result.SetCompleted (true, -1);
  318. result.DoCallback ();
  319. return result;
  320. }
  321. int remaining = readBufferSize - readBufferOffset;
  322. if (remaining > 0) {
  323. int copy = (remaining > size) ? size : remaining;
  324. Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
  325. readBufferOffset += copy;
  326. offset += copy;
  327. size -= copy;
  328. totalRead += copy;
  329. if (size == 0 || totalRead >= contentLength) {
  330. result.SetCompleted (true, copy);
  331. result.DoCallback ();
  332. return result;
  333. }
  334. result.NBytes = copy;
  335. }
  336. if (cb != null)
  337. cb = cb_wrapper;
  338. if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
  339. size = contentLength - totalRead;
  340. if (!read_eof) {
  341. result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
  342. } else {
  343. result.SetCompleted (true, result.NBytes);
  344. result.DoCallback ();
  345. }
  346. return result;
  347. }
  348. public override int EndRead (IAsyncResult r)
  349. {
  350. WebAsyncResult result = (WebAsyncResult) r;
  351. if (result.EndCalled) {
  352. int xx = result.NBytes;
  353. return (xx >= 0) ? xx : 0;
  354. }
  355. result.EndCalled = true;
  356. if (!result.IsCompleted) {
  357. int nbytes = -1;
  358. try {
  359. nbytes = cnc.EndRead (request, result);
  360. } catch (Exception exc) {
  361. lock (locker) {
  362. pendingReads--;
  363. if (pendingReads == 0)
  364. pending.Set ();
  365. }
  366. nextReadCalled = true;
  367. cnc.Close (true);
  368. result.SetCompleted (false, exc);
  369. result.DoCallback ();
  370. throw;
  371. }
  372. if (nbytes < 0) {
  373. nbytes = 0;
  374. read_eof = true;
  375. }
  376. totalRead += nbytes;
  377. result.SetCompleted (false, nbytes + result.NBytes);
  378. result.DoCallback ();
  379. if (nbytes == 0)
  380. contentLength = totalRead;
  381. }
  382. lock (locker) {
  383. pendingReads--;
  384. if (pendingReads == 0)
  385. pending.Set ();
  386. }
  387. if (totalRead >= contentLength && !nextReadCalled)
  388. ReadAll ();
  389. int nb = result.NBytes;
  390. return (nb >= 0) ? nb : 0;
  391. }
  392. void WriteAsyncCB (IAsyncResult r)
  393. {
  394. WebAsyncResult result = (WebAsyncResult) r.AsyncState;
  395. result.InnerAsyncResult = null;
  396. try {
  397. cnc.EndWrite (request, true, r);
  398. result.SetCompleted (false, 0);
  399. if (!initRead) {
  400. initRead = true;
  401. WebConnection.InitRead (cnc);
  402. }
  403. } catch (Exception e) {
  404. KillBuffer ();
  405. nextReadCalled = true;
  406. cnc.Close (true);
  407. if (e is System.Net.Sockets.SocketException)
  408. e = new IOException ("Error writing request", e);
  409. result.SetCompleted (false, e);
  410. }
  411. if (allowBuffering && !sendChunked && request.ContentLength > 0 && totalWritten == request.ContentLength)
  412. complete_request_written = true;
  413. result.DoCallback ();
  414. }
  415. public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
  416. AsyncCallback cb, object state)
  417. {
  418. if (request.Aborted)
  419. throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
  420. if (isRead)
  421. throw new NotSupportedException ("this stream does not allow writing");
  422. if (buffer == null)
  423. throw new ArgumentNullException ("buffer");
  424. int length = buffer.Length;
  425. if (offset < 0 || length < offset)
  426. throw new ArgumentOutOfRangeException ("offset");
  427. if (size < 0 || (length - offset) < size)
  428. throw new ArgumentOutOfRangeException ("size");
  429. if (sendChunked) {
  430. lock (locker) {
  431. pendingWrites++;
  432. pending.Reset ();
  433. }
  434. }
  435. WebAsyncResult result = new WebAsyncResult (cb, state);
  436. AsyncCallback callback = new AsyncCallback (WriteAsyncCB);
  437. if (sendChunked) {
  438. requestWritten = true;
  439. string cSize = String.Format ("{0:X}\r\n", size);
  440. byte[] head = Encoding.ASCII.GetBytes (cSize);
  441. int chunkSize = 2 + size + head.Length;
  442. byte[] newBuffer = new byte [chunkSize];
  443. Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
  444. Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
  445. Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
  446. buffer = newBuffer;
  447. offset = 0;
  448. size = chunkSize;
  449. } else {
  450. CheckWriteOverflow (request.ContentLength, totalWritten, size);
  451. if (allowBuffering) {
  452. if (writeBuffer == null)
  453. writeBuffer = new MemoryStream ();
  454. writeBuffer.Write (buffer, offset, size);
  455. totalWritten += size;
  456. if (request.ContentLength <= 0 || totalWritten < request.ContentLength) {
  457. result.SetCompleted (true, 0);
  458. result.DoCallback ();
  459. return result;
  460. }
  461. result.AsyncWriteAll = true;
  462. requestWritten = true;
  463. buffer = writeBuffer.GetBuffer ();
  464. offset = 0;
  465. size = (int)totalWritten;
  466. }
  467. }
  468. try {
  469. result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
  470. if (result.InnerAsyncResult == null) {
  471. if (!result.IsCompleted)
  472. result.SetCompleted (true, 0);
  473. result.DoCallback ();
  474. }
  475. } catch (Exception) {
  476. if (!IgnoreIOErrors)
  477. throw;
  478. result.SetCompleted (true, 0);
  479. result.DoCallback ();
  480. }
  481. totalWritten += size;
  482. return result;
  483. }
  484. void CheckWriteOverflow (long contentLength, long totalWritten, long size)
  485. {
  486. if (contentLength == -1)
  487. return;
  488. long avail = contentLength - totalWritten;
  489. if (size > avail) {
  490. KillBuffer ();
  491. nextReadCalled = true;
  492. cnc.Close (true);
  493. throw new ProtocolViolationException (
  494. "The number of bytes to be written is greater than " +
  495. "the specified ContentLength.");
  496. }
  497. }
  498. public override void EndWrite (IAsyncResult r)
  499. {
  500. if (r == null)
  501. throw new ArgumentNullException ("r");
  502. WebAsyncResult result = r as WebAsyncResult;
  503. if (result == null)
  504. throw new ArgumentException ("Invalid IAsyncResult");
  505. if (result.EndCalled)
  506. return;
  507. result.EndCalled = true;
  508. if (result.AsyncWriteAll) {
  509. result.WaitUntilComplete ();
  510. if (result.GotException)
  511. throw result.Exception;
  512. return;
  513. }
  514. if (allowBuffering && !sendChunked)
  515. return;
  516. if (result.GotException)
  517. throw result.Exception;
  518. if (sendChunked) {
  519. lock (locker) {
  520. pendingWrites--;
  521. if (pendingWrites == 0)
  522. pending.Set ();
  523. }
  524. }
  525. }
  526. public override void Write (byte [] buffer, int offset, int size)
  527. {
  528. AsyncCallback cb = cb_wrapper;
  529. WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
  530. if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
  531. KillBuffer ();
  532. nextReadCalled = true;
  533. cnc.Close (true);
  534. throw new IOException ("Write timed out.");
  535. }
  536. EndWrite (res);
  537. }
  538. public override void Flush ()
  539. {
  540. }
  541. internal WebAsyncResult SetHeadersAsync (bool setInternalLength, AsyncCallback callback, object state)
  542. {
  543. if (headersSent)
  544. return null;
  545. string method = request.Method;
  546. bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
  547. method == "TRACE");
  548. bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
  549. method == "COPY" || method == "MOVE" || method == "LOCK" ||
  550. method == "UNLOCK");
  551. if (setInternalLength && !no_writestream && writeBuffer != null)
  552. request.InternalContentLength = writeBuffer.Length;
  553. if (sendChunked || request.ContentLength > -1 || no_writestream || webdav) {
  554. headersSent = true;
  555. headers = request.GetRequestHeaders ();
  556. var result = new WebAsyncResult (callback, state);
  557. result.InnerAsyncResult = cnc.BeginWrite (request, headers, 0, headers.Length, new AsyncCallback (SetHeadersCB), result);
  558. if (result.InnerAsyncResult != null)
  559. return result;
  560. }
  561. return null;
  562. }
  563. void SetHeadersCB (IAsyncResult r)
  564. {
  565. WebAsyncResult result = (WebAsyncResult) r.AsyncState;
  566. result.InnerAsyncResult = null;
  567. try {
  568. cnc.EndWrite (request, true, r);
  569. result.SetCompleted (false, 0);
  570. if (!initRead) {
  571. initRead = true;
  572. WebConnection.InitRead (cnc);
  573. }
  574. long cl = request.ContentLength;
  575. if (!sendChunked && cl == 0)
  576. requestWritten = true;
  577. } catch (WebException e) {
  578. result.SetCompleted (false, e);
  579. } catch (Exception e) {
  580. result.SetCompleted (false, new WebException ("Error writing headers", e, WebExceptionStatus.SendFailure));
  581. }
  582. result.DoCallback ();
  583. }
  584. internal bool RequestWritten {
  585. get { return requestWritten; }
  586. }
  587. internal WebAsyncResult WriteRequestAsync (AsyncCallback callback, object state)
  588. {
  589. if (requestWritten)
  590. return null;
  591. requestWritten = true;
  592. if (sendChunked)
  593. return null;
  594. if (!allowBuffering || writeBuffer == null)
  595. return null;
  596. byte[] bytes = writeBuffer.GetBuffer ();
  597. int length = (int)writeBuffer.Length;
  598. if (request.ContentLength != -1 && request.ContentLength < length) {
  599. nextReadCalled = true;
  600. cnc.Close (true);
  601. throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
  602. WebExceptionStatus.ServerProtocolViolation, null);
  603. }
  604. var result = new WebAsyncResult (callback, state);
  605. result.InnerAsyncResult = SetHeadersAsync (true, WriteRequestAsyncCB, result);
  606. if (result.InnerAsyncResult == null)
  607. WriteRequestAsyncCB (result);
  608. return result;
  609. }
  610. void WriteRequestAsyncCB (IAsyncResult ar)
  611. {
  612. var result = (WebAsyncResult)ar;
  613. var innerResult = (WebAsyncResult)result.InnerAsyncResult;
  614. result.InnerAsyncResult = null;
  615. if (innerResult != null && innerResult.GotException) {
  616. result.SetCompleted (false, innerResult.Exception);
  617. result.DoCallback ();
  618. return;
  619. }
  620. if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100) {
  621. result.SetCompleted (false, 0);
  622. result.DoCallback ();
  623. return;
  624. }
  625. byte[] bytes = writeBuffer.GetBuffer ();
  626. int length = (int)writeBuffer.Length;
  627. if (length > 0)
  628. result.InnerAsyncResult = cnc.BeginWrite (request, bytes, 0, length, WriteRequestAsyncCB2, result);
  629. if (!initRead) {
  630. initRead = true;
  631. WebConnection.InitRead (cnc);
  632. }
  633. if (length == 0) {
  634. result.SetCompleted (false, 0);
  635. result.DoCallback ();
  636. complete_request_written = true;
  637. }
  638. }
  639. void WriteRequestAsyncCB2 (IAsyncResult ar)
  640. {
  641. var result = (WebAsyncResult)ar.AsyncState;
  642. var innerResult = result.InnerAsyncResult;
  643. result.InnerAsyncResult = null;
  644. try {
  645. complete_request_written = cnc.EndWrite (request, false, innerResult);
  646. result.SetCompleted (false, 0);
  647. } catch (Exception exc) {
  648. result.SetCompleted (false, exc);
  649. } finally {
  650. result.DoCallback ();
  651. }
  652. }
  653. internal void InternalClose ()
  654. {
  655. disposed = true;
  656. }
  657. public override void Close ()
  658. {
  659. if (sendChunked) {
  660. if (disposed)
  661. return;
  662. disposed = true;
  663. pending.WaitOne ();
  664. byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
  665. string err_msg = null;
  666. cnc.Write (request, chunk, 0, chunk.Length, ref err_msg);
  667. return;
  668. }
  669. if (isRead) {
  670. if (!nextReadCalled) {
  671. CheckComplete ();
  672. // If we have not read all the contents
  673. if (!nextReadCalled) {
  674. nextReadCalled = true;
  675. cnc.Close (true);
  676. }
  677. }
  678. return;
  679. } else if (!allowBuffering) {
  680. complete_request_written = true;
  681. if (!initRead) {
  682. initRead = true;
  683. WebConnection.InitRead (cnc);
  684. }
  685. return;
  686. }
  687. if (disposed || requestWritten)
  688. return;
  689. long length = request.ContentLength;
  690. if (!sendChunked && length != -1 && totalWritten != length) {
  691. IOException io = new IOException ("Cannot close the stream until all bytes are written");
  692. nextReadCalled = true;
  693. cnc.Close (true);
  694. throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
  695. }
  696. // Commented out the next line to fix xamarin bug #1512
  697. //WriteRequest ();
  698. disposed = true;
  699. }
  700. internal void KillBuffer ()
  701. {
  702. writeBuffer = null;
  703. }
  704. public override long Seek (long a, SeekOrigin b)
  705. {
  706. throw new NotSupportedException ();
  707. }
  708. public override void SetLength (long a)
  709. {
  710. throw new NotSupportedException ();
  711. }
  712. public override bool CanSeek {
  713. get { return false; }
  714. }
  715. public override bool CanRead {
  716. get { return !disposed && isRead; }
  717. }
  718. public override bool CanWrite {
  719. get { return !disposed && !isRead; }
  720. }
  721. public override long Length {
  722. get {
  723. if (!isRead)
  724. throw new NotSupportedException ();
  725. return stream_length;
  726. }
  727. }
  728. public override long Position {
  729. get { throw new NotSupportedException (); }
  730. set { throw new NotSupportedException (); }
  731. }
  732. }
  733. }