public WebConnectionStream (WebConnection cnc, WebConnectionData data) { if (data == null) throw new InvalidOperationException ("data was not initialized"); if (data.Headers == null) throw new InvalidOperationException ("data.Headers was not initialized"); if (data.request == null) throw new InvalidOperationException ("data.request was not initialized"); isRead = true; cb_wrapper = new AsyncCallback (ReadCallbackWrapper); pending = new ManualResetEvent (true); this.request = data.request; read_timeout = request.ReadWriteTimeout; write_timeout = read_timeout; this.cnc = cnc; string contentType = data.Headers ["Transfer-Encoding"]; bool chunkedRead = (contentType != null && contentType.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1); string clength = data.Headers ["Content-Length"]; if (!chunkedRead && clength != null && clength != "") { try { contentLength = Int32.Parse (clength); if (contentLength == 0 && !IsNtlmAuth ()) { ReadAll (); } } catch { contentLength = Int64.MaxValue; } } else { contentLength = Int64.MaxValue; } // Negative numbers? if (!Int32.TryParse (clength, out stream_length)) stream_length = -1; }
internal void Close(bool sendNext) { lock (this) { if (nstream != null) { try { nstream.Close(); } catch { } nstream = null; } if (socket != null) { try { socket.Close(); } catch { } socket = null; } busy = false; Data = new WebConnectionData(); if (sendNext) { SendNext(); } } }
private void HandleError(WebExceptionStatus st, Exception e, string where) { status = st; lock (this) { if (st == WebExceptionStatus.RequestCanceled) { Data = new WebConnectionData(); } } if (e == null) { try { throw new Exception(new StackTrace().ToString()); IL_0043 :; } catch (Exception ex) { e = ex; } } HttpWebRequest httpWebRequest = null; if (Data != null && Data.request != null) { httpWebRequest = Data.request; } Close(sendNext: true); if (httpWebRequest != null) { httpWebRequest.FinishedReading = true; httpWebRequest.SetResponseError(st, e, where); } }
void HandleError(WebExceptionStatus st, Exception e, string where) { status = st; lock (this) { if (st == WebExceptionStatus.RequestCanceled) { Data = new WebConnectionData(); } } if (e == null) // At least we now where it comes from { try { #if TARGET_JVM throw new Exception(); #else throw new Exception(new System.Diagnostics.StackTrace().ToString()); #endif } catch (Exception e2) { e = e2; } } HttpWebRequest req = null; if (Data != null && Data.request != null) { req = Data.request; } Close(true); if (req != null) { req.SetResponseError(st, e, where); } }
// Constructors internal HttpWebResponse (Uri uri, string method, WebConnectionData data, CookieContainer container) { this.uri = uri; this.method = method; webHeaders = data.Headers; version = data.Version; statusCode = (HttpStatusCode) data.StatusCode; statusDescription = data.StatusDescription; stream = data.stream; contentLength = -1; try { string cl = webHeaders ["Content-Length"]; if (String.IsNullOrEmpty (cl) || !Int64.TryParse (cl, out contentLength)) contentLength = -1; } catch (Exception) { contentLength = -1; } if (container != null) { this.cookie_container = container; FillCookies (); } string content_encoding = webHeaders ["Content-Encoding"]; if (content_encoding == "gzip" && (data.request.AutomaticDecompression & DecompressionMethods.GZip) != 0) stream = new GZipStream (stream, CompressionMode.Decompress); else if (content_encoding == "deflate" && (data.request.AutomaticDecompression & DecompressionMethods.Deflate) != 0) stream = new DeflateStream (stream, CompressionMode.Decompress); }
internal void Close(bool sendNext) { lock (this) { if (this.nstream != null) { try { this.nstream.Close(); } catch { } this.nstream = null; } if (this.socket != null) { try { this.socket.Close(); } catch { } this.socket = null; } this.busy = false; this.Data = new WebConnectionData(); if (sendNext) { this.SendNext(); } } }
void InitConnection(object state) { HttpWebRequest request = (HttpWebRequest)state; request.WebConnection = this; if (request.ReuseConnection) { request.StoredConnection = this; } if (request.Aborted) { return; } keepAlive = request.KeepAlive; Data = new WebConnectionData(request); retry: Connect(request); if (request.Aborted) { return; } if (status != WebExceptionStatus.Success) { if (!request.Aborted) { request.SetWriteStreamError(status, connect_exception); Close(true); } return; } if (!CreateStream(request)) { if (request.Aborted) { return; } WebExceptionStatus st = status; if (Data.Challenge != null) { goto retry; } Exception cnc_exc = connect_exception; connect_exception = null; request.SetWriteStreamError(st, cnc_exc); Close(true); return; } request.SetWriteStream(new WebConnectionStream(this, request)); }
public WebConnection(WebConnectionGroup group, ServicePoint sPoint) { this.sPoint = sPoint; buffer = new byte [4096]; readState = ReadState.None; Data = new WebConnectionData(); initConn = new WaitCallback(InitConnection); abortHandler = new EventHandler(Abort); queue = group.Queue; }
public WebConnection(IWebConnectionState wcs, ServicePoint sPoint) { this.state = wcs; this.sPoint = sPoint; buffer = new byte [4096]; Data = new WebConnectionData(); queue = wcs.Group.Queue; abortHelper = new AbortHelper(); abortHelper.Connection = this; abortHandler = new EventHandler(abortHelper.Abort); }
public WebConnection(WebConnectionGroup group, ServicePoint sPoint) { this.sPoint = sPoint; buffer = new byte[4096]; readState = ReadState.None; Data = new WebConnectionData(); initConn = InitConnection; queue = group.Queue; abortHelper = new AbortHelper(); abortHelper.Connection = this; abortHandler = abortHelper.Abort; }
public WebConnection(WebConnectionGroup group, ServicePoint sPoint) { this.sPoint = sPoint; this.buffer = new byte[4096]; this.readState = ReadState.None; this.Data = new WebConnectionData(); this.initConn = new WaitCallback(this.InitConnection); this.queue = group.Queue; this.abortHelper = new WebConnection.AbortHelper(); this.abortHelper.Connection = this; this.abortHandler = new EventHandler(this.abortHelper.Abort); }
private void InitConnection(object state) { HttpWebRequest httpWebRequest = (HttpWebRequest)state; httpWebRequest.WebConnection = this; if (httpWebRequest.Aborted) { return; } keepAlive = httpWebRequest.KeepAlive; Data = new WebConnectionData(); Data.request = httpWebRequest; while (true) { Connect(httpWebRequest); if (httpWebRequest.Aborted) { return; } if (status != 0) { if (!httpWebRequest.Aborted) { httpWebRequest.SetWriteStreamError(status, connect_exception); Close(sendNext: true); } return; } if (CreateStream(httpWebRequest)) { break; } if (httpWebRequest.Aborted) { return; } WebExceptionStatus webExceptionStatus = status; if (Data.Challenge != null) { continue; } Exception exc = connect_exception; connect_exception = null; httpWebRequest.SetWriteStreamError(webExceptionStatus, exc); Close(sendNext: true); return; } readState = ReadState.None; httpWebRequest.SetWriteStream(new WebConnectionStream(this, httpWebRequest)); }
// Constructors internal HttpWebResponse(Uri uri, string method, WebConnectionData data, CookieContainer container) { this.uri = uri; this.method = method; webHeaders = data.Headers; version = data.Version; statusCode = (HttpStatusCode)data.StatusCode; statusDescription = data.StatusDescription; stream = data.stream; if (container != null) { this.cookie_container = container; FillCookies(); } }
public WebConnection(WebConnectionGroup group, ServicePoint sPoint) { this.sPoint = sPoint; buffer = new byte [4096]; Data = new WebConnectionData(); initConn = new WaitCallback(state => { try { InitConnection(state); } catch {} }); queue = group.Queue; abortHelper = new AbortHelper(); abortHelper.Connection = this; abortHandler = new EventHandler(abortHelper.Abort); }
public WebConnectionStream(WebConnection cnc, WebConnectionData data) { if (data == null) { throw new InvalidOperationException("data was not initialized"); } if (data.Headers == null) { throw new InvalidOperationException("data.Headers was not initialized"); } if (data.request == null) { throw new InvalidOperationException("data.request was not initialized"); } isRead = true; cb_wrapper = new AsyncCallback(ReadCallbackWrapper); pending = new ManualResetEvent(true); this.request = data.request; read_timeout = request.ReadWriteTimeout; write_timeout = read_timeout; this.cnc = cnc; string contentType = data.Headers ["Transfer-Encoding"]; bool chunkedRead = (contentType != null && contentType.IndexOf("chunked", StringComparison.OrdinalIgnoreCase) != -1); string clength = data.Headers ["Content-Length"]; if (!chunkedRead && clength != null && clength != "") { try { contentLength = Int32.Parse(clength); if (contentLength == 0 && !IsNtlmAuth()) { ReadAll(); } } catch { contentLength = Int32.MaxValue; } } else { contentLength = Int32.MaxValue; } // Negative numbers? if (!Int32.TryParse(clength, out stream_length)) { stream_length = -1; } }
internal void Close(bool sendNext) { lock (this) { if (Data != null && Data.request != null && Data.request.ReuseConnection) { Data.request.ReuseConnection = false; return; } if (nstream != null) { try { nstream.Close(); } catch {} nstream = null; } if (socket != null) { try { socket.Close(); } catch {} socket = null; } if (ntlm_authenticated) { ResetNtlm(); } if (Data != null) { lock (Data) { Data.ReadState = ReadState.Aborted; } } state.SetIdle(); Data = new WebConnectionData(); if (sendNext) { SendNext(); } connect_request = null; connect_ntlm_auth_state = NtlmAuthState.None; } }
// Constructors internal HttpWebResponse(Uri uri, string method, WebConnectionData data, CookieContainer container) { this.uri = uri; this.method = method; webHeaders = data.Headers; version = data.Version; statusCode = (HttpStatusCode)data.StatusCode; statusDescription = data.StatusDescription; stream = data.stream; contentLength = -1; try { string cl = webHeaders ["Content-Length"]; #if NET_2_0 if (String.IsNullOrEmpty(cl) || !Int64.TryParse(cl, out contentLength)) { contentLength = -1; } #else if (cl != null && cl != String.Empty) { contentLength = (long)UInt64.Parse(cl); } #endif } catch (Exception) { contentLength = -1; } if (container != null) { this.cookie_container = container; FillCookies(); } #if NET_2_0 string content_encoding = webHeaders ["Content-Encoding"]; if (content_encoding == "gzip" && (data.request.AutomaticDecompression & DecompressionMethods.GZip) != 0) { stream = new GZipStream(stream, CompressionMode.Decompress); } else if (content_encoding == "deflate" && (data.request.AutomaticDecompression & DecompressionMethods.Deflate) != 0) { stream = new DeflateStream(stream, CompressionMode.Decompress); } #endif }
void CheckSendError (WebConnectionData data) { // Got here, but no one called GetResponse int status = data.StatusCode; if (status < 400 || status == 401 || status == 407) return; if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) { // The request has not been completely sent and we got here! // We should probably just close and cause an error in any case, saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse); if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) { webResponse.ReadAll (); } else { writeStream.IgnoreIOErrors = true; } } }
void CheckSendError(WebConnectionData data) { // Got here, but no one called GetResponse int status = data.StatusCode; if (status < 400 || status == 401 || status == 407) { return; } if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) { // The request has not been completely sent and we got here! // We should probably just close and cause an error in any case, saved_exc = new WebException(data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse); webResponse.ReadAll(); } }
void InitConnection(object state) { HttpWebRequest request = (HttpWebRequest)state; if (status == WebExceptionStatus.RequestCanceled) { lock (this) { busy = false; Data = new WebConnectionData(); SendNext(); } return; } keepAlive = request.KeepAlive; Data = new WebConnectionData(); Data.request = request; retry: Connect(); if (status != WebExceptionStatus.Success) { if (status != WebExceptionStatus.RequestCanceled) { request.SetWriteStreamError(status); Close(true); } return; } if (!CreateStream(request)) { if (Data.Challenge != null) { goto retry; } request.SetWriteStreamError(status); Close(true); return; } readState = ReadState.None; request.SetWriteStream(new WebConnectionStream(this, request)); }
internal HttpWebResponse(System.Uri uri, string method, WebConnectionData data, CookieContainer container) { this.uri = uri; this.method = method; this.webHeaders = data.Headers; this.version = data.Version; this.statusCode = (HttpStatusCode)data.StatusCode; this.statusDescription = data.StatusDescription; this.stream = data.stream; this.contentLength = -1L; try { string text = this.webHeaders["Content-Length"]; if (string.IsNullOrEmpty(text) || !long.TryParse(text, out this.contentLength)) { this.contentLength = -1L; } } catch (Exception) { this.contentLength = -1L; } if (container != null) { this.cookie_container = container; this.FillCookies(); } string a = this.webHeaders["Content-Encoding"]; if (a == "gzip" && (data.request.AutomaticDecompression & DecompressionMethods.GZip) != DecompressionMethods.None) { this.stream = new System.IO.Compression.GZipStream(this.stream, System.IO.Compression.CompressionMode.Decompress); } else if (a == "deflate" && (data.request.AutomaticDecompression & DecompressionMethods.Deflate) != DecompressionMethods.None) { this.stream = new System.IO.Compression.DeflateStream(this.stream, System.IO.Compression.CompressionMode.Decompress); } }
void InitConnection (object state) { HttpWebRequest request = (HttpWebRequest) state; request.WebConnection = this; if (request.Aborted) return; keepAlive = request.KeepAlive; Data = new WebConnectionData (request); retry: Connect (request); if (request.Aborted) return; if (status != WebExceptionStatus.Success) { if (!request.Aborted) { request.SetWriteStreamError (status, connect_exception); Close (true); } return; } if (!CreateStream (request)) { if (request.Aborted) return; WebExceptionStatus st = status; if (Data.Challenge != null) goto retry; Exception cnc_exc = connect_exception; connect_exception = null; request.SetWriteStreamError (st, cnc_exc); Close (true); return; } readState = ReadState.None; request.SetWriteStream (new WebConnectionStream (this, request)); }
void HandleError (WebExceptionStatus st, Exception e, string where) { status = st; lock (this) { if (st == WebExceptionStatus.RequestCanceled) Data = new WebConnectionData (); } if (e == null) { // At least we now where it comes from try { #if TARGET_JVM throw new Exception (); #else throw new Exception (new System.Diagnostics.StackTrace ().ToString ()); #endif } catch (Exception e2) { e = e2; } } HttpWebRequest req = null; if (Data != null && Data.request != null) req = Data.request; Close (true); if (req != null) { req.FinishedReading = true; req.SetResponseError (st, e, where); } }
internal void Close (bool sendNext) { lock (this) { if (nstream != null) { try { nstream.Close (); } catch {} nstream = null; } if (socket != null) { try { socket.Close (); } catch {} socket = null; } if (ntlm_authenticated) ResetNtlm (); busy = false; Data = new WebConnectionData (); if (sendNext) SendNext (); } }
private void Connect(HttpWebRequest request) { object obj = this.socketLock; lock (obj) { if (this.socket != null && this.socket.Connected && this.status == WebExceptionStatus.Success && this.CanReuse() && this.CompleteChunkedRead()) { this.reused = true; } else { this.reused = false; if (this.socket != null) { this.socket.Close(); this.socket = null; } this.chunkStream = null; IPHostEntry hostEntry = this.sPoint.HostEntry; if (hostEntry == null) { this.status = ((!this.sPoint.UsesProxy) ? WebExceptionStatus.NameResolutionFailure : WebExceptionStatus.ProxyNameResolutionFailure); } else { WebConnectionData data = this.Data; foreach (IPAddress ipaddress in hostEntry.AddressList) { this.socket = new System.Net.Sockets.Socket(ipaddress.AddressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); IPEndPoint ipendPoint = new IPEndPoint(ipaddress, this.sPoint.Address.Port); this.socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.Debug, (!this.sPoint.UseNagleAlgorithm) ? 1 : 0); this.socket.NoDelay = !this.sPoint.UseNagleAlgorithm; if (!this.sPoint.CallEndPointDelegate(this.socket, ipendPoint)) { this.socket.Close(); this.socket = null; this.status = WebExceptionStatus.ConnectFailure; } else { try { if (request.Aborted) { break; } this.CheckUnityWebSecurity(request); this.socket.Connect(ipendPoint, false); this.status = WebExceptionStatus.Success; break; } catch (ThreadAbortException) { System.Net.Sockets.Socket socket = this.socket; this.socket = null; if (socket != null) { socket.Close(); } break; } catch (ObjectDisposedException ex) { break; } catch (Exception ex2) { System.Net.Sockets.Socket socket2 = this.socket; this.socket = null; if (socket2 != null) { socket2.Close(); } if (!request.Aborted) { this.status = WebExceptionStatus.ConnectFailure; } this.connect_exception = ex2; } } } } } } }
private void InitConnection(object state) { HttpWebRequest httpWebRequest = (HttpWebRequest)state; httpWebRequest.WebConnection = this; if (httpWebRequest.Aborted) { return; } this.keepAlive = httpWebRequest.KeepAlive; this.Data = new WebConnectionData(); this.Data.request = httpWebRequest; WebExceptionStatus webExceptionStatus; for (;;) { this.Connect(httpWebRequest); if (httpWebRequest.Aborted) { break; } if (this.status != WebExceptionStatus.Success) { goto Block_3; } if (this.CreateStream(httpWebRequest)) { goto IL_D2; } if (httpWebRequest.Aborted) { return; } webExceptionStatus = this.status; if (this.Data.Challenge == null) { goto IL_B4; } } return; Block_3: if (!httpWebRequest.Aborted) { httpWebRequest.SetWriteStreamError(this.status, this.connect_exception); this.Close(true); } return; IL_B4: Exception exc = this.connect_exception; this.connect_exception = null; httpWebRequest.SetWriteStreamError(webExceptionStatus, exc); this.Close(true); return; IL_D2: this.readState = ReadState.None; httpWebRequest.SetWriteStream(new WebConnectionStream(this, httpWebRequest)); }
static int GetResponse (WebConnectionData data, ServicePoint sPoint, byte [] buffer, int max) { int pos = 0; string line = null; bool lineok = false; bool isContinue = false; bool emptyFirstLine = false; do { if (data.ReadState == ReadState.Aborted) return -1; if (data.ReadState == ReadState.None) { lineok = ReadLine (buffer, ref pos, max, ref line); if (!lineok) return 0; if (line == null) { emptyFirstLine = true; continue; } emptyFirstLine = false; data.ReadState = ReadState.Status; string [] parts = line.Split (' '); if (parts.Length < 2) return -1; if (String.Compare (parts [0], "HTTP/1.1", true) == 0) { data.Version = HttpVersion.Version11; sPoint.SetVersion (HttpVersion.Version11); } else { data.Version = HttpVersion.Version10; sPoint.SetVersion (HttpVersion.Version10); } data.StatusCode = (int) UInt32.Parse (parts [1]); if (parts.Length >= 3) data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2); else data.StatusDescription = ""; if (pos >= max) return pos; } emptyFirstLine = false; if (data.ReadState == ReadState.Status) { data.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) return 0; foreach (string s in headers) data.Headers.SetInternal (s); if (data.StatusCode == (int) HttpStatusCode.Continue) { sPoint.SendContinue = true; if (pos >= max) return pos; if (data.request.ExpectContinue) { data.request.DoContinueDelegate (data.StatusCode, data.Headers); // Prevent double calls when getting the // headers in several packets. data.request.ExpectContinue = false; } data.ReadState = ReadState.None; isContinue = true; } else { data.ReadState = ReadState.Content; return pos; } } } while (emptyFirstLine || isContinue); return -1; }
internal void Close (bool sendNext) { lock (this) { if (Data != null && Data.request != null && Data.request.ReuseConnection) { Data.request.ReuseConnection = false; return; } if (nstream != null) { try { nstream.Close (); } catch {} nstream = null; } if (socket != null) { try { socket.Close (); } catch {} socket = null; } if (ntlm_authenticated) ResetNtlm (); if (Data != null) { lock (Data) { Data.ReadState = ReadState.Aborted; } } state.SetIdle (); Data = new WebConnectionData (); if (sendNext) SendNext (); connect_request = null; connect_ntlm_auth_state = NtlmAuthState.None; } }
void InitConnection (object state) { HttpWebRequest request = (HttpWebRequest) state; request.WebConnection = this; if (request.ReuseConnection) request.StoredConnection = this; if (request.Aborted) return; keepAlive = request.KeepAlive; Data = new WebConnectionData (request); retry: Connect (request); if (request.Aborted) return; if (status != WebExceptionStatus.Success) { if (!request.Aborted) { request.SetWriteStreamError (status, connect_exception); Close (true); } return; } if (!CreateStream (request)) { if (request.Aborted) return; WebExceptionStatus st = status; if (Data.Challenge != null) goto retry; Exception cnc_exc = connect_exception; if (cnc_exc == null && (Data.StatusCode == 401 || Data.StatusCode == 407)) { st = WebExceptionStatus.ProtocolError; cnc_exc = new WebException (Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized" , st); } connect_exception = null; request.SetWriteStreamError (st, cnc_exc); Close (true); return; } request.SetWriteStream (new WebConnectionStream (this, request)); }
static void ReadDone(IAsyncResult result) { WebConnection cnc = (WebConnection)result.AsyncState; WebConnectionData data = cnc.Data; Stream ns = cnc.nstream; if (ns == null) { cnc.Close(true); return; } int nread = -1; try { nread = ns.EndRead(result); } catch (ObjectDisposedException) { return; } catch (Exception e) { if (e.InnerException is ObjectDisposedException) { return; } cnc.HandleError(WebExceptionStatus.ReceiveFailure, e, "ReadDone1"); return; } if (nread == 0) { cnc.HandleError(WebExceptionStatus.ReceiveFailure, null, "ReadDone2"); return; } if (nread < 0) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3"); return; } int pos = -1; nread += cnc.position; if (data.ReadState == ReadState.None) { Exception exc = null; try { pos = GetResponse(data, cnc.sPoint, cnc.buffer, nread); } catch (Exception e) { exc = e; } if (exc != null || pos == -1) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4"); return; } } if (data.ReadState == ReadState.Aborted) { cnc.HandleError(WebExceptionStatus.RequestCanceled, null, "ReadDone"); return; } if (data.ReadState != ReadState.Content) { int est = nread * 2; int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est; byte [] newBuffer = new byte [max]; Buffer.BlockCopy(cnc.buffer, 0, newBuffer, 0, nread); cnc.buffer = newBuffer; cnc.position = nread; data.ReadState = ReadState.None; InitRead(cnc); return; } cnc.position = 0; WebConnectionStream stream = new WebConnectionStream(cnc, data); bool expect_content = ExpectContent(data.StatusCode, data.request.Method); string tencoding = null; if (expect_content) { tencoding = data.Headers ["Transfer-Encoding"]; } cnc.chunkedRead = (tencoding != null && tencoding.IndexOf("chunked", StringComparison.OrdinalIgnoreCase) != -1); if (!cnc.chunkedRead) { stream.ReadBuffer = cnc.buffer; stream.ReadBufferOffset = pos; stream.ReadBufferSize = nread; try { stream.CheckResponseInBuffer(); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ReceiveFailure, e, "ReadDone7"); } } else if (cnc.chunkStream == null) { try { cnc.chunkStream = new ChunkStream(cnc.buffer, pos, nread, data.Headers); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5"); return; } } else { cnc.chunkStream.ResetBuffer(); try { cnc.chunkStream.Write(cnc.buffer, pos, nread); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6"); return; } } data.stream = stream; if (!expect_content) { stream.ForceCompletion(); } data.request.SetResponseData(data); }
internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg) { err_msg = null; Stream s = null; lock (this) { if (Data.request != request) throw new ObjectDisposedException (typeof (NetworkStream).FullName); s = nstream; if (s == null) return false; } try { s.Write (buffer, offset, size); // here SSL handshake should have been done if (ssl && !certsAvailable) GetCertificates (s); } catch (Exception e) { err_msg = e.Message; WebExceptionStatus wes = WebExceptionStatus.SendFailure; string msg = "Write: " + err_msg; if (e is WebException) { HandleError (wes, e, msg); return false; } // if SSL is in use then check for TrustFailure if (ssl) { #if SECURITY_DEP && (MONOTOUCH || MONODROID) HttpsClientStream https = (s as HttpsClientStream); if (https.TrustFailure) { #else if ((bool) piTrustFailure.GetValue (s , null)) { #endif wes = WebExceptionStatus.TrustFailure; msg = "Trust failure"; } } HandleError (wes, e, msg); return false; } return true; } internal void Close (bool sendNext) { lock (this) { if (Data != null && Data.request != null && Data.request.ReuseConnection) { Data.request.ReuseConnection = false; return; } if (nstream != null) { try { nstream.Close (); } catch {} nstream = null; } if (socket != null) { try { socket.Close (); } catch {} socket = null; } if (ntlm_authenticated) ResetNtlm (); if (Data != null) { lock (Data) { Data.ReadState = ReadState.Aborted; } } state.SetIdle (); Data = new WebConnectionData (); if (sendNext) SendNext (); connect_request = null; connect_ntlm_auth_state = NtlmAuthState.None; } } void Abort (object sender, EventArgs args) { lock (this) { lock (queue) { HttpWebRequest req = (HttpWebRequest) sender; if (Data.request == req || Data.request == null) { if (!req.FinishedReading) { status = WebExceptionStatus.RequestCanceled; Close (false); if (queue.Count > 0) { Data.request = (HttpWebRequest) queue.Dequeue (); SendRequest (Data.request); } } return; } req.FinishedReading = true; req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted"); if (queue.Count > 0 && queue.Peek () == sender) { queue.Dequeue (); } else if (queue.Count > 0) { object [] old = queue.ToArray (); queue.Clear (); for (int i = old.Length - 1; i >= 0; i--) { if (old [i] != sender) queue.Enqueue (old [i]); } } } } }
internal void SetResponseData(WebConnectionData data) { if (aborted) { if (data.stream != null) { data.stream.Close(); } return; } WebException wexc = null; try { webResponse = new HttpWebResponse(actualUri, method, data, cookieContainer); haveResponse = true; } catch (Exception e) { wexc = new WebException(e.Message, e, WebExceptionStatus.ProtocolError, null); if (data.stream != null) { data.stream.Close(); } } if (wexc == null && (method == "POST" || method == "PUT")) { lock (locker) { CheckSendError(data); if (saved_exc != null) { wexc = (WebException)saved_exc; } } } WebAsyncResult r = asyncRead; if (r != null) { if (wexc != null) { r.SetCompleted(false, wexc); r.DoCallback(); return; } bool redirected; try { redirected = CheckFinalStatus(r); if (!redirected) { r.SetCompleted(false, webResponse); r.DoCallback(); } else { if (webResponse != null) { webResponse.Close(); webResponse = null; } haveResponse = false; webResponse = null; r.Reset(); servicePoint = GetServicePoint(); abortHandler = servicePoint.SendRequest(this, connectionGroup); } } catch (WebException wexc2) { r.SetCompleted(false, wexc2); r.DoCallback(); return; } catch (Exception ex) { wexc = new WebException(ex.Message, ex, WebExceptionStatus.ProtocolError, null); r.SetCompleted(false, wexc); r.DoCallback(); return; } } }
public WebConnection (WebConnectionGroup group, ServicePoint sPoint) { this.sPoint = sPoint; buffer = new byte [4096]; readState = ReadState.None; Data = new WebConnectionData (); initConn = new WaitCallback (state => { try { InitConnection (state); } catch {} }); queue = group.Queue; abortHelper = new AbortHelper (); abortHelper.Connection = this; abortHandler = new EventHandler (abortHelper.Abort); }
public WebConnection (IWebConnectionState wcs, ServicePoint sPoint) { this.state = wcs; this.sPoint = sPoint; buffer = new byte [4096]; Data = new WebConnectionData (); initConn = new WaitCallback (state => { try { InitConnection (state); } catch {} }); queue = wcs.Group.Queue; abortHelper = new AbortHelper (); abortHelper.Connection = this; abortHandler = new EventHandler (abortHelper.Abort); }
void InitConnection(object state) { HttpWebRequest request = (HttpWebRequest)state; request.WebConnection = this; if (request.ReuseConnection) { request.StoredConnection = this; } if (request.Aborted) { return; } keepAlive = request.KeepAlive; Data = new WebConnectionData(request); retry: Connect(request); if (request.Aborted) { return; } if (status != WebExceptionStatus.Success) { if (!request.Aborted) { request.SetWriteStreamError(status, connect_exception); Close(true); } return; } if (!CreateStream(request)) { if (request.Aborted) { return; } WebExceptionStatus st = status; if (Data.Challenge != null) { goto retry; } Exception cnc_exc = connect_exception; if (cnc_exc == null && (Data.StatusCode == 401 || Data.StatusCode == 407)) { st = WebExceptionStatus.ProtocolError; if (Data.Headers == null) { Data.Headers = new WebHeaderCollection(); } var webResponse = new HttpWebResponse(sPoint.Address, "CONNECT", Data, null); cnc_exc = new WebException(Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized", null, st, webResponse); } connect_exception = null; request.SetWriteStreamError(st, cnc_exc); Close(true); return; } request.SetWriteStream(new WebConnectionStream(this, request)); }
internal void SetResponseData (WebConnectionData data) { lock (locker) { if (Aborted) { if (data.stream != null) data.stream.Close (); return; } WebException wexc = null; try { webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer); } catch (Exception e) { wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null); if (data.stream != null) data.stream.Close (); } if (wexc == null && (method == "POST" || method == "PUT")) { CheckSendError (data); if (saved_exc != null) wexc = (WebException) saved_exc; } WebAsyncResult r = asyncRead; bool forced = false; if (r == null && webResponse != null) { // This is a forced completion (302, 204)... forced = true; r = new WebAsyncResult (null, null); r.SetCompleted (false, webResponse); } if (r != null) { if (wexc != null) { haveResponse = true; if (!r.IsCompleted) r.SetCompleted (false, wexc); r.DoCallback (); return; } bool redirected; try { redirected = CheckFinalStatus (r); if (!redirected) { if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null && (int)webResponse.StatusCode < 400) { WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream; if (wce != null) { WebConnection cnc = wce.Connection; cnc.NtlmAuthenticated = true; } } // clear internal buffer so that it does not // hold possible big buffer (bug #397627) if (writeStream != null) writeStream.KillBuffer (); haveResponse = true; r.SetCompleted (false, webResponse); r.DoCallback (); } else { if (webResponse != null) { if (ntlm_auth_state != NtlmAuthState.None) { HandleNtlmAuth (r); return; } webResponse.Close (); } finished_reading = false; haveResponse = false; webResponse = null; r.Reset (); servicePoint = GetServicePoint (); abortHandler = servicePoint.SendRequest (this, connectionGroup); } } catch (WebException wexc2) { if (forced) { saved_exc = wexc2; haveResponse = true; } r.SetCompleted (false, wexc2); r.DoCallback (); return; } catch (Exception ex) { wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null); if (forced) { saved_exc = wexc; haveResponse = true; } r.SetCompleted (false, wexc); r.DoCallback (); return; } } } }
private void Connect(HttpWebRequest request) { lock (socketLock) { if (this.socket != null && this.socket.Connected && status == WebExceptionStatus.Success && CanReuse() && CompleteChunkedRead()) { reused = true; } else { reused = false; if (this.socket != null) { this.socket.Close(); this.socket = null; } chunkStream = null; IPHostEntry hostEntry = sPoint.HostEntry; if (hostEntry == null) { status = ((!sPoint.UsesProxy) ? WebExceptionStatus.NameResolutionFailure : WebExceptionStatus.ProxyNameResolutionFailure); } else { WebConnectionData data = Data; IPAddress[] addressList = hostEntry.AddressList; foreach (IPAddress iPAddress in addressList) { this.socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, sPoint.Address.Port); this.socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Debug, (!sPoint.UseNagleAlgorithm) ? 1 : 0); this.socket.NoDelay = !sPoint.UseNagleAlgorithm; if (!sPoint.CallEndPointDelegate(this.socket, iPEndPoint)) { this.socket.Close(); this.socket = null; status = WebExceptionStatus.ConnectFailure; } else { try { if (!request.Aborted) { CheckUnityWebSecurity(request); this.socket.Connect(iPEndPoint, requireSocketPolicy: false); status = WebExceptionStatus.Success; } return; IL_01a1 :; } catch (ThreadAbortException) { Socket socket = this.socket; this.socket = null; socket?.Close(); return; IL_01c9 :; } catch (ObjectDisposedException) { return; IL_01d5 :; } catch (Exception ex3) { Socket socket2 = this.socket; this.socket = null; socket2?.Close(); if (!request.Aborted) { status = WebExceptionStatus.ConnectFailure; } connect_exception = ex3; } } } } } } }
void Connect(HttpWebRequest request) { lock (socketLock) { if (socket != null && socket.Connected && status == WebExceptionStatus.Success) { // Take the chunked stream to the expected state (State.None) if (CanReuse() && CompleteChunkedRead()) { reused = true; return; } } reused = false; if (socket != null) { socket.Close(); socket = null; } chunkStream = null; IPHostEntry hostEntry = sPoint.HostEntry; if (hostEntry == null) { #if MONOTOUCH if (start_wwan != null) { start_wwan.Invoke(null, new object [1] { sPoint.Address }); hostEntry = sPoint.HostEntry; } if (hostEntry == null) { #endif status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure : WebExceptionStatus.NameResolutionFailure; return; #if MONOTOUCH } #endif } WebConnectionData data = Data; foreach (IPAddress address in hostEntry.AddressList) { socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); IPEndPoint remote = new IPEndPoint(address, sPoint.Address.Port); #if NET_1_1 socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, sPoint.UseNagleAlgorithm ? 0 : 1); #endif #if NET_2_0 socket.NoDelay = !sPoint.UseNagleAlgorithm; if (!sPoint.CallEndPointDelegate(socket, remote)) { socket.Close(); socket = null; status = WebExceptionStatus.ConnectFailure; } else { #endif try { if (request.Aborted) { return; } socket.Connect(remote); status = WebExceptionStatus.Success; break; } catch (ThreadAbortException) { // program exiting... Socket s = socket; socket = null; if (s != null) { s.Close(); } return; } catch (ObjectDisposedException exc) { // socket closed from another thread return; } catch (Exception exc) { Socket s = socket; socket = null; if (s != null) { s.Close(); } if (!request.Aborted) { status = WebExceptionStatus.ConnectFailure; } connect_exception = exc; } #if NET_2_0 } #endif } } }
private static void ReadDone(IAsyncResult result) { WebConnection webConnection = (WebConnection)result.AsyncState; WebConnectionData data = webConnection.Data; Stream stream = webConnection.nstream; if (stream == null) { webConnection.Close(sendNext: true); return; } int num = -1; try { num = stream.EndRead(result); } catch (Exception e) { webConnection.HandleError(WebExceptionStatus.ReceiveFailure, e, "ReadDone1"); return; IL_004c :; } if (num == 0) { webConnection.HandleError(WebExceptionStatus.ReceiveFailure, null, "ReadDone2"); return; } if (num < 0) { webConnection.HandleError(WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3"); return; } int num2 = -1; num += webConnection.position; if (webConnection.readState == ReadState.None) { Exception ex = null; try { num2 = webConnection.GetResponse(webConnection.buffer, num); } catch (Exception ex2) { ex = ex2; } if (ex != null) { webConnection.HandleError(WebExceptionStatus.ServerProtocolViolation, ex, "ReadDone4"); return; } } if (webConnection.readState != ReadState.Content) { int num3 = num * 2; int num4 = (num3 >= webConnection.buffer.Length) ? num3 : webConnection.buffer.Length; byte[] dst = new byte[num4]; Buffer.BlockCopy(webConnection.buffer, 0, dst, 0, num); webConnection.buffer = dst; webConnection.position = num; webConnection.readState = ReadState.None; InitRead(webConnection); return; } webConnection.position = 0; WebConnectionStream webConnectionStream = new WebConnectionStream(webConnection); string text = data.Headers["Transfer-Encoding"]; webConnection.chunkedRead = (text != null && text.ToLower().IndexOf("chunked") != -1); if (!webConnection.chunkedRead) { webConnectionStream.ReadBuffer = webConnection.buffer; webConnectionStream.ReadBufferOffset = num2; webConnectionStream.ReadBufferSize = num; webConnectionStream.CheckResponseInBuffer(); } else if (webConnection.chunkStream == null) { try { webConnection.chunkStream = new ChunkStream(webConnection.buffer, num2, num, data.Headers); } catch (Exception e2) { webConnection.HandleError(WebExceptionStatus.ServerProtocolViolation, e2, "ReadDone5"); return; IL_01ef :; } } else { webConnection.chunkStream.ResetBuffer(); try { webConnection.chunkStream.Write(webConnection.buffer, num2, num); } catch (Exception e3) { webConnection.HandleError(WebExceptionStatus.ServerProtocolViolation, e3, "ReadDone6"); return; IL_0233 :; } } data.stream = webConnectionStream; if (!ExpectContent(data.StatusCode) || data.request.Method == "HEAD") { webConnectionStream.ForceCompletion(); } data.request.SetResponseData(data); }
static void ReadDone(IAsyncResult result) { WebConnection cnc = (WebConnection)result.AsyncState; WebConnectionData data = cnc.Data; Stream ns = cnc.nstream; if (ns == null) { cnc.Close(true); return; } int nread = -1; try { nread = ns.EndRead(result); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ReceiveFailure, e, "ReadDone1"); return; } if (nread == 0) { cnc.HandleError(WebExceptionStatus.ReceiveFailure, null, "ReadDone2"); return; } if (nread < 0) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3"); return; } int pos = -1; nread += cnc.position; if (cnc.readState == ReadState.None) { Exception exc = null; try { pos = cnc.GetResponse(cnc.buffer, nread); } catch (Exception e) { exc = e; } if (exc != null) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4"); return; } } if (cnc.readState != ReadState.Content) { int est = nread * 2; int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est; byte [] newBuffer = new byte [max]; Buffer.BlockCopy(cnc.buffer, 0, newBuffer, 0, nread); cnc.buffer = newBuffer; cnc.position = nread; cnc.readState = ReadState.None; InitRead(cnc); return; } cnc.position = 0; 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; stream.CheckResponseInBuffer(); } else if (cnc.chunkStream == null) { try { cnc.chunkStream = new ChunkStream(cnc.buffer, pos, nread, data.Headers); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5"); return; } } else { cnc.chunkStream.ResetBuffer(); try { cnc.chunkStream.Write(cnc.buffer, pos, nread); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6"); return; } } data.stream = stream; if (!ExpectContent(data.StatusCode) || data.request.Method == "HEAD") { stream.ForceCompletion(); } data.request.SetResponseData(data); }
static int GetResponse(WebConnectionData data, ServicePoint sPoint, byte [] buffer, int max) { int pos = 0; string line = null; bool lineok = false; bool isContinue = false; bool emptyFirstLine = false; do { if (data.ReadState == ReadState.Aborted) { return(-1); } if (data.ReadState == ReadState.None) { lineok = ReadLine(buffer, ref pos, max, ref line); if (!lineok) { return(0); } if (line == null) { emptyFirstLine = true; continue; } emptyFirstLine = false; data.ReadState = ReadState.Status; string [] parts = line.Split(' '); if (parts.Length < 2) { return(-1); } if (String.Compare(parts [0], "HTTP/1.1", true) == 0) { data.Version = HttpVersion.Version11; sPoint.SetVersion(HttpVersion.Version11); } else { data.Version = HttpVersion.Version10; sPoint.SetVersion(HttpVersion.Version10); } data.StatusCode = (int)UInt32.Parse(parts [1]); if (parts.Length >= 3) { data.StatusDescription = String.Join(" ", parts, 2, parts.Length - 2); } else { data.StatusDescription = ""; } if (pos >= max) { return(pos); } } emptyFirstLine = false; if (data.ReadState == ReadState.Status) { data.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) { return(0); } foreach (string s in headers) { data.Headers.SetInternal(s); } if (data.StatusCode == (int)HttpStatusCode.Continue) { sPoint.SendContinue = true; if (pos >= max) { return(pos); } if (data.request.ExpectContinue) { data.request.DoContinueDelegate(data.StatusCode, data.Headers); // Prevent double calls when getting the // headers in several packets. data.request.ExpectContinue = false; } data.ReadState = ReadState.None; isContinue = true; } else { data.ReadState = ReadState.Content; return(pos); } } } while (emptyFirstLine || isContinue); return(-1); }