WebConnectionStream.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. //
  9. using System.IO;
  10. using System.Threading;
  11. namespace System.Net
  12. {
  13. class WebConnectionStream : Stream
  14. {
  15. bool isRead;
  16. WebConnection cnc;
  17. HttpWebRequest request;
  18. byte [] readBuffer;
  19. int readBufferOffset;
  20. int readBufferSize;
  21. int contentLength;
  22. int totalRead;
  23. bool nextReadCalled;
  24. int pendingReads;
  25. ManualResetEvent pending;
  26. bool allowBuffering;
  27. bool sendChunked;
  28. MemoryStream writeBuffer;
  29. bool requestWritten;
  30. byte [] headers;
  31. bool disposed;
  32. public WebConnectionStream (WebConnection cnc)
  33. {
  34. isRead = true;
  35. pending = new ManualResetEvent (true);
  36. this.cnc = cnc;
  37. try {
  38. contentLength = Int32.Parse (cnc.Data.Headers ["Content-Length"]);
  39. } catch {
  40. contentLength = Int32.MaxValue;
  41. }
  42. }
  43. public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
  44. {
  45. isRead = false;
  46. this.cnc = cnc;
  47. this.request = request;
  48. allowBuffering = request.InternalAllowBuffering;
  49. sendChunked = request.SendChunked;
  50. if (allowBuffering)
  51. writeBuffer = new MemoryStream ();
  52. }
  53. internal byte [] ReadBuffer {
  54. set { readBuffer = value; }
  55. }
  56. internal int ReadBufferOffset {
  57. set { readBufferOffset = value;}
  58. }
  59. internal int ReadBufferSize {
  60. set { readBufferSize = value; }
  61. }
  62. internal void CheckComplete ()
  63. {
  64. if (!nextReadCalled && readBufferSize - readBufferOffset == contentLength) {
  65. nextReadCalled = true;
  66. cnc.NextRead ();
  67. }
  68. }
  69. internal void ReadAll ()
  70. {
  71. if (!isRead || totalRead >= contentLength || nextReadCalled)
  72. return;
  73. pending.WaitOne ();
  74. lock (this) {
  75. if (totalRead >= contentLength)
  76. return;
  77. byte [] b = null;
  78. int diff = readBufferSize - readBufferOffset;
  79. int new_size;
  80. if (contentLength == Int32.MaxValue) {
  81. MemoryStream ms = new MemoryStream ();
  82. if (readBuffer != null && diff > 0)
  83. ms.Write (readBuffer, readBufferOffset, diff);
  84. byte [] buffer = new byte [2048];
  85. int read;
  86. while ((read = cnc.Read (buffer, 0, 2048)) != 0)
  87. ms.Write (buffer, 0, read);
  88. b = ms.GetBuffer ();
  89. new_size = (int) ms.Length;
  90. contentLength = new_size;
  91. } else {
  92. new_size = contentLength - totalRead;
  93. b = new byte [new_size];
  94. if (readBuffer != null && diff > 0)
  95. Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
  96. int remaining = new_size - diff;
  97. int r = -1;
  98. while (remaining > 0 && r != 0) {
  99. r = cnc.Read (b, diff, remaining);
  100. remaining -= r;
  101. diff += r;
  102. }
  103. }
  104. readBuffer = b;
  105. readBufferOffset = 0;
  106. readBufferSize = new_size;
  107. totalRead = 0;
  108. nextReadCalled = true;
  109. }
  110. cnc.NextRead ();
  111. }
  112. static void CallbackWrapper (IAsyncResult r)
  113. {
  114. WebAsyncResult result = (WebAsyncResult) r.AsyncState;
  115. result.InnerAsyncResult = r;
  116. result.DoCallback ();
  117. }
  118. public override int Read (byte [] buffer, int offset, int size)
  119. {
  120. if (!isRead)
  121. throw new NotSupportedException ("this stream does not allow reading");
  122. if (totalRead >= contentLength)
  123. return 0;
  124. IAsyncResult res = BeginRead (buffer, offset, size, null, null);
  125. return EndRead (res);
  126. }
  127. public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
  128. AsyncCallback cb, object state)
  129. {
  130. if (!isRead)
  131. throw new NotSupportedException ("this stream does not allow reading");
  132. if (buffer == null)
  133. throw new ArgumentNullException ("buffer");
  134. int length = buffer.Length;
  135. if (size < 0 || offset < 0 || length < offset || length - offset < size)
  136. throw new ArgumentOutOfRangeException ();
  137. WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
  138. if (totalRead >= contentLength) {
  139. result.SetCompleted (true, -1);
  140. result.DoCallback ();
  141. return result;
  142. }
  143. int remaining = readBufferSize - readBufferOffset;
  144. if (remaining > 0) {
  145. int copy = (remaining > size) ? size : remaining;
  146. Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
  147. readBufferOffset += copy;
  148. offset += copy;
  149. size -= copy;
  150. totalRead += copy;
  151. if (size == 0 || totalRead >= contentLength) {
  152. result.SetCompleted (true, copy);
  153. result.DoCallback ();
  154. return result;
  155. }
  156. result.NBytes = copy;
  157. }
  158. lock (this) {
  159. pendingReads++;
  160. pending.Reset ();
  161. }
  162. if (cb != null)
  163. cb = new AsyncCallback (CallbackWrapper);
  164. if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
  165. size = contentLength - totalRead;
  166. result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
  167. return result;
  168. }
  169. public override int EndRead (IAsyncResult r)
  170. {
  171. WebAsyncResult result = (WebAsyncResult) r;
  172. if (!result.IsCompleted) {
  173. int nbytes = cnc.EndRead (result.InnerAsyncResult);
  174. lock (this) {
  175. pendingReads--;
  176. if (pendingReads == 0)
  177. pending.Set ();
  178. }
  179. bool finished = (nbytes == -1);
  180. if (finished && result.NBytes > 0)
  181. nbytes = 0;
  182. result.SetCompleted (false, nbytes + result.NBytes);
  183. totalRead += nbytes;
  184. if (finished || nbytes == 0)
  185. contentLength = totalRead;
  186. }
  187. if (totalRead >= contentLength && !nextReadCalled) {
  188. nextReadCalled = true;
  189. cnc.NextRead ();
  190. }
  191. return result.NBytes;
  192. }
  193. public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
  194. AsyncCallback cb, object state)
  195. {
  196. if (isRead)
  197. throw new NotSupportedException ("this stream does not allow writing");
  198. if (buffer == null)
  199. throw new ArgumentNullException ("buffer");
  200. int length = buffer.Length;
  201. if (size < 0 || offset < 0 || length < offset || length - offset < size)
  202. throw new ArgumentOutOfRangeException ();
  203. WebAsyncResult result = new WebAsyncResult (cb, state);
  204. if (allowBuffering) {
  205. writeBuffer.Write (buffer, offset, size);
  206. result.SetCompleted (true, 0);
  207. result.DoCallback ();
  208. } else {
  209. if (cb != null)
  210. cb = new AsyncCallback (CallbackWrapper);
  211. result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, cb, result);
  212. if (result.InnerAsyncResult == null)
  213. throw new WebException ("Aborted");
  214. }
  215. return result;
  216. }
  217. public override void EndWrite (IAsyncResult r)
  218. {
  219. if (r == null)
  220. throw new ArgumentNullException ("r");
  221. if (allowBuffering)
  222. return;
  223. WebAsyncResult result = r as WebAsyncResult;
  224. if (result == null)
  225. throw new ArgumentException ("Invalid IAsyncResult");
  226. cnc.EndWrite (result.InnerAsyncResult);
  227. return;
  228. }
  229. public override void Write (byte [] buffer, int offset, int size)
  230. {
  231. if (isRead)
  232. throw new NotSupportedException ("this stream does not allow writing");
  233. IAsyncResult res = BeginWrite (buffer, offset, size, null, null);
  234. EndWrite (res);
  235. }
  236. public override void Flush ()
  237. {
  238. }
  239. internal void SetHeaders (byte [] buffer, int offset, int size)
  240. {
  241. if (!allowBuffering) {
  242. try {
  243. Write (buffer, offset, size);
  244. } catch (IOException) {
  245. if (cnc.Connected)
  246. throw;
  247. if (!cnc.TryReconnect ())
  248. throw;
  249. Write (buffer, offset, size);
  250. }
  251. } else {
  252. headers = new byte [size];
  253. Buffer.BlockCopy (buffer, offset, headers, 0, size);
  254. }
  255. }
  256. internal void WriteRequest ()
  257. {
  258. if (!allowBuffering || writeBuffer == null || requestWritten)
  259. return;
  260. byte [] bytes = writeBuffer.GetBuffer ();
  261. int length = (int) writeBuffer.Length;
  262. if (request.ContentLength != -1 && request.ContentLength < length) {
  263. throw new ProtocolViolationException ("Specified Content-Length is less than the " +
  264. "number of bytes to write");
  265. }
  266. request.InternalContentLength = length;
  267. request.SendRequestHeaders ();
  268. requestWritten = true;
  269. while (true) {
  270. cnc.WaitForContinue (headers, 0, headers.Length);
  271. if (!cnc.Connected) {
  272. if (!cnc.TryReconnect ())
  273. return;
  274. continue;
  275. }
  276. if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
  277. return;
  278. cnc.Write (bytes, 0, length);
  279. if (!cnc.Connected && cnc.TryReconnect ())
  280. continue;
  281. break;
  282. }
  283. }
  284. internal void InternalClose ()
  285. {
  286. disposed = true;
  287. }
  288. public override void Close ()
  289. {
  290. if (isRead || !allowBuffering || disposed)
  291. return;
  292. disposed = true;
  293. long length = request.ContentLength;
  294. if (length != -1 && length > writeBuffer.Length)
  295. throw new IOException ("Cannot close the stream until all bytes are written");
  296. WriteRequest ();
  297. }
  298. internal void ResetWriteBuffer ()
  299. {
  300. if (!allowBuffering)
  301. return;
  302. writeBuffer = new MemoryStream ();
  303. requestWritten = false;
  304. }
  305. public override long Seek (long a, SeekOrigin b)
  306. {
  307. throw new NotSupportedException ();
  308. }
  309. public override void SetLength (long a)
  310. {
  311. throw new NotSupportedException ();
  312. }
  313. public override bool CanSeek {
  314. get { return false; }
  315. }
  316. public override bool CanRead {
  317. get { return isRead && (contentLength == Int32.MaxValue || totalRead < contentLength); }
  318. }
  319. public override bool CanWrite {
  320. get { return !isRead; }
  321. }
  322. public override long Length {
  323. get { throw new NotSupportedException (); }
  324. }
  325. public override long Position {
  326. get { throw new NotSupportedException (); }
  327. set { throw new NotSupportedException (); }
  328. }
  329. }
  330. }