WebConnection.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. WaitOrTimerCallback initConn;
  31. bool keepAlive;
  32. bool aborted;
  33. byte [] buffer;
  34. static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
  35. EventHandler abortHandler;
  36. ReadState readState;
  37. internal WebConnectionData Data;
  38. WebConnectionStream prevStream;
  39. bool chunkedRead;
  40. ChunkStream chunkStream;
  41. AutoResetEvent waitForContinue;
  42. AutoResetEvent goAhead;
  43. bool waitingForContinue;
  44. Queue queue;
  45. bool reused;
  46. public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
  47. {
  48. this.group = group;
  49. this.sPoint = sPoint;
  50. buffer = new byte [4096];
  51. readState = ReadState.None;
  52. Data = new WebConnectionData ();
  53. initConn = new WaitOrTimerCallback (InitConnection);
  54. abortHandler = new EventHandler (Abort);
  55. goAhead = new AutoResetEvent (true);
  56. queue = new Queue (1);
  57. }
  58. public void Connect ()
  59. {
  60. lock (this) {
  61. if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
  62. reused = true;
  63. return;
  64. }
  65. reused = false;
  66. if (socket != null) {
  67. socket.Close();
  68. socket = null;
  69. }
  70. chunkStream = null;
  71. IPHostEntry hostEntry = sPoint.HostEntry;
  72. if (hostEntry == null) {
  73. status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
  74. WebExceptionStatus.NameResolutionFailure;
  75. return;
  76. }
  77. foreach (IPAddress address in hostEntry.AddressList) {
  78. socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  79. try {
  80. socket.Connect (new IPEndPoint(address, sPoint.Address.Port));
  81. status = WebExceptionStatus.Success;
  82. break;
  83. } catch (SocketException) {
  84. socket.Close();
  85. socket = null;
  86. status = WebExceptionStatus.ConnectFailure;
  87. }
  88. }
  89. }
  90. }
  91. bool CreateStream (HttpWebRequest request)
  92. {
  93. //TODO: create stream for https
  94. try {
  95. nstream = new NetworkStream (socket, false);
  96. } catch (Exception) {
  97. status = WebExceptionStatus.ConnectFailure;
  98. return false;
  99. }
  100. return true;
  101. }
  102. void HandleError (WebExceptionStatus st, Exception e)
  103. {
  104. status = st;
  105. lock (this) {
  106. busy = false;
  107. if (st == WebExceptionStatus.RequestCanceled)
  108. Data = new WebConnectionData ();
  109. status = st;
  110. }
  111. if (e == null) { // At least we now where it comes from
  112. try {
  113. throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
  114. } catch (Exception e2) {
  115. e = e2;
  116. }
  117. }
  118. if (Data != null && Data.request != null)
  119. Data.request.SetResponseError (st, e);
  120. Close (true);
  121. }
  122. internal bool WaitForContinue (byte [] headers, int offset, int size)
  123. {
  124. waitingForContinue = sPoint.SendContinue;
  125. if (waitingForContinue && waitForContinue == null)
  126. waitForContinue = new AutoResetEvent (false);
  127. Write (headers, offset, size);
  128. if (!waitingForContinue)
  129. return false;
  130. bool result = waitForContinue.WaitOne (2000, false);
  131. waitingForContinue = false;
  132. if (result) {
  133. sPoint.SendContinue = true;
  134. if (Data.request.ExpectContinue)
  135. Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
  136. } else {
  137. sPoint.SendContinue = false;
  138. }
  139. return result;
  140. }
  141. static void ReadDone (IAsyncResult result)
  142. {
  143. WebConnection cnc = (WebConnection) result.AsyncState;
  144. WebConnectionData data = cnc.Data;
  145. NetworkStream ns = cnc.nstream;
  146. if (ns == null) {
  147. cnc.Close (true);
  148. return;
  149. }
  150. int nread = -1;
  151. try {
  152. nread = ns.EndRead (result);
  153. } catch (Exception e) {
  154. cnc.status = WebExceptionStatus.ReceiveFailure;
  155. cnc.HandleError (cnc.status, e);
  156. return;
  157. }
  158. if (nread == 0) {
  159. cnc.status = WebExceptionStatus.ReceiveFailure;
  160. cnc.HandleError (cnc.status, null);
  161. return;
  162. }
  163. if (nread < 0) {
  164. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
  165. return;
  166. }
  167. //Console.WriteLine (System.Text.Encoding.Default.GetString (cnc.buffer, 0, nread));
  168. int pos = -1;
  169. if (cnc.readState == ReadState.None) {
  170. Exception exc = null;
  171. try {
  172. pos = cnc.GetResponse (cnc.buffer, nread);
  173. if (data.StatusCode == 100) {
  174. cnc.readState = ReadState.None;
  175. InitRead (cnc);
  176. cnc.sPoint.SendContinue = true;
  177. if (cnc.waitingForContinue) {
  178. cnc.waitForContinue.Set ();
  179. } else if (data.request.ExpectContinue) { // We get a 100 after waiting for it.
  180. data.request.DoContinueDelegate (data.StatusCode, data.Headers);
  181. }
  182. return;
  183. }
  184. } catch (Exception e) {
  185. exc = e;
  186. }
  187. if (pos == -1 || exc != null) {
  188. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc);
  189. return;
  190. }
  191. }
  192. if (cnc.readState != ReadState.Content) {
  193. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
  194. return;
  195. }
  196. WebConnectionStream stream = new WebConnectionStream (cnc);
  197. string contentType = data.Headers ["Transfer-Encoding"];
  198. cnc.chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
  199. if (!cnc.chunkedRead) {
  200. stream.ReadBuffer = cnc.buffer;
  201. stream.ReadBufferOffset = pos;
  202. stream.ReadBufferSize = nread;
  203. } else if (cnc.chunkStream == null) {
  204. cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
  205. } else {
  206. cnc.chunkStream.ResetBuffer ();
  207. cnc.chunkStream.Write (cnc.buffer, pos, nread);
  208. }
  209. data.stream = stream;
  210. lock (cnc) {
  211. if (cnc.queue.Count > 0)
  212. stream.ReadAll ();
  213. else
  214. {
  215. cnc.prevStream = stream;
  216. stream.CheckComplete ();
  217. }
  218. }
  219. data.request.SetResponseData (data);
  220. }
  221. static void InitRead (object state)
  222. {
  223. WebConnection cnc = (WebConnection) state;
  224. NetworkStream ns = cnc.nstream;
  225. try {
  226. ns.BeginRead (cnc.buffer, 0, cnc.buffer.Length, readDoneDelegate, cnc);
  227. } catch (Exception e) {
  228. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e);
  229. }
  230. }
  231. int GetResponse (byte [] buffer, int max)
  232. {
  233. int pos = 0;
  234. string line = null;
  235. bool lineok = false;
  236. if (readState == ReadState.None) {
  237. lineok = ReadLine (buffer, ref pos, max, ref line);
  238. if (!lineok)
  239. return -1;
  240. readState = ReadState.Status;
  241. string [] parts = line.Split (' ');
  242. if (parts.Length < 3)
  243. return -1;
  244. if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
  245. Data.Version = HttpVersion.Version11;
  246. } else {
  247. Data.Version = HttpVersion.Version10;
  248. }
  249. Data.StatusCode = (int) UInt32.Parse (parts [1]);
  250. Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
  251. if (pos >= max)
  252. return pos;
  253. }
  254. if (readState == ReadState.Status) {
  255. readState = ReadState.Headers;
  256. Data.Headers = new WebHeaderCollection ();
  257. ArrayList headers = new ArrayList ();
  258. bool finished = false;
  259. while (!finished) {
  260. if (ReadLine (buffer, ref pos, max, ref line) == false)
  261. break;
  262. if (line == null) {
  263. // Empty line: end of headers
  264. finished = true;
  265. continue;
  266. }
  267. if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
  268. int count = headers.Count - 1;
  269. if (count < 0)
  270. break;
  271. string prev = (string) headers [count] + line;
  272. headers [count] = prev;
  273. } else {
  274. headers.Add (line);
  275. }
  276. }
  277. if (!finished) {
  278. // handle the error...
  279. } else {
  280. foreach (string s in headers)
  281. Data.Headers.Add (s);
  282. readState = ReadState.Content;
  283. return pos;
  284. }
  285. }
  286. return -1;
  287. }
  288. void InitConnection (object state, bool notUsed)
  289. {
  290. HttpWebRequest request = (HttpWebRequest) state;
  291. if (status == WebExceptionStatus.RequestCanceled) {
  292. busy = false;
  293. Data = new WebConnectionData ();
  294. goAhead.Set ();
  295. aborted = false;
  296. SendNext ();
  297. return;
  298. }
  299. keepAlive = request.KeepAlive;
  300. Data = new WebConnectionData ();
  301. Data.request = request;
  302. Connect ();
  303. if (status != WebExceptionStatus.Success) {
  304. request.SetWriteStreamError (status);
  305. Close (true);
  306. return;
  307. }
  308. if (!CreateStream (request)) {
  309. request.SetWriteStreamError (status);
  310. Close (true);
  311. return;
  312. }
  313. readState = ReadState.None;
  314. request.SetWriteStream (new WebConnectionStream (this, request));
  315. InitRead (this);
  316. }
  317. internal EventHandler SendRequest (HttpWebRequest request)
  318. {
  319. lock (this) {
  320. if (prevStream != null && socket != null && socket.Connected) {
  321. prevStream.ReadAll ();
  322. prevStream = null;
  323. }
  324. if (!busy) {
  325. busy = true;
  326. ThreadPool.RegisterWaitForSingleObject (goAhead, initConn,
  327. request, -1, true);
  328. } else {
  329. queue.Enqueue (request);
  330. }
  331. }
  332. return abortHandler;
  333. }
  334. void SendNext ()
  335. {
  336. lock (this) {
  337. if (queue.Count > 0) {
  338. prevStream = null;
  339. SendRequest ((HttpWebRequest) queue.Dequeue ());
  340. }
  341. }
  342. }
  343. internal void NextRead ()
  344. {
  345. lock (this) {
  346. busy = false;
  347. string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
  348. string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
  349. bool keepAlive = (Data.Version == HttpVersion.Version11);
  350. if (cncHeader != null) {
  351. cncHeader = cncHeader.ToLower ();
  352. keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive") != -1);
  353. }
  354. if ((socket != null && !socket.Connected) ||
  355. (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
  356. Close (false);
  357. }
  358. goAhead.Set ();
  359. if (queue.Count > 0) {
  360. prevStream = null;
  361. SendRequest ((HttpWebRequest) queue.Dequeue ());
  362. }
  363. }
  364. }
  365. static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
  366. {
  367. bool foundCR = false;
  368. StringBuilder text = new StringBuilder ();
  369. int c = 0;
  370. while (start < max) {
  371. c = (int) buffer [start++];
  372. if (c == '\n') { // newline
  373. if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
  374. text.Length--;
  375. foundCR = false;
  376. break;
  377. } else if (foundCR) {
  378. text.Length--;
  379. break;
  380. }
  381. if (c == '\r')
  382. foundCR = true;
  383. text.Append ((char) c);
  384. }
  385. if (c != '\n' && c != '\r')
  386. return false;
  387. if (text.Length == 0) {
  388. output = null;
  389. return (c == '\n' || c == '\r');
  390. }
  391. if (foundCR)
  392. text.Length--;
  393. output = text.ToString ();
  394. return true;
  395. }
  396. internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  397. {
  398. if (nstream == null)
  399. return null;
  400. IAsyncResult result = null;
  401. if (!chunkedRead || chunkStream.WantMore) {
  402. try {
  403. result = nstream.BeginRead (buffer, offset, size, cb, state);
  404. } catch (Exception) {
  405. status = WebExceptionStatus.ReceiveFailure;
  406. throw;
  407. }
  408. }
  409. if (chunkedRead) {
  410. WebAsyncResult wr = new WebAsyncResult (null, null, buffer, offset, size);
  411. wr.InnerAsyncResult = result;
  412. return wr;
  413. }
  414. return result;
  415. }
  416. internal int EndRead (IAsyncResult result)
  417. {
  418. if (nstream == null)
  419. return 0;
  420. if (chunkedRead) {
  421. WebAsyncResult wr = (WebAsyncResult) result;
  422. int nbytes = 0;
  423. if (wr.InnerAsyncResult != null)
  424. nbytes = nstream.EndRead (wr.InnerAsyncResult);
  425. chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
  426. return nbytes;
  427. }
  428. return nstream.EndRead (result);
  429. }
  430. internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  431. {
  432. IAsyncResult result = null;
  433. if (nstream == null)
  434. return null;
  435. try {
  436. result = nstream.BeginWrite (buffer, offset, size, cb, state);
  437. } catch (Exception) {
  438. status = WebExceptionStatus.SendFailure;
  439. throw;
  440. }
  441. return result;
  442. }
  443. internal void EndWrite (IAsyncResult result)
  444. {
  445. if (nstream != null)
  446. nstream.EndWrite (result);
  447. }
  448. internal int Read (byte [] buffer, int offset, int size)
  449. {
  450. if (nstream == null)
  451. return 0;
  452. int result = 0;
  453. try {
  454. if (!chunkedRead || chunkStream.WantMore)
  455. result = nstream.Read (buffer, offset, size);
  456. if (chunkedRead)
  457. chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
  458. } catch (Exception e) {
  459. status = WebExceptionStatus.ReceiveFailure;
  460. HandleError (status, e);
  461. }
  462. return result;
  463. }
  464. internal void Write (byte [] buffer, int offset, int size)
  465. {
  466. if (nstream == null)
  467. return;
  468. try {
  469. nstream.Write (buffer, offset, size);
  470. } catch (Exception) {
  471. }
  472. }
  473. internal bool TryReconnect ()
  474. {
  475. lock (this) {
  476. if (!reused) {
  477. HandleError (WebExceptionStatus.SendFailure, null);
  478. return false;
  479. }
  480. Close (false);
  481. reused = false;
  482. Connect ();
  483. if (status != WebExceptionStatus.Success) {
  484. HandleError (WebExceptionStatus.SendFailure, null);
  485. return false;
  486. }
  487. if (!CreateStream (Data.request)) {
  488. HandleError (WebExceptionStatus.SendFailure, null);
  489. return false;
  490. }
  491. }
  492. return true;
  493. }
  494. void Close (bool sendNext)
  495. {
  496. lock (this) {
  497. busy = false;
  498. if (nstream != null) {
  499. try {
  500. nstream.Close ();
  501. } catch {}
  502. nstream = null;
  503. }
  504. if (socket != null) {
  505. try {
  506. socket.Close ();
  507. } catch {}
  508. socket = null;
  509. }
  510. if (sendNext) {
  511. goAhead.Set ();
  512. SendNext ();
  513. }
  514. }
  515. }
  516. void Abort (object sender, EventArgs args)
  517. {
  518. HandleError (WebExceptionStatus.RequestCanceled, null);
  519. }
  520. internal bool Busy {
  521. get { lock (this) return busy; }
  522. }
  523. internal bool Connected {
  524. get {
  525. lock (this) {
  526. return (socket != null && socket.Connected);
  527. }
  528. }
  529. }
  530. ~WebConnection ()
  531. {
  532. Close (false);
  533. }
  534. }
  535. }