WebConnection.cs 12 KB

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