WebConnectionStream.cs 14 KB

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