WebConnectionStream.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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 contentLength;
  45. int totalRead;
  46. bool nextReadCalled;
  47. int pendingReads;
  48. int pendingWrites;
  49. ManualResetEvent pending;
  50. bool allowBuffering;
  51. bool sendChunked;
  52. MemoryStream writeBuffer;
  53. bool requestWritten;
  54. byte [] headers;
  55. bool disposed;
  56. bool headersSent;
  57. object locker = new object ();
  58. bool initRead;
  59. bool read_eof;
  60. bool complete_request_written;
  61. public WebConnectionStream (WebConnection cnc)
  62. {
  63. isRead = true;
  64. pending = new ManualResetEvent (true);
  65. this.request = cnc.Data.request;
  66. this.cnc = cnc;
  67. string contentType = cnc.Data.Headers ["Transfer-Encoding"];
  68. bool chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
  69. string clength = cnc.Data.Headers ["Content-Length"];
  70. if (!chunkedRead && clength != null && clength != "") {
  71. try {
  72. contentLength = Int32.Parse (clength);
  73. } catch {
  74. contentLength = Int32.MaxValue;
  75. }
  76. } else {
  77. contentLength = Int32.MaxValue;
  78. }
  79. }
  80. public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
  81. {
  82. isRead = false;
  83. this.cnc = cnc;
  84. this.request = request;
  85. allowBuffering = request.InternalAllowBuffering;
  86. sendChunked = request.SendChunked;
  87. if (allowBuffering)
  88. writeBuffer = new MemoryStream ();
  89. if (sendChunked)
  90. pending = new ManualResetEvent (true);
  91. }
  92. internal bool CompleteRequestWritten {
  93. get { return complete_request_written; }
  94. }
  95. internal bool SendChunked {
  96. set { sendChunked = value; }
  97. }
  98. internal byte [] ReadBuffer {
  99. set { readBuffer = value; }
  100. }
  101. internal int ReadBufferOffset {
  102. set { readBufferOffset = value;}
  103. }
  104. internal int ReadBufferSize {
  105. set { readBufferSize = value; }
  106. }
  107. internal byte[] WriteBuffer {
  108. get { return writeBuffer.GetBuffer (); }
  109. }
  110. internal int WriteBufferLength {
  111. get { return (int) writeBuffer.Length; }
  112. }
  113. internal void ForceCompletion ()
  114. {
  115. nextReadCalled = true;
  116. cnc.NextRead ();
  117. }
  118. internal void CheckComplete ()
  119. {
  120. bool nrc = nextReadCalled;
  121. if (!nrc && readBufferSize - readBufferOffset == contentLength) {
  122. nextReadCalled = true;
  123. cnc.NextRead ();
  124. }
  125. }
  126. internal void ReadAll ()
  127. {
  128. if (!isRead || read_eof || totalRead >= contentLength || nextReadCalled) {
  129. if (isRead && !nextReadCalled) {
  130. nextReadCalled = true;
  131. cnc.NextRead ();
  132. }
  133. return;
  134. }
  135. pending.WaitOne ();
  136. lock (locker) {
  137. if (totalRead >= contentLength)
  138. return;
  139. byte [] b = null;
  140. int diff = readBufferSize - readBufferOffset;
  141. int new_size;
  142. if (contentLength == Int32.MaxValue) {
  143. MemoryStream ms = new MemoryStream ();
  144. byte [] buffer = null;
  145. if (readBuffer != null && diff > 0) {
  146. ms.Write (readBuffer, readBufferOffset, diff);
  147. if (readBufferSize >= 8192)
  148. buffer = readBuffer;
  149. }
  150. if (buffer == null)
  151. buffer = new byte [8192];
  152. int read;
  153. while ((read = cnc.Read (buffer, 0, buffer.Length)) != 0)
  154. ms.Write (buffer, 0, read);
  155. b = ms.GetBuffer ();
  156. new_size = (int) ms.Length;
  157. contentLength = new_size;
  158. } else {
  159. new_size = contentLength - totalRead;
  160. b = new byte [new_size];
  161. if (readBuffer != null && diff > 0) {
  162. if (diff > new_size)
  163. diff = new_size;
  164. Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
  165. }
  166. int remaining = new_size - diff;
  167. int r = -1;
  168. while (remaining > 0 && r != 0) {
  169. r = cnc.Read (b, diff, remaining);
  170. remaining -= r;
  171. diff += r;
  172. }
  173. }
  174. readBuffer = b;
  175. readBufferOffset = 0;
  176. readBufferSize = new_size;
  177. totalRead = 0;
  178. nextReadCalled = true;
  179. }
  180. cnc.NextRead ();
  181. }
  182. void WriteCallbackWrapper (IAsyncResult r)
  183. {
  184. WebAsyncResult result;
  185. if (r.AsyncState != null) {
  186. result = (WebAsyncResult) r.AsyncState;
  187. result.InnerAsyncResult = r;
  188. result.DoCallback ();
  189. } else {
  190. EndWrite (r);
  191. }
  192. }
  193. void ReadCallbackWrapper (IAsyncResult r)
  194. {
  195. WebAsyncResult result;
  196. if (r.AsyncState != null) {
  197. result = (WebAsyncResult) r.AsyncState;
  198. result.InnerAsyncResult = r;
  199. result.DoCallback ();
  200. } else {
  201. EndRead (r);
  202. }
  203. }
  204. public override int Read (byte [] buffer, int offset, int size)
  205. {
  206. if (!isRead)
  207. throw new NotSupportedException ("this stream does not allow reading");
  208. if (totalRead >= contentLength)
  209. return 0;
  210. AsyncCallback cb = new AsyncCallback (ReadCallbackWrapper);
  211. WebAsyncResult res = (WebAsyncResult) BeginRead (buffer, offset, size, cb, null);
  212. if (!res.IsCompleted && !res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
  213. nextReadCalled = true;
  214. cnc.Close (true);
  215. throw new IOException ("Read timed out.");
  216. }
  217. return EndRead (res);
  218. }
  219. public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
  220. AsyncCallback cb, object state)
  221. {
  222. if (!isRead)
  223. throw new NotSupportedException ("this stream does not allow reading");
  224. if (buffer == null)
  225. throw new ArgumentNullException ("buffer");
  226. int length = buffer.Length;
  227. if (size < 0 || offset < 0 || length < offset || length - offset < size)
  228. throw new ArgumentOutOfRangeException ();
  229. lock (locker) {
  230. pendingReads++;
  231. pending.Reset ();
  232. }
  233. WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
  234. if (totalRead >= contentLength) {
  235. result.SetCompleted (true, -1);
  236. result.DoCallback ();
  237. return result;
  238. }
  239. int remaining = readBufferSize - readBufferOffset;
  240. if (remaining > 0) {
  241. int copy = (remaining > size) ? size : remaining;
  242. Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
  243. readBufferOffset += copy;
  244. offset += copy;
  245. size -= copy;
  246. totalRead += copy;
  247. if (size == 0 || totalRead >= contentLength) {
  248. result.SetCompleted (true, copy);
  249. result.DoCallback ();
  250. return result;
  251. }
  252. result.NBytes = copy;
  253. }
  254. if (cb != null)
  255. cb = new AsyncCallback (ReadCallbackWrapper);
  256. if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
  257. size = contentLength - totalRead;
  258. if (!read_eof) {
  259. result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
  260. } else {
  261. result.SetCompleted (true, result.NBytes);
  262. result.DoCallback ();
  263. }
  264. return result;
  265. }
  266. public override int EndRead (IAsyncResult r)
  267. {
  268. WebAsyncResult result = (WebAsyncResult) r;
  269. if (result.EndCalled) {
  270. int xx = result.NBytes;
  271. return (xx >= 0) ? xx : 0;
  272. }
  273. result.EndCalled = true;
  274. if (!result.IsCompleted) {
  275. int nbytes = -1;
  276. try {
  277. nbytes = cnc.EndRead (result);
  278. } catch (Exception exc) {
  279. lock (locker) {
  280. pendingReads--;
  281. if (pendingReads == 0)
  282. pending.Set ();
  283. }
  284. nextReadCalled = true;
  285. cnc.Close (true);
  286. result.SetCompleted (false, exc);
  287. throw;
  288. }
  289. if (nbytes < 0) {
  290. nbytes = 0;
  291. read_eof = true;
  292. }
  293. totalRead += nbytes;
  294. result.SetCompleted (false, nbytes + result.NBytes);
  295. result.DoCallback ();
  296. if (nbytes == 0)
  297. contentLength = totalRead;
  298. }
  299. lock (locker) {
  300. pendingReads--;
  301. if (pendingReads == 0)
  302. pending.Set ();
  303. }
  304. if (totalRead >= contentLength && !nextReadCalled)
  305. ReadAll ();
  306. int nb = result.NBytes;
  307. return (nb >= 0) ? nb : 0;
  308. }
  309. public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
  310. AsyncCallback cb, object state)
  311. {
  312. if (isRead)
  313. throw new NotSupportedException ("this stream does not allow writing");
  314. if (buffer == null)
  315. throw new ArgumentNullException ("buffer");
  316. int length = buffer.Length;
  317. if (size < 0 || offset < 0 || length < offset || length - offset < size)
  318. throw new ArgumentOutOfRangeException ();
  319. if (sendChunked) {
  320. lock (locker) {
  321. pendingWrites++;
  322. pending.Reset ();
  323. }
  324. }
  325. WebAsyncResult result = new WebAsyncResult (cb, state);
  326. if (allowBuffering) {
  327. writeBuffer.Write (buffer, offset, size);
  328. if (!sendChunked) {
  329. result.SetCompleted (true, 0);
  330. result.DoCallback ();
  331. return result;
  332. }
  333. }
  334. AsyncCallback callback = null;
  335. if (cb != null)
  336. callback = new AsyncCallback (WriteCallbackWrapper);
  337. if (sendChunked) {
  338. WriteRequest ();
  339. string cSize = String.Format ("{0:X}\r\n", size);
  340. byte [] head = Encoding.ASCII.GetBytes (cSize);
  341. int chunkSize = 2 + size + head.Length;
  342. byte [] newBuffer = new byte [chunkSize];
  343. Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
  344. Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
  345. Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
  346. buffer = newBuffer;
  347. offset = 0;
  348. size = chunkSize;
  349. }
  350. result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
  351. return result;
  352. }
  353. public override void EndWrite (IAsyncResult r)
  354. {
  355. if (r == null)
  356. throw new ArgumentNullException ("r");
  357. WebAsyncResult result = r as WebAsyncResult;
  358. if (result == null)
  359. throw new ArgumentException ("Invalid IAsyncResult");
  360. if (result.EndCalled)
  361. return;
  362. result.EndCalled = true;
  363. if (allowBuffering && !sendChunked)
  364. return;
  365. if (result.GotException)
  366. throw result.Exception;
  367. try {
  368. cnc.EndWrite (result.InnerAsyncResult);
  369. result.SetCompleted (false, 0);
  370. } catch (Exception e) {
  371. result.SetCompleted (false, e);
  372. }
  373. if (sendChunked) {
  374. lock (locker) {
  375. pendingWrites--;
  376. if (pendingWrites == 0)
  377. pending.Set ();
  378. }
  379. }
  380. }
  381. public override void Write (byte [] buffer, int offset, int size)
  382. {
  383. if (isRead)
  384. throw new NotSupportedException ("This stream does not allow writing");
  385. AsyncCallback cb = new AsyncCallback (WriteCallbackWrapper);
  386. WebAsyncResult res = (WebAsyncResult) BeginWrite (buffer, offset, size, cb, null);
  387. if (!res.IsCompleted && !res.WaitUntilComplete (request.ReadWriteTimeout, false)) {
  388. nextReadCalled = true;
  389. cnc.Close (true);
  390. throw new IOException ("Write timed out.");
  391. }
  392. EndWrite (res);
  393. }
  394. public override void Flush ()
  395. {
  396. }
  397. internal void SetHeaders (byte [] buffer, int offset, int size)
  398. {
  399. if (headersSent)
  400. return;
  401. if (!allowBuffering || sendChunked) {
  402. headersSent = true;
  403. if (!cnc.Connected)
  404. throw new WebException ("Not connected", null, WebExceptionStatus.SendFailure, null);
  405. cnc.Write (buffer, offset, size);
  406. if (!initRead) {
  407. initRead = true;
  408. WebConnection.InitRead (cnc);
  409. }
  410. } else {
  411. headers = new byte [size];
  412. Buffer.BlockCopy (buffer, offset, headers, 0, size);
  413. }
  414. }
  415. internal bool RequestWritten {
  416. get { return requestWritten; }
  417. }
  418. internal void WriteRequest ()
  419. {
  420. if (requestWritten)
  421. return;
  422. if (sendChunked) {
  423. request.SendRequestHeaders ();
  424. requestWritten = true;
  425. return;
  426. }
  427. if (!allowBuffering || writeBuffer == null)
  428. return;
  429. byte [] bytes = writeBuffer.GetBuffer ();
  430. int length = (int) writeBuffer.Length;
  431. if (request.ContentLength != -1 && request.ContentLength < length) {
  432. throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
  433. WebExceptionStatus.ServerProtocolViolation, null);
  434. }
  435. request.InternalContentLength = length;
  436. request.SendRequestHeaders ();
  437. requestWritten = true;
  438. cnc.Write (headers, 0, headers.Length);
  439. if (!cnc.Connected)
  440. throw new WebException ("Error writing request.", null, WebExceptionStatus.SendFailure, null);
  441. headersSent = true;
  442. if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
  443. return;
  444. IAsyncResult result = cnc.BeginWrite (bytes, 0, length, null, null);
  445. if (!initRead) {
  446. initRead = true;
  447. WebConnection.InitRead (cnc);
  448. }
  449. complete_request_written = cnc.EndWrite (result);
  450. }
  451. internal void InternalClose ()
  452. {
  453. disposed = true;
  454. }
  455. internal void ForceCloseConnection ()
  456. {
  457. if (!disposed) {
  458. disposed = true;
  459. cnc.Close (true);
  460. }
  461. }
  462. public override void Close ()
  463. {
  464. if (sendChunked) {
  465. pending.WaitOne ();
  466. byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
  467. cnc.Write (chunk, 0, chunk.Length);
  468. return;
  469. }
  470. if (isRead) {
  471. if (!nextReadCalled) {
  472. CheckComplete ();
  473. // If we have not read all the contents
  474. if (!nextReadCalled) {
  475. nextReadCalled = true;
  476. cnc.Close (true);
  477. }
  478. }
  479. return;
  480. } else if (!allowBuffering) {
  481. complete_request_written = true;
  482. if (!initRead) {
  483. initRead = true;
  484. WebConnection.InitRead (cnc);
  485. }
  486. return;
  487. }
  488. if (disposed)
  489. return;
  490. long length = request.ContentLength;
  491. if (length != -1 && length > writeBuffer.Length)
  492. throw new IOException ("Cannot close the stream until all bytes are written");
  493. WriteRequest ();
  494. disposed = true;
  495. }
  496. public override long Seek (long a, SeekOrigin b)
  497. {
  498. throw new NotSupportedException ();
  499. }
  500. public override void SetLength (long a)
  501. {
  502. throw new NotSupportedException ();
  503. }
  504. public override bool CanSeek {
  505. get { return false; }
  506. }
  507. public override bool CanRead {
  508. get { return isRead; }
  509. }
  510. public override bool CanWrite {
  511. get { return !isRead; }
  512. }
  513. public override long Length {
  514. get { throw new NotSupportedException (); }
  515. }
  516. public override long Position {
  517. get { throw new NotSupportedException (); }
  518. set { throw new NotSupportedException (); }
  519. }
  520. }
  521. }