WebConnection.cs 13 KB

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