WebConnectionStream.cs 12 KB

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