WebConnection.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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. byte [] buffer;
  33. static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
  34. EventHandler abortHandler;
  35. ReadState readState;
  36. internal WebConnectionData Data;
  37. WebConnectionStream prevStream;
  38. bool chunkedRead;
  39. ChunkStream chunkStream;
  40. AutoResetEvent waitForContinue;
  41. AutoResetEvent goAhead;
  42. bool waitingForContinue;
  43. Queue queue;
  44. bool reused;
  45. public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
  46. {
  47. this.group = group;
  48. this.sPoint = sPoint;
  49. buffer = new byte [4096];
  50. readState = ReadState.None;
  51. Data = new WebConnectionData ();
  52. initConn = new WaitOrTimerCallback (InitConnection);
  53. abortHandler = new EventHandler (Abort);
  54. goAhead = new AutoResetEvent (true);
  55. queue = new Queue (1);
  56. }
  57. public void Connect ()
  58. {
  59. lock (this) {
  60. if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
  61. reused = true;
  62. return;
  63. }
  64. reused = false;
  65. if (socket != null) {
  66. socket.Close();
  67. socket = null;
  68. }
  69. chunkStream = null;
  70. IPHostEntry hostEntry = sPoint.HostEntry;
  71. if (hostEntry == null) {
  72. status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
  73. WebExceptionStatus.NameResolutionFailure;
  74. return;
  75. }
  76. foreach (IPAddress address in hostEntry.AddressList) {
  77. socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  78. try {
  79. socket.Connect (new IPEndPoint(address, sPoint.Address.Port));
  80. status = WebExceptionStatus.Success;
  81. break;
  82. } catch (SocketException) {
  83. socket.Close();
  84. socket = null;
  85. status = WebExceptionStatus.ConnectFailure;
  86. }
  87. }
  88. }
  89. }
  90. bool CreateStream (HttpWebRequest request)
  91. {
  92. //TODO: create stream for https
  93. try {
  94. nstream = new NetworkStream (socket, false);
  95. } catch (Exception) {
  96. status = WebExceptionStatus.ConnectFailure;
  97. return false;
  98. }
  99. return true;
  100. }
  101. void HandleError (WebExceptionStatus st, Exception e)
  102. {
  103. status = st;
  104. lock (this) {
  105. busy = false;
  106. if (st == WebExceptionStatus.RequestCanceled)
  107. Data = new WebConnectionData ();
  108. status = st;
  109. }
  110. if (e == null) { // At least we now where it comes from
  111. try {
  112. throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
  113. } catch (Exception e2) {
  114. e = e2;
  115. }
  116. }
  117. if (Data != null && Data.request != null)
  118. Data.request.SetResponseError (st, e);
  119. Close (true);
  120. }
  121. internal bool WaitForContinue (byte [] headers, int offset, int size)
  122. {
  123. waitingForContinue = sPoint.SendContinue;
  124. if (waitingForContinue && waitForContinue == null)
  125. waitForContinue = new AutoResetEvent (false);
  126. Write (headers, offset, size);
  127. if (!waitingForContinue)
  128. return false;
  129. bool result = waitForContinue.WaitOne (2000, false);
  130. waitingForContinue = false;
  131. if (result) {
  132. sPoint.SendContinue = true;
  133. if (Data.request.ExpectContinue)
  134. Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
  135. } else {
  136. sPoint.SendContinue = false;
  137. }
  138. return result;
  139. }
  140. static void ReadDone (IAsyncResult result)
  141. {
  142. WebConnection cnc = (WebConnection) result.AsyncState;
  143. WebConnectionData data = cnc.Data;
  144. NetworkStream ns = cnc.nstream;
  145. if (ns == null) {
  146. cnc.Close (true);
  147. return;
  148. }
  149. int nread = -1;
  150. try {
  151. nread = ns.EndRead (result);
  152. } catch (Exception e) {
  153. cnc.status = WebExceptionStatus.ReceiveFailure;
  154. cnc.HandleError (cnc.status, e);
  155. return;
  156. }
  157. if (nread == 0) {
  158. cnc.status = WebExceptionStatus.ReceiveFailure;
  159. cnc.HandleError (cnc.status, null);
  160. return;
  161. }
  162. if (nread < 0) {
  163. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
  164. return;
  165. }
  166. //Console.WriteLine (System.Text.Encoding.Default.GetString (cnc.buffer, 0, nread));
  167. int pos = -1;
  168. if (cnc.readState == ReadState.None) {
  169. Exception exc = null;
  170. try {
  171. pos = cnc.GetResponse (cnc.buffer, nread);
  172. if (data.StatusCode == 100) {
  173. cnc.readState = ReadState.None;
  174. InitRead (cnc);
  175. cnc.sPoint.SendContinue = true;
  176. if (cnc.waitingForContinue) {
  177. cnc.waitForContinue.Set ();
  178. } else if (data.request.ExpectContinue) { // We get a 100 after waiting for it.
  179. data.request.DoContinueDelegate (data.StatusCode, data.Headers);
  180. }
  181. return;
  182. }
  183. } catch (Exception e) {
  184. exc = e;
  185. }
  186. if (pos == -1 || exc != null) {
  187. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc);
  188. return;
  189. }
  190. }
  191. if (cnc.readState != ReadState.Content) {
  192. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
  193. return;
  194. }
  195. WebConnectionStream stream = new WebConnectionStream (cnc);
  196. string contentType = data.Headers ["Transfer-Encoding"];
  197. cnc.chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
  198. if (!cnc.chunkedRead) {
  199. stream.ReadBuffer = cnc.buffer;
  200. stream.ReadBufferOffset = pos;
  201. stream.ReadBufferSize = nread;
  202. } else if (cnc.chunkStream == null) {
  203. cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
  204. } else {
  205. cnc.chunkStream.ResetBuffer ();
  206. cnc.chunkStream.Write (cnc.buffer, pos, nread);
  207. }
  208. data.stream = stream;
  209. lock (cnc) {
  210. if (cnc.queue.Count > 0)
  211. stream.ReadAll ();
  212. else
  213. {
  214. cnc.prevStream = stream;
  215. stream.CheckComplete ();
  216. }
  217. }
  218. data.request.SetResponseData (data);
  219. }
  220. static void InitRead (object state)
  221. {
  222. WebConnection cnc = (WebConnection) state;
  223. NetworkStream ns = cnc.nstream;
  224. try {
  225. ns.BeginRead (cnc.buffer, 0, cnc.buffer.Length, readDoneDelegate, cnc);
  226. } catch (Exception e) {
  227. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e);
  228. }
  229. }
  230. int GetResponse (byte [] buffer, int max)
  231. {
  232. int pos = 0;
  233. string line = null;
  234. bool lineok = false;
  235. bool isContinue = false;
  236. do {
  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. if (Data.StatusCode == (int) HttpStatusCode.Continue) {
  284. if (pos >= max)
  285. return pos;
  286. if (Data.request.ExpectContinue)
  287. Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
  288. readState = ReadState.None;
  289. isContinue = true;
  290. }
  291. else {
  292. readState = ReadState.Content;
  293. return pos;
  294. }
  295. }
  296. }
  297. } while (isContinue == true);
  298. return -1;
  299. }
  300. void InitConnection (object state, bool notUsed)
  301. {
  302. HttpWebRequest request = (HttpWebRequest) state;
  303. if (status == WebExceptionStatus.RequestCanceled) {
  304. busy = false;
  305. Data = new WebConnectionData ();
  306. goAhead.Set ();
  307. SendNext ();
  308. return;
  309. }
  310. keepAlive = request.KeepAlive;
  311. Data = new WebConnectionData ();
  312. Data.request = request;
  313. Connect ();
  314. if (status != WebExceptionStatus.Success) {
  315. request.SetWriteStreamError (status);
  316. Close (true);
  317. return;
  318. }
  319. if (!CreateStream (request)) {
  320. request.SetWriteStreamError (status);
  321. Close (true);
  322. return;
  323. }
  324. readState = ReadState.None;
  325. request.SetWriteStream (new WebConnectionStream (this, request));
  326. InitRead (this);
  327. }
  328. internal EventHandler SendRequest (HttpWebRequest request)
  329. {
  330. lock (this) {
  331. if (prevStream != null && socket != null && socket.Connected) {
  332. prevStream.ReadAll ();
  333. prevStream = null;
  334. }
  335. if (!busy) {
  336. busy = true;
  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. if (nbytes == 0 && chunkStream.WantMore) {
  438. nbytes = nstream.Read (wr.Buffer, wr.Offset, wr.Size);
  439. chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
  440. }
  441. return nbytes;
  442. }
  443. return nstream.EndRead (result);
  444. }
  445. internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  446. {
  447. IAsyncResult result = null;
  448. if (nstream == null)
  449. return null;
  450. try {
  451. result = nstream.BeginWrite (buffer, offset, size, cb, state);
  452. } catch (Exception) {
  453. status = WebExceptionStatus.SendFailure;
  454. throw;
  455. }
  456. return result;
  457. }
  458. internal void EndWrite (IAsyncResult result)
  459. {
  460. if (nstream != null)
  461. nstream.EndWrite (result);
  462. }
  463. internal int Read (byte [] buffer, int offset, int size)
  464. {
  465. if (nstream == null)
  466. return 0;
  467. int result = 0;
  468. try {
  469. if (!chunkedRead || chunkStream.WantMore)
  470. result = nstream.Read (buffer, offset, size);
  471. if (chunkedRead)
  472. chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
  473. } catch (Exception e) {
  474. status = WebExceptionStatus.ReceiveFailure;
  475. HandleError (status, e);
  476. }
  477. return result;
  478. }
  479. internal void Write (byte [] buffer, int offset, int size)
  480. {
  481. if (nstream == null)
  482. return;
  483. try {
  484. nstream.Write (buffer, offset, size);
  485. } catch (Exception) {
  486. }
  487. }
  488. internal bool TryReconnect ()
  489. {
  490. lock (this) {
  491. if (!reused) {
  492. HandleError (WebExceptionStatus.SendFailure, null);
  493. return false;
  494. }
  495. Close (false);
  496. reused = false;
  497. Connect ();
  498. if (status != WebExceptionStatus.Success) {
  499. HandleError (WebExceptionStatus.SendFailure, null);
  500. return false;
  501. }
  502. if (!CreateStream (Data.request)) {
  503. HandleError (WebExceptionStatus.SendFailure, null);
  504. return false;
  505. }
  506. }
  507. return true;
  508. }
  509. void Close (bool sendNext)
  510. {
  511. lock (this) {
  512. busy = false;
  513. if (nstream != null) {
  514. try {
  515. nstream.Close ();
  516. } catch {}
  517. nstream = null;
  518. }
  519. if (socket != null) {
  520. try {
  521. socket.Close ();
  522. } catch {}
  523. socket = null;
  524. }
  525. if (sendNext) {
  526. goAhead.Set ();
  527. SendNext ();
  528. }
  529. }
  530. }
  531. void Abort (object sender, EventArgs args)
  532. {
  533. HandleError (WebExceptionStatus.RequestCanceled, null);
  534. }
  535. internal bool Busy {
  536. get { lock (this) return busy; }
  537. }
  538. internal bool Connected {
  539. get {
  540. lock (this) {
  541. return (socket != null && socket.Connected);
  542. }
  543. }
  544. }
  545. ~WebConnection ()
  546. {
  547. Close (false);
  548. }
  549. }
  550. }