WebConnectionStream.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. public WebConnectionStream (WebConnection cnc)
  58. {
  59. isRead = true;
  60. pending = new ManualResetEvent (true);
  61. this.cnc = cnc;
  62. string clength = cnc.Data.Headers ["Content-Length"];
  63. if (clength != null && clength != "") {
  64. try {
  65. contentLength = Int32.Parse (clength);
  66. } catch {
  67. contentLength = Int32.MaxValue;
  68. }
  69. } else {
  70. contentLength = Int32.MaxValue;
  71. }
  72. }
  73. public WebConnectionStream (WebConnection cnc, HttpWebRequest request)
  74. {
  75. isRead = false;
  76. this.cnc = cnc;
  77. this.request = request;
  78. allowBuffering = request.InternalAllowBuffering;
  79. sendChunked = request.SendChunked;
  80. if (allowBuffering)
  81. writeBuffer = new MemoryStream ();
  82. if (sendChunked)
  83. pending = new ManualResetEvent (true);
  84. }
  85. internal bool SendChunked {
  86. set { sendChunked = value; }
  87. }
  88. internal byte [] ReadBuffer {
  89. set { readBuffer = value; }
  90. }
  91. internal int ReadBufferOffset {
  92. set { readBufferOffset = value;}
  93. }
  94. internal int ReadBufferSize {
  95. set { readBufferSize = value; }
  96. }
  97. internal byte[] WriteBuffer {
  98. get { return writeBuffer.GetBuffer (); }
  99. }
  100. internal int WriteBufferLength {
  101. get { return (int) writeBuffer.Length; }
  102. }
  103. internal void CheckComplete ()
  104. {
  105. if (!nextReadCalled && readBufferSize - readBufferOffset == contentLength) {
  106. nextReadCalled = true;
  107. cnc.NextRead ();
  108. }
  109. }
  110. internal void ReadAll ()
  111. {
  112. if (!isRead || totalRead >= contentLength || nextReadCalled)
  113. return;
  114. pending.WaitOne ();
  115. lock (this) {
  116. if (totalRead >= contentLength)
  117. return;
  118. byte [] b = null;
  119. int diff = readBufferSize - readBufferOffset;
  120. int new_size;
  121. if (contentLength == Int32.MaxValue) {
  122. MemoryStream ms = new MemoryStream ();
  123. if (readBuffer != null && diff > 0)
  124. ms.Write (readBuffer, readBufferOffset, diff);
  125. byte [] buffer = new byte [2048];
  126. int read;
  127. while ((read = cnc.Read (buffer, 0, 2048)) != 0)
  128. ms.Write (buffer, 0, read);
  129. b = ms.GetBuffer ();
  130. new_size = (int) ms.Length;
  131. contentLength = new_size;
  132. } else {
  133. new_size = contentLength - totalRead;
  134. b = new byte [new_size];
  135. if (readBuffer != null && diff > 0)
  136. Buffer.BlockCopy (readBuffer, readBufferOffset, b, 0, diff);
  137. int remaining = new_size - diff;
  138. int r = -1;
  139. while (remaining > 0 && r != 0) {
  140. r = cnc.Read (b, diff, remaining);
  141. remaining -= r;
  142. diff += r;
  143. }
  144. }
  145. readBuffer = b;
  146. readBufferOffset = 0;
  147. readBufferSize = new_size;
  148. totalRead = 0;
  149. nextReadCalled = true;
  150. }
  151. cnc.NextRead ();
  152. }
  153. static void CallbackWrapper (IAsyncResult r)
  154. {
  155. WebAsyncResult result = (WebAsyncResult) r.AsyncState;
  156. result.InnerAsyncResult = r;
  157. result.DoCallback ();
  158. }
  159. public override int Read (byte [] buffer, int offset, int size)
  160. {
  161. if (!isRead)
  162. throw new NotSupportedException ("this stream does not allow reading");
  163. if (totalRead >= contentLength)
  164. return 0;
  165. IAsyncResult res = BeginRead (buffer, offset, size, null, null);
  166. return EndRead (res);
  167. }
  168. public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
  169. AsyncCallback cb, object state)
  170. {
  171. if (!isRead)
  172. throw new NotSupportedException ("this stream does not allow reading");
  173. if (buffer == null)
  174. throw new ArgumentNullException ("buffer");
  175. int length = buffer.Length;
  176. if (size < 0 || offset < 0 || length < offset || length - offset < size)
  177. throw new ArgumentOutOfRangeException ();
  178. WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
  179. if (totalRead >= contentLength) {
  180. result.SetCompleted (true, -1);
  181. result.DoCallback ();
  182. return result;
  183. }
  184. int remaining = readBufferSize - readBufferOffset;
  185. if (remaining > 0) {
  186. int copy = (remaining > size) ? size : remaining;
  187. Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
  188. readBufferOffset += copy;
  189. offset += copy;
  190. size -= copy;
  191. totalRead += copy;
  192. if (size == 0 || totalRead >= contentLength) {
  193. result.SetCompleted (true, copy);
  194. result.DoCallback ();
  195. return result;
  196. }
  197. result.NBytes = copy;
  198. }
  199. lock (this) {
  200. pendingReads++;
  201. pending.Reset ();
  202. }
  203. if (cb != null)
  204. cb = new AsyncCallback (CallbackWrapper);
  205. if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
  206. size = contentLength - totalRead;
  207. result.InnerAsyncResult = cnc.BeginRead (buffer, offset, size, cb, result);
  208. return result;
  209. }
  210. public override int EndRead (IAsyncResult r)
  211. {
  212. WebAsyncResult result = (WebAsyncResult) r;
  213. if (!result.IsCompleted) {
  214. int nbytes = cnc.EndRead (result.InnerAsyncResult);
  215. lock (this) {
  216. pendingReads--;
  217. if (pendingReads == 0)
  218. pending.Set ();
  219. }
  220. bool finished = (nbytes == -1);
  221. if (finished && result.NBytes > 0)
  222. nbytes = 0;
  223. result.SetCompleted (false, nbytes + result.NBytes);
  224. totalRead += nbytes;
  225. if (finished || nbytes == 0)
  226. contentLength = totalRead;
  227. }
  228. if (totalRead >= contentLength && !nextReadCalled) {
  229. nextReadCalled = true;
  230. cnc.NextRead ();
  231. }
  232. return result.NBytes;
  233. }
  234. public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
  235. AsyncCallback cb, object state)
  236. {
  237. if (isRead)
  238. throw new NotSupportedException ("this stream does not allow writing");
  239. if (buffer == null)
  240. throw new ArgumentNullException ("buffer");
  241. int length = buffer.Length;
  242. if (size < 0 || offset < 0 || length < offset || length - offset < size)
  243. throw new ArgumentOutOfRangeException ();
  244. if (sendChunked) {
  245. lock (this) {
  246. pendingWrites++;
  247. pending.Reset ();
  248. }
  249. }
  250. WebAsyncResult result = new WebAsyncResult (cb, state);
  251. if (allowBuffering) {
  252. writeBuffer.Write (buffer, offset, size);
  253. if (!sendChunked) {
  254. result.SetCompleted (true, 0);
  255. result.DoCallback ();
  256. return result;
  257. }
  258. }
  259. AsyncCallback callback = null;
  260. if (cb != null)
  261. callback = new AsyncCallback (CallbackWrapper);
  262. if (sendChunked) {
  263. WriteRequest ();
  264. string cSize = String.Format ("{0:X}\r\n", size);
  265. byte [] head = Encoding.ASCII.GetBytes (cSize);
  266. int chunkSize = 2 + size + head.Length;
  267. byte [] newBuffer = new byte [chunkSize];
  268. Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
  269. Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
  270. Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
  271. buffer = newBuffer;
  272. offset = 0;
  273. size = chunkSize;
  274. }
  275. result.InnerAsyncResult = cnc.BeginWrite (buffer, offset, size, callback, result);
  276. return result;
  277. }
  278. public override void EndWrite (IAsyncResult r)
  279. {
  280. if (r == null)
  281. throw new ArgumentNullException ("r");
  282. if (allowBuffering && !sendChunked)
  283. return;
  284. WebAsyncResult result = r as WebAsyncResult;
  285. if (result == null)
  286. throw new ArgumentException ("Invalid IAsyncResult");
  287. if (result.GotException)
  288. throw result.Exception;
  289. cnc.EndWrite (result.InnerAsyncResult);
  290. if (sendChunked) {
  291. lock (this) {
  292. pendingWrites--;
  293. if (pendingWrites == 0)
  294. pending.Set ();
  295. }
  296. }
  297. }
  298. public override void Write (byte [] buffer, int offset, int size)
  299. {
  300. if (isRead)
  301. throw new NotSupportedException ("This stream does not allow writing");
  302. IAsyncResult res = BeginWrite (buffer, offset, size, null, null);
  303. EndWrite (res);
  304. }
  305. public override void Flush ()
  306. {
  307. }
  308. internal void SetHeaders (byte [] buffer, int offset, int size)
  309. {
  310. if (headersSent)
  311. return;
  312. if (!allowBuffering || sendChunked) {
  313. headersSent = true;
  314. try {
  315. cnc.Write (buffer, offset, size);
  316. } catch (IOException) {
  317. if (cnc.Connected)
  318. throw;
  319. if (!cnc.TryReconnect ())
  320. throw;
  321. cnc.Write (buffer, offset, size);
  322. }
  323. } else {
  324. headers = new byte [size];
  325. Buffer.BlockCopy (buffer, offset, headers, 0, size);
  326. }
  327. }
  328. internal void WriteRequest ()
  329. {
  330. if (requestWritten)
  331. return;
  332. if (sendChunked) {
  333. request.SendRequestHeaders ();
  334. requestWritten = true;
  335. return;
  336. }
  337. if (!allowBuffering || writeBuffer == null)
  338. return;
  339. byte [] bytes = writeBuffer.GetBuffer ();
  340. int length = (int) writeBuffer.Length;
  341. if (request.ContentLength != -1 && request.ContentLength < length) {
  342. throw new ProtocolViolationException ("Specified Content-Length is less than the " +
  343. "number of bytes to write");
  344. }
  345. request.InternalContentLength = length;
  346. request.SendRequestHeaders ();
  347. requestWritten = true;
  348. while (true) {
  349. cnc.Write (headers, 0, headers.Length);
  350. if (!cnc.Connected) {
  351. if (!cnc.TryReconnect ())
  352. return;
  353. continue;
  354. }
  355. headersSent = true;
  356. if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
  357. return;
  358. cnc.Write (bytes, 0, length);
  359. if (!cnc.Connected && cnc.TryReconnect ())
  360. continue;
  361. break;
  362. }
  363. }
  364. internal void InternalClose ()
  365. {
  366. disposed = true;
  367. }
  368. public override void Close ()
  369. {
  370. if (sendChunked) {
  371. pending.WaitOne ();
  372. byte [] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
  373. cnc.Write (chunk, 0, chunk.Length);
  374. return;
  375. }
  376. if (isRead || !allowBuffering || disposed)
  377. return;
  378. disposed = true;
  379. long length = request.ContentLength;
  380. if (length != -1 && length > writeBuffer.Length)
  381. throw new IOException ("Cannot close the stream until all bytes are written");
  382. WriteRequest ();
  383. }
  384. internal void ResetWriteBuffer ()
  385. {
  386. if (!allowBuffering)
  387. return;
  388. writeBuffer = new MemoryStream ();
  389. requestWritten = false;
  390. headersSent = false;
  391. }
  392. public override long Seek (long a, SeekOrigin b)
  393. {
  394. throw new NotSupportedException ();
  395. }
  396. public override void SetLength (long a)
  397. {
  398. throw new NotSupportedException ();
  399. }
  400. public override bool CanSeek {
  401. get { return false; }
  402. }
  403. public override bool CanRead {
  404. get { return isRead; }
  405. }
  406. public override bool CanWrite {
  407. get { return !isRead; }
  408. }
  409. public override long Length {
  410. get { throw new NotSupportedException (); }
  411. }
  412. public override long Position {
  413. get { throw new NotSupportedException (); }
  414. set { throw new NotSupportedException (); }
  415. }
  416. }
  417. }