WebConnection.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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.Init ();
  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. bool more = false;
  210. lock (cnc) {
  211. more = (cnc.queue.Count > 0);
  212. }
  213. if (more)
  214. stream.ReadAll ();
  215. data.stream = stream;
  216. stream.CheckComplete ();
  217. data.request.SetResponseData (data);
  218. lock (cnc) {
  219. cnc.prevStream = stream;
  220. }
  221. }
  222. static void InitRead (object state)
  223. {
  224. WebConnection cnc = (WebConnection) state;
  225. NetworkStream ns = cnc.nstream;
  226. try {
  227. ns.BeginRead (cnc.buffer, 0, cnc.buffer.Length, readDoneDelegate, cnc);
  228. } catch (Exception e) {
  229. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e);
  230. }
  231. }
  232. int GetResponse (byte [] buffer, int max)
  233. {
  234. int pos = 0;
  235. string line = null;
  236. bool lineok = false;
  237. if (readState == ReadState.None) {
  238. lineok = ReadLine (buffer, ref pos, max, ref line);
  239. if (!lineok)
  240. return -1;
  241. readState = ReadState.Status;
  242. string [] parts = line.Split (' ');
  243. if (parts.Length < 3)
  244. return -1;
  245. if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
  246. Data.Version = HttpVersion.Version11;
  247. } else {
  248. Data.Version = HttpVersion.Version10;
  249. }
  250. Data.StatusCode = (int) UInt32.Parse (parts [1]);
  251. Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
  252. if (pos >= max)
  253. return pos;
  254. }
  255. if (readState == ReadState.Status) {
  256. readState = ReadState.Headers;
  257. Data.Headers = new WebHeaderCollection ();
  258. ArrayList headers = new ArrayList ();
  259. bool finished = false;
  260. while (!finished) {
  261. if (ReadLine (buffer, ref pos, max, ref line) == false)
  262. break;
  263. if (line == null) {
  264. // Empty line: end of headers
  265. finished = true;
  266. continue;
  267. }
  268. if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
  269. int count = headers.Count - 1;
  270. if (count < 0)
  271. break;
  272. string prev = (string) headers [count] + line;
  273. headers [count] = prev;
  274. } else {
  275. headers.Add (line);
  276. }
  277. }
  278. if (!finished) {
  279. // handle the error...
  280. } else {
  281. foreach (string s in headers)
  282. Data.Headers.Add (s);
  283. readState = ReadState.Content;
  284. return pos;
  285. }
  286. }
  287. return -1;
  288. }
  289. void InitConnection (object state, bool notUsed)
  290. {
  291. HttpWebRequest request = (HttpWebRequest) state;
  292. // Just in case 2 requests are released
  293. bool relaunch = false;
  294. lock (this) {
  295. relaunch = busy;
  296. busy = true;
  297. }
  298. if (relaunch) {
  299. SendRequest (request);
  300. return;
  301. }
  302. //
  303. if (status == WebExceptionStatus.RequestCanceled) {
  304. busy = false;
  305. Data.Init ();
  306. goAhead.Set ();
  307. aborted = false;
  308. SendNext ();
  309. return;
  310. }
  311. keepAlive = request.KeepAlive;
  312. Data.Init ();
  313. Data.request = request;
  314. Connect ();
  315. if (status != WebExceptionStatus.Success) {
  316. request.SetWriteStreamError (status);
  317. Close (true);
  318. return;
  319. }
  320. if (!CreateStream (request)) {
  321. request.SetWriteStreamError (status);
  322. Close (true);
  323. return;
  324. }
  325. readState = ReadState.None;
  326. request.SetWriteStream (new WebConnectionStream (this, request));
  327. InitRead (this);
  328. }
  329. internal EventHandler SendRequest (HttpWebRequest request)
  330. {
  331. lock (this) {
  332. if (prevStream != null && socket != null && socket.Connected) {
  333. prevStream.ReadAll ();
  334. prevStream = null;
  335. }
  336. if (!busy) {
  337. ThreadPool.RegisterWaitForSingleObject (goAhead, initConn,
  338. request, -1, true);
  339. } else {
  340. queue.Enqueue (request);
  341. }
  342. }
  343. return abortHandler;
  344. }
  345. void SendNext ()
  346. {
  347. lock (this) {
  348. if (queue.Count > 0) {
  349. prevStream = null;
  350. SendRequest ((HttpWebRequest) queue.Dequeue ());
  351. }
  352. }
  353. }
  354. internal void NextRead ()
  355. {
  356. lock (this) {
  357. busy = false;
  358. string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
  359. string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
  360. bool keepAlive = (Data.Version == HttpVersion.Version11);
  361. if (cncHeader != null) {
  362. cncHeader = cncHeader.ToLower ();
  363. keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive") != -1);
  364. }
  365. if ((socket != null && !socket.Connected) ||
  366. (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
  367. Close (false);
  368. }
  369. goAhead.Set ();
  370. if (queue.Count > 0) {
  371. prevStream = null;
  372. SendRequest ((HttpWebRequest) queue.Dequeue ());
  373. }
  374. }
  375. }
  376. static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
  377. {
  378. bool foundCR = false;
  379. StringBuilder text = new StringBuilder ();
  380. int c = 0;
  381. while (start < max) {
  382. c = (int) buffer [start++];
  383. if (c == '\n') { // newline
  384. if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
  385. text.Length--;
  386. foundCR = false;
  387. break;
  388. } else if (foundCR) {
  389. text.Length--;
  390. break;
  391. }
  392. if (c == '\r')
  393. foundCR = true;
  394. text.Append ((char) c);
  395. }
  396. if (c != '\n' && c != '\r')
  397. return false;
  398. if (text.Length == 0) {
  399. output = null;
  400. return (c == '\n' || c == '\r');
  401. }
  402. if (foundCR)
  403. text.Length--;
  404. output = text.ToString ();
  405. return true;
  406. }
  407. internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  408. {
  409. if (nstream == null)
  410. return null;
  411. IAsyncResult result = null;
  412. if (!chunkedRead || chunkStream.WantMore) {
  413. try {
  414. result = nstream.BeginRead (buffer, offset, size, cb, state);
  415. } catch (Exception) {
  416. status = WebExceptionStatus.ReceiveFailure;
  417. throw;
  418. }
  419. }
  420. if (chunkedRead) {
  421. WebAsyncResult wr = new WebAsyncResult (null, null, buffer, offset, size);
  422. wr.InnerAsyncResult = result;
  423. return wr;
  424. }
  425. return result;
  426. }
  427. internal int EndRead (IAsyncResult result)
  428. {
  429. if (nstream == null)
  430. return 0;
  431. if (chunkedRead) {
  432. WebAsyncResult wr = (WebAsyncResult) result;
  433. int nbytes = 0;
  434. if (wr.InnerAsyncResult != null)
  435. nbytes = nstream.EndRead (wr.InnerAsyncResult);
  436. chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
  437. return nbytes;
  438. }
  439. return nstream.EndRead (result);
  440. }
  441. internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  442. {
  443. IAsyncResult result = null;
  444. if (nstream == null)
  445. return null;
  446. try {
  447. result = nstream.BeginWrite (buffer, offset, size, cb, state);
  448. } catch (Exception) {
  449. status = WebExceptionStatus.SendFailure;
  450. throw;
  451. }
  452. return result;
  453. }
  454. internal void EndWrite (IAsyncResult result)
  455. {
  456. if (nstream != null)
  457. nstream.EndWrite (result);
  458. }
  459. internal int Read (byte [] buffer, int offset, int size)
  460. {
  461. if (nstream == null)
  462. return 0;
  463. int result = 0;
  464. try {
  465. if (!chunkedRead || chunkStream.WantMore)
  466. result = nstream.Read (buffer, offset, size);
  467. if (chunkedRead)
  468. chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
  469. } catch (Exception e) {
  470. status = WebExceptionStatus.ReceiveFailure;
  471. HandleError (status, e);
  472. }
  473. return result;
  474. }
  475. internal void Write (byte [] buffer, int offset, int size)
  476. {
  477. if (nstream == null)
  478. return;
  479. try {
  480. nstream.Write (buffer, offset, size);
  481. } catch (Exception) {
  482. }
  483. }
  484. internal bool TryReconnect ()
  485. {
  486. lock (this) {
  487. if (!reused) {
  488. HandleError (WebExceptionStatus.SendFailure, null);
  489. return false;
  490. }
  491. Close (false);
  492. reused = false;
  493. Connect ();
  494. if (status != WebExceptionStatus.Success) {
  495. HandleError (WebExceptionStatus.SendFailure, null);
  496. return false;
  497. }
  498. if (!CreateStream (Data.request)) {
  499. HandleError (WebExceptionStatus.SendFailure, null);
  500. return false;
  501. }
  502. }
  503. return true;
  504. }
  505. void Close (bool sendNext)
  506. {
  507. lock (this) {
  508. busy = false;
  509. if (nstream != null) {
  510. try {
  511. nstream.Close ();
  512. } catch {}
  513. nstream = null;
  514. }
  515. if (socket != null) {
  516. try {
  517. socket.Close ();
  518. } catch {}
  519. socket = null;
  520. }
  521. if (sendNext) {
  522. goAhead.Set ();
  523. SendNext ();
  524. }
  525. }
  526. }
  527. void Abort (object sender, EventArgs args)
  528. {
  529. HandleError (WebExceptionStatus.RequestCanceled, null);
  530. }
  531. internal bool Busy {
  532. get { lock (this) return busy; }
  533. }
  534. internal bool Connected {
  535. get {
  536. lock (this) {
  537. return (socket != null && socket.Connected);
  538. }
  539. }
  540. }
  541. ~WebConnection ()
  542. {
  543. Close (false);
  544. }
  545. }
  546. }