WebConnection.cs 12 KB

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