WebConnectionStream.cs 12 KB

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