WebConnection.cs 13 KB

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