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