WebConnection.cs 12 KB

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