WebConnectionStream.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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 IsNtlmAuth ()
  117. {
  118. bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.Address));
  119. string header_name = (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate";
  120. string authHeader = cnc.Data.Headers [header_name];
  121. return (authHeader != null && authHeader.IndexOf ("NTLM", StringComparison.Ordinal) != -1);
  122. }
  123. internal void CheckResponseInBuffer ()
  124. {
  125. if (contentLength > 0 && (readBufferSize - readBufferOffset) >= contentLength) {
  126. if (!IsNtlmAuth ())
  127. ReadAll ();
  128. }
  129. }
  130. internal HttpWebRequest Request {
  131. get { return request; }
  132. }
  133. internal WebConnection Connection {
  134. get { return cnc; }
  135. }
  136. public override bool CanTimeout {
  137. get { return true; }
  138. }
  139. public override int ReadTimeout {
  140. get {
  141. return read_timeout;
  142. }
  143. set {
  144. if (value < -1)
  145. throw new ArgumentOutOfRangeException ("value");
  146. read_timeout = value;
  147. }
  148. }
  149. public override int WriteTimeout {
  150. get {
  151. return write_timeout;
  152. }
  153. set {
  154. if (value < -1)
  155. throw new ArgumentOutOfRangeException ("value");
  156. write_timeout = value;
  157. }
  158. }
  159. internal bool CompleteRequestWritten {
  160. get { return complete_request_written; }
  161. }
  162. internal bool SendChunked {
  163. set { sendChunked = value; }
  164. }
  165. internal byte [] ReadBuffer {
  166. set { readBuffer = value; }
  167. }
  168. internal int ReadBufferOffset {
  169. set { readBufferOffset = value;}
  170. }
  171. internal int ReadBufferSize {
  172. set { readBufferSize = value; }
  173. }
  174. internal byte[] WriteBuffer {
  175. get { return writeBuffer.GetBuffer (); }
  176. }
  177. internal int WriteBufferLength {
  178. get { return writeBuffer != null ? (int) writeBuffer.Length : (-1); }
  179. }
  180. internal void ForceCompletion ()
  181. {
  182. if (!nextReadCalled) {
  183. if (contentLength == Int32.MaxValue)
  184. contentLength = 0;
  185. nextReadCalled = true;
  186. cnc.NextRead ();
  187. }
  188. }
  189. internal void CheckComplete ()
  190. {
  191. bool nrc = nextReadCalled;
  192. if (!nrc && readBufferSize - readBufferOffset == contentLength) {
  193. nextReadCalled = true;
  194. cnc.NextRead ();
  195. }
  196. }
  197. internal void ReadAll ()
  198. {
  199. if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
  200. if (isRead && !nextReadCalled) {
  201. nextReadCalled = true;
  202. cnc.NextRead ();
  203. }
  204. return;
  205. }
  206. pending.WaitOne ();
  207. lock (locker) {
  208. if (totalRead >= contentLength)
  209. return;
  210. byte [] b = null;
  211. int diff = readBufferSize - readBufferOffset;
  212. int new_size;
  213. if (contentLength == Int32.MaxValue) {
  214. MemoryStream ms = new MemoryStream ();
  215. byte [] buffer = null;
  216. if (readBuffer != null && diff > 0) {
  217. ms.Write (readBuffer, readBufferOffset, diff);
  218. if (readBufferSize >= 8192)
  219. buffer = readBuffer;
  220. }
  221. if (buffer == null)
  222. buffer = new byte [8192];
  223. int read;
  224. while ((read = cnc.Read (request, buffer, 0, buffer.Length)) != 0)
  225. ms.Write (buffer, 0, read);
  226. b = ms.GetBuffer ();
  227. new_size = (int) ms.Length;
  228. contentLength = new_size;
  229. } else {
  230. new_size = contentLength - totalRead;
  231. b = new byte [new_size];
  232. if (readBuffer != null && diff > 0) {
  233. if (diff > new_size)
  234. diff = new_size;
  235. Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
  236. }
  237. int remaining = new_size - diff;
  238. int r = -1;
  239. while (remaining > 0 && r != 0) {
  240. r = cnc.Read (request, b, diff, remaining);
  241. remaining -= r;
  242. diff += r;
  243. }
  244. }
  245. readBuffer = b;
  246. readBufferOffset = 0;
  247. readBufferSize = new_size;
  248. totalRead = 0;
  249. nextReadCalled = true;
  250. }
  251. cnc.NextRead ();
  252. }
  253. void WriteCallbackWrapper (IAsyncResult r)
  254. {
  255. WebAsyncResult result = r as WebAsyncResult;
  256. if (result != null && result.AsyncWriteAll)
  257. return;
  258. if (r.AsyncState != null) {
  259. result = (WebAsyncResult) r.AsyncState;
  260. result.InnerAsyncResult = r;
  261. result.DoCallback ();
  262. } else {
  263. try {
  264. EndWrite (r);
  265. } catch {
  266. }
  267. }
  268. }
  269. void ReadCallbackWrapper (IAsyncResult r)
  270. {
  271. WebAsyncResult result;
  272. if (r.AsyncState != null) {
  273. result = (WebAsyncResult) r.AsyncState;
  274. result.InnerAsyncResult = r;
  275. result.DoCallback ();
  276. } else {
  277. try {
  278. EndRead (r);
  279. } catch {
  280. }
  281. }
  282. }
  283. public override int Read (byte [] buffer, int offset, int size)
  284. {
  285. AsyncCallback cb = cb_wrapper;
  286. WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
  287. if (!res.IsCompleted && !res.WaitUntilComplete (ReadTimeout, false)) {
  288. nextReadCalled = true;
  289. cnc.Close (true);
  290. throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
  291. }
  292. return EndRead (res);
  293. }
  294. public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
  295. AsyncCallback cb, object state)
  296. {
  297. if (!isRead)
  298. throw new NotSupportedException ("this stream does not allow reading");
  299. if (buffer == null)
  300. throw new ArgumentNullException ("buffer");
  301. int length = buffer.Length;
  302. if (offset < 0 || length < offset)
  303. throw new ArgumentOutOfRangeException ("offset");
  304. if (size < 0 || (length - offset) < size)
  305. throw new ArgumentOutOfRangeException ("size");
  306. lock (locker) {
  307. pendingReads++;
  308. pending.Reset ();
  309. }
  310. WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
  311. if (totalRead >= contentLength) {
  312. result.SetCompleted (true, -1);
  313. result.DoCallback ();
  314. return result;
  315. }
  316. int remaining = readBufferSize - readBufferOffset;
  317. if (remaining > 0) {
  318. int copy = (remaining > size) ? size : remaining;
  319. Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
  320. readBufferOffset += copy;
  321. offset += copy;
  322. size -= copy;
  323. totalRead += copy;
  324. if (size == 0 || totalRead >= contentLength) {
  325. result.SetCompleted (true, copy);
  326. result.DoCallback ();
  327. return result;
  328. }
  329. result.NBytes = copy;
  330. }
  331. if (cb != null)
  332. cb = cb_wrapper;
  333. if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
  334. size = contentLength - totalRead;
  335. if (!read_eof) {
  336. result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
  337. } else {
  338. result.SetCompleted (true, result.NBytes);
  339. result.DoCallback ();
  340. }
  341. return result;
  342. }
  343. public override int EndRead (IAsyncResult r)
  344. {
  345. WebAsyncResult result = (WebAsyncResult) r;
  346. if (result.EndCalled) {
  347. int xx = result.NBytes;
  348. return (xx >= 0) ? xx : 0;
  349. }
  350. result.EndCalled = true;
  351. if (!result.IsCompleted) {
  352. int nbytes = -1;
  353. try {
  354. nbytes = cnc.EndRead (request, result);
  355. } catch (Exception exc) {
  356. lock (locker) {
  357. pendingReads--;
  358. if (pendingReads == 0)
  359. pending.Set ();
  360. }
  361. nextReadCalled = true;
  362. cnc.Close (true);
  363. result.SetCompleted (false, exc);
  364. result.DoCallback ();
  365. throw;
  366. }
  367. if (nbytes < 0) {
  368. nbytes = 0;
  369. read_eof = true;
  370. }
  371. totalRead += nbytes;
  372. result.SetCompleted (false, nbytes + result.NBytes);
  373. result.DoCallback ();
  374. if (nbytes == 0)
  375. contentLength = totalRead;
  376. }
  377. lock (locker) {
  378. pendingReads--;
  379. if (pendingReads == 0)
  380. pending.Set ();
  381. }
  382. if (totalRead >= contentLength && !nextReadCalled)
  383. ReadAll ();
  384. int nb = result.NBytes;
  385. return (nb >= 0) ? nb : 0;
  386. }
  387. void WriteRequestAsyncCB (IAsyncResult r)
  388. {
  389. WebAsyncResult result = (WebAsyncResult) r.AsyncState;
  390. try {
  391. cnc.EndWrite2 (request, r);
  392. result.SetCompleted (false, 0);
  393. if (!initRead) {
  394. initRead = true;
  395. WebConnection.InitRead (cnc);
  396. }
  397. } catch (Exception e) {
  398. KillBuffer ();
  399. nextReadCalled = true;
  400. cnc.Close (true);
  401. if (e is System.Net.Sockets.SocketException)
  402. e = new IOException ("Error writing request", e);
  403. result.SetCompleted (false, e);
  404. }
  405. complete_request_written = true;
  406. result.DoCallback ();
  407. }
  408. public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
  409. AsyncCallback cb, object state)
  410. {
  411. if (request.Aborted)
  412. throw new WebException ("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
  413. if (isRead)
  414. throw new NotSupportedException ("this stream does not allow writing");
  415. if (buffer == null)
  416. throw new ArgumentNullException ("buffer");
  417. int length = buffer.Length;
  418. if (offset < 0 || length < offset)
  419. throw new ArgumentOutOfRangeException ("offset");
  420. if (size < 0 || (length - offset) < size)
  421. throw new ArgumentOutOfRangeException ("size");
  422. if (sendChunked) {
  423. lock (locker) {
  424. pendingWrites++;
  425. pending.Reset ();
  426. }
  427. }
  428. WebAsyncResult result = new WebAsyncResult (cb, state);
  429. if (!sendChunked)
  430. CheckWriteOverflow (request.ContentLength, totalWritten, size);
  431. if (allowBuffering && !sendChunked) {
  432. if (writeBuffer == null)
  433. writeBuffer = new MemoryStream ();
  434. writeBuffer.Write (buffer, offset, size);
  435. totalWritten += size;
  436. if (request.ContentLength > 0 && totalWritten == request.ContentLength) {
  437. try {
  438. result.AsyncWriteAll = true;
  439. result.InnerAsyncResult = WriteRequestAsync (new AsyncCallback (WriteRequestAsyncCB), result);
  440. if (result.InnerAsyncResult == null) {
  441. if (!result.IsCompleted)
  442. result.SetCompleted (true, 0);
  443. result.DoCallback ();
  444. }
  445. } catch (Exception exc) {
  446. result.SetCompleted (true, exc);
  447. result.DoCallback ();
  448. }
  449. } else {
  450. result.SetCompleted (true, 0);
  451. result.DoCallback ();
  452. }
  453. return result;
  454. }
  455. AsyncCallback callback = null;
  456. if (cb != null)
  457. callback = cb_wrapper;
  458. if (sendChunked) {
  459. WriteRequest ();
  460. string cSize = String.Format ("{0:X}\r\n", size);
  461. byte [] head = Encoding.ASCII.GetBytes (cSize);
  462. int chunkSize = 2 + size + head.Length;
  463. byte [] newBuffer = new byte [chunkSize];
  464. Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
  465. Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
  466. Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
  467. buffer = newBuffer;
  468. offset = 0;
  469. size = chunkSize;
  470. }
  471. try {
  472. result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
  473. } catch (Exception) {
  474. if (!IgnoreIOErrors)
  475. throw;
  476. result.SetCompleted (true, 0);
  477. result.DoCallback ();
  478. }
  479. totalWritten += size;
  480. return result;
  481. }
  482. void CheckWriteOverflow (long contentLength, long totalWritten, long size)
  483. {
  484. if (contentLength == -1)
  485. return;
  486. long avail = contentLength - totalWritten;
  487. if (size > avail) {
  488. KillBuffer ();
  489. nextReadCalled = true;
  490. cnc.Close (true);
  491. throw new ProtocolViolationException (
  492. "The number of bytes to be written is greater than " +
  493. "the specified ContentLength.");
  494. }
  495. }
  496. public override void EndWrite (IAsyncResult r)
  497. {
  498. if (r == null)
  499. throw new ArgumentNullException ("r");
  500. WebAsyncResult result = r as WebAsyncResult;
  501. if (result == null)
  502. throw new ArgumentException ("Invalid IAsyncResult");
  503. if (result.EndCalled)
  504. return;
  505. result.EndCalled = true;
  506. if (result.AsyncWriteAll) {
  507. result.WaitUntilComplete ();
  508. if (result.GotException)
  509. throw result.Exception;
  510. return;
  511. }
  512. if (allowBuffering && !sendChunked)
  513. return;
  514. if (result.GotException)
  515. throw result.Exception;
  516. try {
  517. cnc.EndWrite2 (request, result.InnerAsyncResult);
  518. result.SetCompleted (false, 0);
  519. result.DoCallback ();
  520. } catch (Exception e) {
  521. if (IgnoreIOErrors)
  522. result.SetCompleted (false, 0);
  523. else
  524. result.SetCompleted (false, e);
  525. result.DoCallback ();
  526. if (!IgnoreIOErrors)
  527. throw;
  528. } finally {
  529. if (sendChunked) {
  530. lock (locker) {
  531. pendingWrites--;
  532. if (pendingWrites == 0)
  533. pending.Set ();
  534. }
  535. }
  536. }
  537. }
  538. public override void Write (byte [] buffer, int offset, int size)
  539. {
  540. AsyncCallback cb = cb_wrapper;
  541. WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
  542. if (!res.IsCompleted && !res.WaitUntilComplete (WriteTimeout, false)) {
  543. KillBuffer ();
  544. nextReadCalled = true;
  545. cnc.Close (true);
  546. throw new IOException ("Write timed out.");
  547. }
  548. EndWrite (res);
  549. }
  550. public override void Flush ()
  551. {
  552. }
  553. internal void SetHeadersAsync (byte[] buffer, WebAsyncResult result)
  554. {
  555. if (headersSent)
  556. return;
  557. headers = buffer;
  558. long cl = request.ContentLength;
  559. string method = request.Method;
  560. bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
  561. method == "TRACE");
  562. bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
  563. method == "COPY" || method == "MOVE" || method == "LOCK" ||
  564. method == "UNLOCK");
  565. if (sendChunked || cl > -1 || no_writestream || webdav) {
  566. headersSent = true;
  567. try {
  568. result.InnerAsyncResult = cnc.BeginWrite (request, headers, 0, headers.Length, new AsyncCallback(SetHeadersCB), result);
  569. if (result.InnerAsyncResult == null) {
  570. // when does BeginWrite return null? Is the case when the request is aborted?
  571. if (!result.IsCompleted)
  572. result.SetCompleted (true, 0);
  573. result.DoCallback ();
  574. }
  575. } catch (Exception exc) {
  576. result.SetCompleted (true, exc);
  577. result.DoCallback ();
  578. }
  579. }
  580. }
  581. void SetHeadersCB (IAsyncResult r)
  582. {
  583. WebAsyncResult result = (WebAsyncResult) r.AsyncState;
  584. result.InnerAsyncResult = null;
  585. try {
  586. cnc.EndWrite2 (request, r);
  587. result.SetCompleted (false, 0);
  588. if (!initRead) {
  589. initRead = true;
  590. WebConnection.InitRead (cnc);
  591. }
  592. long cl = request.ContentLength;
  593. if (!sendChunked && cl == 0)
  594. requestWritten = true;
  595. } catch (WebException e) {
  596. result.SetCompleted (false, e);
  597. } catch (Exception e) {
  598. result.SetCompleted (false, new WebException ("Error writing headers", e, WebExceptionStatus.SendFailure));
  599. }
  600. result.DoCallback ();
  601. }
  602. internal bool RequestWritten {
  603. get { return requestWritten; }
  604. }
  605. IAsyncResult WriteRequestAsync (AsyncCallback cb, object state)
  606. {
  607. requestWritten = true;
  608. byte [] bytes = writeBuffer.GetBuffer ();
  609. int length = (int) writeBuffer.Length;
  610. // Headers already written to the stream
  611. return (length > 0) ? cnc.BeginWrite (request, bytes, 0, length, cb, state) : null;
  612. }
  613. internal void WriteRequest ()
  614. {
  615. if (requestWritten)
  616. return;
  617. requestWritten = true;
  618. if (sendChunked)
  619. return;
  620. if (!allowBuffering || writeBuffer == null)
  621. return;
  622. byte [] bytes = writeBuffer.GetBuffer ();
  623. int length = (int) writeBuffer.Length;
  624. if (request.ContentLength != -1 && request.ContentLength < length) {
  625. nextReadCalled = true;
  626. cnc.Close (true);
  627. throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
  628. WebExceptionStatus.ServerProtocolViolation, null);
  629. }
  630. if (!headersSent) {
  631. string method = request.Method;
  632. bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
  633. method == "TRACE");
  634. if (!no_writestream)
  635. request.InternalContentLength = length;
  636. byte[] requestHeaders = request.GetRequestHeaders ();
  637. WebAsyncResult ar = new WebAsyncResult (null, null);
  638. SetHeadersAsync (requestHeaders, ar);
  639. ar.AsyncWaitHandle.WaitOne ();
  640. if (ar.Exception != null)
  641. throw ar.Exception;
  642. }
  643. if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
  644. return;
  645. IAsyncResult result = null;
  646. if (length > 0)
  647. result = cnc.BeginWrite (request, bytes, 0, length, null, null);
  648. if (!initRead) {
  649. initRead = true;
  650. WebConnection.InitRead (cnc);
  651. }
  652. if (length > 0)
  653. complete_request_written = cnc.EndWrite (request, result);
  654. else
  655. complete_request_written = true;
  656. }
  657. internal void InternalClose ()
  658. {
  659. disposed = true;
  660. }
  661. public override void Close ()
  662. {
  663. if (sendChunked) {
  664. if (disposed)
  665. return;
  666. disposed = true;
  667. pending.WaitOne ();
  668. byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
  669. string err_msg = null;
  670. cnc.Write (request, chunk, 0, chunk.Length, ref err_msg);
  671. return;
  672. }
  673. if (isRead) {
  674. if (!nextReadCalled) {
  675. CheckComplete ();
  676. // If we have not read all the contents
  677. if (!nextReadCalled) {
  678. nextReadCalled = true;
  679. cnc.Close (true);
  680. }
  681. }
  682. return;
  683. } else if (!allowBuffering) {
  684. complete_request_written = true;
  685. if (!initRead) {
  686. initRead = true;
  687. WebConnection.InitRead (cnc);
  688. }
  689. return;
  690. }
  691. if (disposed || requestWritten)
  692. return;
  693. long length = request.ContentLength;
  694. if (!sendChunked && length != -1 && totalWritten != length) {
  695. IOException io = new IOException ("Cannot close the stream until all bytes are written");
  696. nextReadCalled = true;
  697. cnc.Close (true);
  698. throw new WebException ("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
  699. }
  700. // Commented out the next line to fix xamarin bug #1512
  701. //WriteRequest ();
  702. disposed = true;
  703. }
  704. internal void KillBuffer ()
  705. {
  706. writeBuffer = null;
  707. }
  708. public override long Seek (long a, SeekOrigin b)
  709. {
  710. throw new NotSupportedException ();
  711. }
  712. public override void SetLength (long a)
  713. {
  714. throw new NotSupportedException ();
  715. }
  716. public override bool CanSeek {
  717. get { return false; }
  718. }
  719. public override bool CanRead {
  720. get { return !disposed && isRead; }
  721. }
  722. public override bool CanWrite {
  723. get { return !disposed && !isRead; }
  724. }
  725. public override long Length {
  726. get {
  727. if (!isRead)
  728. throw new NotSupportedException ();
  729. return stream_length;
  730. }
  731. }
  732. public override long Position {
  733. get { throw new NotSupportedException (); }
  734. set { throw new NotSupportedException (); }
  735. }
  736. }
  737. }