WebConnectionStream.cs 13 KB

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