WebConnection.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. //
  2. // System.Net.WebConnection
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System.Collections;
  10. using System.Net.Sockets;
  11. using System.Text;
  12. using System.Threading;
  13. namespace System.Net
  14. {
  15. enum ReadState
  16. {
  17. None,
  18. Status,
  19. Headers,
  20. Content
  21. }
  22. class WebConnection
  23. {
  24. ServicePoint sPoint;
  25. NetworkStream nstream;
  26. Socket socket;
  27. WebExceptionStatus status;
  28. WebConnectionGroup group;
  29. bool busy;
  30. ArrayList queue;
  31. WaitOrTimerCallback initConn;
  32. internal ManualResetEvent dataAvailable;
  33. bool keepAlive;
  34. bool aborted;
  35. byte [] buffer;
  36. internal static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
  37. EventHandler abortHandler;
  38. ReadState readState;
  39. internal WebConnectionData Data;
  40. WebConnectionStream prevStream;
  41. bool chunkedRead;
  42. ChunkStream chunkStream;
  43. AutoResetEvent waitForContinue;
  44. bool waitingForContinue;
  45. public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
  46. {
  47. this.group = group;
  48. this.sPoint = sPoint;
  49. queue = new ArrayList (1);
  50. dataAvailable = new ManualResetEvent (true);
  51. buffer = new byte [4096];
  52. readState = ReadState.None;
  53. Data = new WebConnectionData ();
  54. initConn = new WaitOrTimerCallback (InitConnection);
  55. abortHandler = new EventHandler (Abort);
  56. }
  57. public void Connect ()
  58. {
  59. if (socket != null && socket.Connected && status == WebExceptionStatus.Success)
  60. return;
  61. lock (this) {
  62. if (socket != null && socket.Connected && status == WebExceptionStatus.Success)
  63. return;
  64. if (socket == null)
  65. socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
  66. status = sPoint.Connect (socket);
  67. chunkStream = null;
  68. }
  69. }
  70. bool CreateStream (HttpWebRequest request)
  71. {
  72. //TODO: create stream for https
  73. try {
  74. nstream = new NetworkStream (socket, false);
  75. } catch (Exception e) {
  76. status = WebExceptionStatus.ConnectFailure;
  77. return false;
  78. }
  79. return true;
  80. }
  81. void HandleError (WebExceptionStatus st, Exception e)
  82. {
  83. status = st;
  84. Close ();
  85. if (e == null) { // At least we noe where it comes from
  86. try {
  87. throw new Exception ();
  88. } catch (Exception e2) {
  89. e = e2;
  90. }
  91. }
  92. if (Data != null && Data.request != null)
  93. Data.request.SetResponseError (st, e);
  94. }
  95. internal bool WaitForContinue (byte [] headers, int offset, int size)
  96. {
  97. if (waitForContinue == null)
  98. waitForContinue = new AutoResetEvent (false);
  99. Write (headers, offset, size);
  100. waitingForContinue = true;
  101. bool result = waitForContinue.WaitOne (Timeout.Infinite, false);
  102. waitingForContinue = false;
  103. if (result)
  104. Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
  105. return result;
  106. }
  107. static void ReadDone (IAsyncResult result)
  108. {
  109. WebConnection cnc = (WebConnection) result.AsyncState;
  110. NetworkStream ns = cnc.nstream;
  111. if (ns == null)
  112. return;
  113. int nread = -1;
  114. cnc.dataAvailable.Reset ();
  115. try {
  116. nread = ns.EndRead (result);
  117. } catch (Exception e) {
  118. cnc.status = WebExceptionStatus.ReceiveFailure;
  119. cnc.HandleError (cnc.status, e);
  120. cnc.dataAvailable.Set ();
  121. return;
  122. }
  123. if (nread == 0) {
  124. Console.WriteLine ("nread == 0");
  125. return;
  126. }
  127. if (nread < 0) {
  128. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
  129. cnc.dataAvailable.Set ();
  130. return;
  131. }
  132. //Console.WriteLine (System.Text.Encoding.Default.GetString (cnc.buffer, 0, nread));
  133. int pos = -1;
  134. if (cnc.readState == ReadState.None) {
  135. Exception exc = null;
  136. try {
  137. pos = cnc.GetResponse (cnc.buffer, nread);
  138. } catch (Exception e) {
  139. exc = e;
  140. }
  141. if (pos == -1 || exc != null) {
  142. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc);
  143. cnc.dataAvailable.Set ();
  144. return;
  145. }
  146. }
  147. if (cnc.readState != ReadState.Content) {
  148. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
  149. cnc.dataAvailable.Set ();
  150. return;
  151. }
  152. if (cnc.waitingForContinue) {
  153. cnc.waitForContinue.Set ();
  154. if (cnc.Data.StatusCode == 100) {
  155. cnc.readState = ReadState.None;
  156. InitRead (cnc);
  157. return;
  158. }
  159. }
  160. WebConnectionStream stream = new WebConnectionStream (cnc);
  161. string contentType = cnc.Data.Headers ["Transfer-Encoding"];
  162. cnc.chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
  163. if (!cnc.chunkedRead) {
  164. stream.ReadBuffer = cnc.buffer;
  165. stream.ReadBufferOffset = pos;
  166. stream.ReadBufferSize = nread;
  167. stream.CheckComplete ();
  168. } else if (cnc.chunkStream == null) {
  169. cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, cnc.Data.Headers);
  170. } else {
  171. cnc.chunkStream.ResetBuffer ();
  172. cnc.chunkStream.Write (cnc.buffer, pos, nread);
  173. }
  174. cnc.prevStream = stream;
  175. cnc.Data.stream = stream;
  176. cnc.Data.request.SetResponseData (cnc.Data);
  177. }
  178. static void InitRead (object state)
  179. {
  180. WebConnection cnc = (WebConnection) state;
  181. NetworkStream ns = cnc.nstream;
  182. try {
  183. ns.BeginRead (cnc.buffer, 0, cnc.buffer.Length, readDoneDelegate, cnc);
  184. } catch (Exception e) {
  185. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e);
  186. cnc.dataAvailable.Set ();
  187. }
  188. }
  189. int GetResponse (byte [] buffer, int max)
  190. {
  191. int pos = 0;
  192. string line = null;
  193. bool lineok = false;
  194. if (readState == ReadState.None) {
  195. lineok = ReadLine (buffer, ref pos, max, ref line);
  196. if (!lineok)
  197. return -1;
  198. readState = ReadState.Status;
  199. string [] parts = line.Split (' ');
  200. if (parts.Length < 3)
  201. return -1;
  202. if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
  203. Data.Version = HttpVersion.Version11;
  204. } else {
  205. Data.Version = HttpVersion.Version10;
  206. }
  207. Data.StatusCode = (int) UInt32.Parse (parts [1]);
  208. Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
  209. if (pos >= max)
  210. return pos;
  211. }
  212. if (readState == ReadState.Status) {
  213. readState = ReadState.Headers;
  214. Data.Headers = new WebHeaderCollection ();
  215. ArrayList headers = new ArrayList ();
  216. bool finished = false;
  217. while (!finished) {
  218. if (ReadLine (buffer, ref pos, max, ref line) == false)
  219. break;
  220. if (line == null) {
  221. // Empty line: end of headers
  222. finished = true;
  223. continue;
  224. }
  225. if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
  226. int count = headers.Count - 1;
  227. if (count < 0)
  228. break;
  229. string prev = (string) headers [count] + line;
  230. headers [count] = prev;
  231. } else {
  232. headers.Add (line);
  233. }
  234. }
  235. if (!finished) {
  236. // handle the error...
  237. } else {
  238. foreach (string s in headers)
  239. Data.Headers.Add (s);
  240. readState = ReadState.Content;
  241. return pos;
  242. }
  243. }
  244. return -1;
  245. }
  246. void InitConnection (object state, bool notUsed)
  247. {
  248. HttpWebRequest request = (HttpWebRequest) state;
  249. if (aborted) {
  250. status = WebExceptionStatus.RequestCanceled;
  251. request.SetWriteStreamError (status);
  252. return;
  253. }
  254. Connect ();
  255. if (status != WebExceptionStatus.Success) {
  256. request.SetWriteStreamError (status);
  257. Close ();
  258. return;
  259. }
  260. if (!CreateStream (request)) {
  261. request.SetWriteStreamError (status);
  262. Close ();
  263. return;
  264. }
  265. readState = ReadState.None;
  266. request.SetWriteStream (new WebConnectionStream (this, request));
  267. InitRead (this);
  268. }
  269. void BeginRequest (HttpWebRequest request)
  270. {
  271. lock (this) {
  272. keepAlive = request.KeepAlive;
  273. Data.Init ();
  274. Data.request = request;
  275. }
  276. ThreadPool.RegisterWaitForSingleObject (dataAvailable, initConn, request, -1, true);
  277. }
  278. internal EventHandler SendRequest (HttpWebRequest request)
  279. {
  280. Monitor.Enter (this);
  281. if (prevStream != null && socket != null && socket.Connected) {
  282. prevStream.ReadAll ();
  283. prevStream = null;
  284. }
  285. if (!busy) {
  286. busy = true;
  287. Monitor.Exit (this);
  288. BeginRequest (request);
  289. } else {
  290. queue.Add (request);
  291. Monitor.Exit (this);
  292. }
  293. return abortHandler;
  294. }
  295. internal void NextRead ()
  296. {
  297. Monitor.Enter (this);
  298. string cncHeader = (Data.Headers != null) ? Data.Headers ["Connection"] : null;
  299. // Bug in xsp...? It does not send Connection: close. Well. it's 1.0
  300. if (Data.Version == HttpVersion.Version10 || (socket != null && !socket.Connected) || (!keepAlive ||
  301. (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
  302. Close ();
  303. }
  304. if (queue.Count > 0) {
  305. HttpWebRequest request = (HttpWebRequest) queue [0];
  306. queue.RemoveAt (0);
  307. Monitor.Exit (this);
  308. SendRequest (request);
  309. } else {
  310. busy = false;
  311. Monitor.Exit (this);
  312. }
  313. }
  314. static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
  315. {
  316. bool foundCR = false;
  317. StringBuilder text = new StringBuilder ();
  318. int c = 0;
  319. while (start < max) {
  320. c = (int) buffer [start++];
  321. if (c == '\n') { // newline
  322. if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
  323. text.Length--;
  324. foundCR = false;
  325. break;
  326. } else if (foundCR) {
  327. text.Length--;
  328. break;
  329. }
  330. if (c == '\r')
  331. foundCR = true;
  332. text.Append ((char) c);
  333. }
  334. if (c != '\n' && c != '\r')
  335. return false;
  336. if (text.Length == 0) {
  337. output = null;
  338. return (c == '\n' || c == '\r');
  339. }
  340. if (foundCR)
  341. text.Length--;
  342. output = text.ToString ();
  343. return true;
  344. }
  345. internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  346. {
  347. if (nstream == null)
  348. return null;
  349. IAsyncResult result = null;
  350. if (!chunkedRead || chunkStream.WantMore) {
  351. try {
  352. result = nstream.BeginRead (buffer, offset, size, cb, state);
  353. } catch (Exception e) {
  354. status = WebExceptionStatus.ReceiveFailure;
  355. throw;
  356. }
  357. }
  358. if (chunkedRead) {
  359. WebAsyncResult wr = new WebAsyncResult (null, null, buffer, offset, size);
  360. wr.InnerAsyncResult = result;
  361. return wr;
  362. }
  363. return result;
  364. }
  365. internal int EndRead (IAsyncResult result)
  366. {
  367. if (nstream == null)
  368. return 0;
  369. if (chunkedRead) {
  370. WebAsyncResult wr = (WebAsyncResult) result;
  371. int nbytes = 0;
  372. if (wr.InnerAsyncResult != null)
  373. nbytes = nstream.EndRead (wr.InnerAsyncResult);
  374. chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
  375. return nbytes;
  376. }
  377. return nstream.EndRead (result);
  378. }
  379. internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  380. {
  381. IAsyncResult result = null;
  382. if (nstream == null)
  383. return null;
  384. try {
  385. result = nstream.BeginWrite (buffer, offset, size, cb, state);
  386. } catch (Exception e) {
  387. status = WebExceptionStatus.SendFailure;
  388. throw;
  389. }
  390. return result;
  391. }
  392. internal void EndWrite (IAsyncResult result)
  393. {
  394. if (nstream != null)
  395. nstream.EndWrite (result);
  396. }
  397. internal int Read (byte [] buffer, int offset, int size)
  398. {
  399. if (nstream == null)
  400. return 0;
  401. int result = 0;
  402. try {
  403. if (!chunkedRead || chunkStream.WantMore)
  404. result = nstream.Read (buffer, offset, size);
  405. if (chunkedRead)
  406. chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
  407. } catch (Exception e) {
  408. status = WebExceptionStatus.ReceiveFailure;
  409. HandleError (status, e);
  410. }
  411. return result;
  412. }
  413. internal void Write (byte [] buffer, int offset, int size)
  414. {
  415. if (nstream == null)
  416. return;
  417. try {
  418. nstream.Write (buffer, offset, size);
  419. } catch (Exception e) {
  420. status = WebExceptionStatus.SendFailure;
  421. HandleError (status, e);
  422. }
  423. }
  424. void Close ()
  425. {
  426. if (nstream != null) {
  427. try {
  428. nstream.Close ();
  429. } catch {}
  430. nstream = null;
  431. }
  432. if (socket != null) {
  433. try {
  434. socket.Close ();
  435. } catch {}
  436. socket = null;
  437. }
  438. }
  439. void Abort (object sender, EventArgs args)
  440. {
  441. HandleError (WebExceptionStatus.RequestCanceled, null);
  442. }
  443. }
  444. }