| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598 |
- //
- // System.Net.WebConnection
- //
- // Authors:
- // Gonzalo Paniagua Javier ([email protected])
- //
- // (C) 2003 Ximian, Inc (http://www.ximian.com)
- //
- using System.Collections;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- namespace System.Net
- {
- enum ReadState
- {
- None,
- Status,
- Headers,
- Content
- }
-
- class WebConnection
- {
- ServicePoint sPoint;
- NetworkStream nstream;
- Socket socket;
- WebExceptionStatus status;
- WebConnectionGroup group;
- bool busy;
- WaitOrTimerCallback initConn;
- bool keepAlive;
- bool aborted;
- byte [] buffer;
- static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
- EventHandler abortHandler;
- ReadState readState;
- internal WebConnectionData Data;
- WebConnectionStream prevStream;
- bool chunkedRead;
- ChunkStream chunkStream;
- AutoResetEvent waitForContinue;
- AutoResetEvent goAhead;
- bool waitingForContinue;
- int queued;
-
- public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
- {
- this.group = group;
- this.sPoint = sPoint;
- buffer = new byte [4096];
- readState = ReadState.None;
- Data = new WebConnectionData ();
- initConn = new WaitOrTimerCallback (InitConnection);
- abortHandler = new EventHandler (Abort);
- goAhead = new AutoResetEvent (true);
- }
- public void Connect ()
- {
- if (socket != null && socket.Connected && status == WebExceptionStatus.Success)
- return;
- lock (this) {
- if (socket != null && socket.Connected && status == WebExceptionStatus.Success)
- return;
- if (socket != null) {
- socket.Close();
- socket = null;
- }
-
- IPHostEntry hostEntry = sPoint.HostEntry;
- if(hostEntry == null) {
- status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
- WebExceptionStatus.NameResolutionFailure;
- socket.Close();
- socket = null;
- } else {
- foreach(IPAddress address in hostEntry.AddressList) {
- socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- try {
- socket.Connect (new IPEndPoint(address, sPoint.Address.Port));
- status = WebExceptionStatus.Success;
- break;
- } catch (SocketException) {
- socket.Close();
- socket = null;
- status = WebExceptionStatus.ConnectFailure;
- }
- }
- }
- chunkStream = null;
- }
- }
- bool CreateStream (HttpWebRequest request)
- {
- //TODO: create stream for https
- try {
- nstream = new NetworkStream (socket, false);
- } catch (Exception) {
- status = WebExceptionStatus.ConnectFailure;
- return false;
- }
- return true;
- }
-
- void HandleError (WebExceptionStatus st, Exception e)
- {
- status = st;
- Close ();
- lock (this) {
- busy = false;
- if (st == WebExceptionStatus.RequestCanceled)
- Data.Init ();
- status = st;
- }
- if (e == null) { // At least we now where it comes from
- try {
- throw new Exception ();
- } catch (Exception e2) {
- e = e2;
- }
- }
- if (Data != null && Data.request != null)
- Data.request.SetResponseError (st, e);
- goAhead.Set ();
- }
-
- internal bool WaitForContinue (byte [] headers, int offset, int size)
- {
- Data.StatusCode = 0;
- waitingForContinue = sPoint.SendContinue;
- if (waitingForContinue && waitForContinue == null)
- waitForContinue = new AutoResetEvent (false);
- Write (headers, offset, size);
- if (!waitingForContinue)
- return false;
- bool result = waitForContinue.WaitOne (2000, false);
- waitingForContinue = false;
- if (result) {
- sPoint.SendContinue = true;
- if (Data.request.ExpectContinue)
- Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
- } else {
- sPoint.SendContinue = false;
- }
- return result;
- }
-
- static void ReadDone (IAsyncResult result)
- {
- WebConnection cnc = (WebConnection) result.AsyncState;
- WebConnectionData data = cnc.Data;
- NetworkStream ns = cnc.nstream;
- if (ns == null) {
- cnc.busy = false;
- cnc.goAhead.Set ();
- return;
- }
- int nread = -1;
- try {
- nread = ns.EndRead (result);
- } catch (Exception e) {
- cnc.status = WebExceptionStatus.ReceiveFailure;
- cnc.HandleError (cnc.status, e);
- return;
- }
- if (nread == 0) {
- cnc.status = WebExceptionStatus.ReceiveFailure;
- cnc.HandleError (cnc.status, null);
- return;
- }
- if (nread < 0) {
- cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
- return;
- }
- //Console.WriteLine (System.Text.Encoding.Default.GetString (cnc.buffer, 0, nread));
- int pos = -1;
- if (cnc.readState == ReadState.None) {
- Exception exc = null;
- try {
- pos = cnc.GetResponse (cnc.buffer, nread);
- if (data.StatusCode == 100) {
- cnc.readState = ReadState.None;
- InitRead (cnc);
- cnc.sPoint.SendContinue = true;
- if (cnc.waitingForContinue) {
- cnc.waitForContinue.Set ();
- } else if (data.request.ExpectContinue) { // We get a 100 after waiting for it.
- data.request.DoContinueDelegate (data.StatusCode, data.Headers);
- }
- return;
- }
- } catch (Exception e) {
- exc = e;
- }
- if (pos == -1 || exc != null) {
- cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc);
- return;
- }
- }
- if (cnc.readState != ReadState.Content) {
- cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null);
- return;
- }
- WebConnectionStream stream = new WebConnectionStream (cnc);
- string contentType = data.Headers ["Transfer-Encoding"];
- cnc.chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
- if (!cnc.chunkedRead) {
- stream.ReadBuffer = cnc.buffer;
- stream.ReadBufferOffset = pos;
- stream.ReadBufferSize = nread;
- } else if (cnc.chunkStream == null) {
- cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
- } else {
- cnc.chunkStream.ResetBuffer ();
- cnc.chunkStream.Write (cnc.buffer, pos, nread);
- }
- int more = Interlocked.Decrement (ref cnc.queued);
- if (more > 0)
- stream.ReadAll ();
- data.stream = stream;
- stream.CheckComplete ();
- data.request.SetResponseData (data);
- lock (cnc) {
- cnc.prevStream = stream;
- }
- }
-
- static void InitRead (object state)
- {
- WebConnection cnc = (WebConnection) state;
- NetworkStream ns = cnc.nstream;
-
- try {
- ns.BeginRead (cnc.buffer, 0, cnc.buffer.Length, readDoneDelegate, cnc);
- } catch (Exception e) {
- cnc.HandleError (WebExceptionStatus.ReceiveFailure, e);
- }
- }
-
- int GetResponse (byte [] buffer, int max)
- {
- int pos = 0;
- string line = null;
- bool lineok = false;
-
- if (readState == ReadState.None) {
- lineok = ReadLine (buffer, ref pos, max, ref line);
- if (!lineok)
- return -1;
- readState = ReadState.Status;
- string [] parts = line.Split (' ');
- if (parts.Length < 3)
- return -1;
- if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
- Data.Version = HttpVersion.Version11;
- } else {
- Data.Version = HttpVersion.Version10;
- }
- Data.StatusCode = (int) UInt32.Parse (parts [1]);
- Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
- if (pos >= max)
- return pos;
- }
- if (readState == ReadState.Status) {
- readState = ReadState.Headers;
- Data.Headers = new WebHeaderCollection ();
- ArrayList headers = new ArrayList ();
- bool finished = false;
- while (!finished) {
- if (ReadLine (buffer, ref pos, max, ref line) == false)
- break;
-
- if (line == null) {
- // Empty line: end of headers
- finished = true;
- continue;
- }
-
- if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
- int count = headers.Count - 1;
- if (count < 0)
- break;
- string prev = (string) headers [count] + line;
- headers [count] = prev;
- } else {
- headers.Add (line);
- }
- }
- if (!finished) {
- // handle the error...
- } else {
- foreach (string s in headers)
- Data.Headers.Add (s);
- readState = ReadState.Content;
- return pos;
- }
- }
- return -1;
- }
-
- void InitConnection (object state, bool notUsed)
- {
- HttpWebRequest request = (HttpWebRequest) state;
- // Just in case 2 requests are released
- bool relaunch = false;
- lock (this) {
- relaunch = busy;
- busy = true;
- }
- if (relaunch) {
- SendRequest (request);
- return;
- }
- //
- if (status == WebExceptionStatus.RequestCanceled) {
- busy = false;
- Data.Init ();
- goAhead.Set ();
- aborted = false;
- return;
- }
- keepAlive = request.KeepAlive;
- Data.Init ();
- Data.request = request;
- Connect ();
- if (status != WebExceptionStatus.Success) {
- busy = false;
- request.SetWriteStreamError (status);
- Close ();
- goAhead.Set ();
- return;
- }
-
- if (!CreateStream (request)) {
- busy = false;
- request.SetWriteStreamError (status);
- Close ();
- goAhead.Set ();
- return;
- }
- readState = ReadState.None;
- request.SetWriteStream (new WebConnectionStream (this, request));
- InitRead (this);
- }
-
- internal EventHandler SendRequest (HttpWebRequest request)
- {
- lock (this) {
- Interlocked.Increment (ref queued);
- if (prevStream != null && socket != null && socket.Connected) {
- prevStream.ReadAll ();
- prevStream = null;
- }
- ThreadPool.RegisterWaitForSingleObject (goAhead, initConn, request, -1, true);
- }
- return abortHandler;
- }
-
- internal void NextRead ()
- {
- lock (this) {
- busy = false;
- string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
- string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
- bool keepAlive = this.keepAlive;
- if (cncHeader != null) {
- cncHeader = cncHeader.ToLower ();
- keepAlive = (keepAlive && cncHeader.IndexOf ("keep-alive") != -1);
- }
- if ((socket != null && !socket.Connected) ||
- (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
- Close ();
- }
- goAhead.Set ();
- }
- }
-
- static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
- {
- bool foundCR = false;
- StringBuilder text = new StringBuilder ();
- int c = 0;
- while (start < max) {
- c = (int) buffer [start++];
- if (c == '\n') { // newline
- if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
- text.Length--;
- foundCR = false;
- break;
- } else if (foundCR) {
- text.Length--;
- break;
- }
- if (c == '\r')
- foundCR = true;
-
- text.Append ((char) c);
- }
- if (c != '\n' && c != '\r')
- return false;
- if (text.Length == 0) {
- output = null;
- return (c == '\n' || c == '\r');
- }
- if (foundCR)
- text.Length--;
- output = text.ToString ();
- return true;
- }
- internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
- {
- if (nstream == null)
- return null;
- IAsyncResult result = null;
- if (!chunkedRead || chunkStream.WantMore) {
- try {
- result = nstream.BeginRead (buffer, offset, size, cb, state);
- } catch (Exception) {
- status = WebExceptionStatus.ReceiveFailure;
- throw;
- }
- }
- if (chunkedRead) {
- WebAsyncResult wr = new WebAsyncResult (null, null, buffer, offset, size);
- wr.InnerAsyncResult = result;
- return wr;
- }
- return result;
- }
-
- internal int EndRead (IAsyncResult result)
- {
- if (nstream == null)
- return 0;
- if (chunkedRead) {
- WebAsyncResult wr = (WebAsyncResult) result;
- int nbytes = 0;
- if (wr.InnerAsyncResult != null)
- nbytes = nstream.EndRead (wr.InnerAsyncResult);
- chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
- return nbytes;
- }
- return nstream.EndRead (result);
- }
- internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
- {
- IAsyncResult result = null;
- if (nstream == null)
- return null;
- try {
- result = nstream.BeginWrite (buffer, offset, size, cb, state);
- } catch (Exception) {
- status = WebExceptionStatus.SendFailure;
- throw;
- }
- return result;
- }
- internal void EndWrite (IAsyncResult result)
- {
- if (nstream != null)
- nstream.EndWrite (result);
- }
- internal int Read (byte [] buffer, int offset, int size)
- {
- if (nstream == null)
- return 0;
- int result = 0;
- try {
- if (!chunkedRead || chunkStream.WantMore)
- result = nstream.Read (buffer, offset, size);
- if (chunkedRead)
- chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
- } catch (Exception e) {
- status = WebExceptionStatus.ReceiveFailure;
- HandleError (status, e);
- }
- return result;
- }
- internal void Write (byte [] buffer, int offset, int size)
- {
- if (nstream == null)
- return;
- try {
- nstream.Write (buffer, offset, size);
- } catch (Exception e) {
- status = WebExceptionStatus.SendFailure;
- HandleError (status, e);
- }
- }
- void Close ()
- {
- lock (this) {
- if (nstream != null) {
- try {
- nstream.Close ();
- } catch {}
- nstream = null;
- }
- if (socket != null) {
- try {
- socket.Close ();
- } catch {}
- socket = null;
- }
- }
- }
- void Abort (object sender, EventArgs args)
- {
- HandleError (WebExceptionStatus.RequestCanceled, null);
- }
- internal bool Busy {
- get { lock (this) return busy; }
- }
-
- ~WebConnection ()
- {
- Close ();
- }
- }
- }
|