WebConnection.cs 14 KB

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