WebConnection.cs 13 KB

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