Files
mono/mcs/class/System/System.Net/WebConnection.cs
T
Gonzalo Paniagua Javier 88b5e403bc 2003-10-08 Gonzalo Paniagua Javier <[email protected]>
* System.Net/WebConnection.cs: the queue is now handled by the
	threadpool. Initialize the connection data in a place where it does not
	depend on the execution order of the requests in threadpool. More error
	handling.

	* System.Net/WebConnectionGroup.cs: use the limits in the config file
	and reuse connections when the limit is reached.

	* System.Net.Configuration/ConnectionManagementHandler.cs: added
	GetMaxConnections to return the max. number of simultaneous connections
	to a given host.

svn path=/trunk/mcs/; revision=18735
2003-10-08 02:45:25 +00:00

599 lines
13 KiB
C#

//
// 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 ();
}
}
}