private void WriteRequestAsyncCB(IAsyncResult r)
        {
            WebAsyncResult webAsyncResult = (WebAsyncResult)r.AsyncState;

            try
            {
                cnc.EndWrite2(request, r);
                webAsyncResult.SetCompleted(synch: false, 0);
                if (!initRead)
                {
                    initRead = true;
                    WebConnection.InitRead(cnc);
                }
            }
            catch (Exception ex)
            {
                Exception ex2 = ex;
                KillBuffer();
                nextReadCalled = true;
                cnc.Close(sendNext: true);
                if (ex2 is SocketException)
                {
                    ex2 = new IOException("Error writing request", ex2);
                }
                webAsyncResult.SetCompleted(synch: false, ex2);
            }
            complete_request_written = true;
            webAsyncResult.DoCallback();
        }
        private void WriteRequestAsyncCB(IAsyncResult r)
        {
            WebAsyncResult webAsyncResult = (WebAsyncResult)r.AsyncState;

            try
            {
                this.cnc.EndWrite2(this.request, r);
                webAsyncResult.SetCompleted(false, 0);
                if (!this.initRead)
                {
                    this.initRead = true;
                    WebConnection.InitRead(this.cnc);
                }
            }
            catch (Exception ex)
            {
                this.KillBuffer();
                this.nextReadCalled = true;
                this.cnc.Close(true);
                if (ex is System.Net.Sockets.SocketException)
                {
                    ex = new IOException("Error writing request", ex);
                }
                webAsyncResult.SetCompleted(false, ex);
            }
            this.complete_request_written = true;
            webAsyncResult.DoCallback();
        }
Example #3
0
        void WriteAsyncCB(IAsyncResult r)
        {
            WebAsyncResult result = (WebAsyncResult)r.AsyncState;

            result.InnerAsyncResult = null;

            try {
                cnc.EndWrite(request, true, r);
                result.SetCompleted(false, 0);
                if (!initRead)
                {
                    initRead = true;
                    WebConnection.InitRead(cnc);
                }
            } catch (Exception e) {
                KillBuffer();
                nextReadCalled = true;
                cnc.Close(true);
                if (e is System.Net.Sockets.SocketException)
                {
                    e = new IOException("Error writing request", e);
                }
                result.SetCompleted(false, e);
            }

            if (allowBuffering && !sendChunked && request.ContentLength > 0 && totalWritten == request.ContentLength)
            {
                complete_request_written = true;
            }

            result.DoCallback();
        }
Example #4
0
		internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
		{
			if (Aborted)
				return;
			lock (locker) {
			string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
			WebAsyncResult r = asyncRead;
			if (r == null)
				r = asyncWrite;

			WebException wexc;
			if (e is WebException) {
				wexc = (WebException) e;
			} else {
				wexc = new WebException (msg, e, status, null); 
			}
			if (r != null) {
				if (!r.IsCompleted) {
					r.SetCompleted (false, wexc);
					r.DoCallback ();
				} else if (r == asyncWrite) {
					saved_exc = wexc;
				}
				haveResponse = true;
				asyncRead = null;
				asyncWrite = null;
			} else {
				haveResponse = true;
				saved_exc = wexc;
			}
			}
		}
Example #5
0
        internal void SetResponseError(WebExceptionStatus status, Exception e, string where)
        {
            if (aborted)
            {
                return;
            }
            string         msg = String.Format("Error getting response stream ({0}): {1}", where, status);
            WebAsyncResult r   = asyncRead;

            if (r == null)
            {
                r = asyncWrite;
            }

            if (r != null)
            {
                WebException wexc;
                if (e is WebException)
                {
                    wexc = (WebException)e;
                }
                else
                {
                    wexc = new WebException(msg, e, status, null);
                }
                r.SetCompleted(false, wexc);
                r.DoCallback();
                asyncRead  = null;
                asyncWrite = null;
            }
        }
Example #6
0
        void SetHeadersCB(IAsyncResult r)
        {
            WebAsyncResult result = (WebAsyncResult)r.AsyncState;

            result.InnerAsyncResult = null;
            try {
                cnc.EndWrite(request, true, r);
                result.SetCompleted(false, 0);
                if (!initRead)
                {
                    initRead = true;
                    WebConnection.InitRead(cnc);
                }
                long cl = request.ContentLength;
                if (!sendChunked && cl == 0)
                {
                    requestWritten = true;
                }
            } catch (WebException e) {
                result.SetCompleted(false, e);
            } catch (Exception e) {
                result.SetCompleted(false, new WebException("Error writing headers", e, WebExceptionStatus.SendFailure));
            }
            result.DoCallback();
        }
Example #7
0
        void WriteRequestAsyncCB(IAsyncResult r)
        {
            WebAsyncResult result = (WebAsyncResult)r.AsyncState;

            try {
                cnc.EndWrite2(request, r);
                result.SetCompleted(false, 0);
                if (!initRead)
                {
                    initRead = true;
                    WebConnection.InitRead(cnc);
                }
            } catch (Exception e) {
                KillBuffer();
                nextReadCalled = true;
                cnc.Close(true);
                if (e is System.Net.Sockets.SocketException)
                {
                    e = new IOException("Error writing request", e);
                }
                result.SetCompleted(false, e);
            }
            complete_request_written = true;
            result.DoCallback();
        }
        void WriteCallbackWrapper(IAsyncResult r)
        {
            WebAsyncResult result = r as WebAsyncResult;

            if (result != null && result.AsyncWriteAll)
            {
                return;
            }

            if (r.AsyncState != null)
            {
                result = (WebAsyncResult)r.AsyncState;
                result.InnerAsyncResult = r;
                result.DoCallback();
            }
            else
            {
                try
                {
                    EndWrite(r);
                }
                catch
                {
                }
            }
        }
Example #9
0
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            bool send = (method == "PUT" || method == "POST");

            if (send)
            {
                if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
                {
                    throw new ProtocolViolationException("Content-Length not set");
                }
            }

            CommonChecks(send);
            Monitor.Enter(this);
            getResponseCalled = true;
            if (asyncRead != null && !haveResponse)
            {
                Monitor.Exit(this);
                throw new InvalidOperationException("Cannot re-call start of asynchronous " +
                                                    "method while a previous call is still in progress.");
            }

            CheckIfForceWrite();
            asyncRead = new WebAsyncResult(this, callback, state);
            WebAsyncResult aread = asyncRead;

            initialMethod = method;
            if (haveResponse)
            {
                if (webResponse != null)
                {
                    Exception saved = saved_exc;
                    Monitor.Exit(this);
                    if (saved == null)
                    {
                        aread.SetCompleted(true, webResponse);
                    }
                    else
                    {
                        aread.SetCompleted(true, saved);
                    }
                    aread.DoCallback();
                    return(aread);
                }
            }

            if (!requestSent)
            {
                requestSent  = true;
                redirects    = 0;
                servicePoint = GetServicePoint();
                abortHandler = servicePoint.SendRequest(this, connectionGroup);
            }

            Monitor.Exit(this);
            return(aread);
        }
Example #10
0
        internal void SetHeadersAsync(byte[] buffer, WebAsyncResult result)
        {
            if (headersSent)
            {
                return;
            }

            headers = buffer;
            long   cl             = request.ContentLength;
            string method         = request.Method;
            bool   no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
                                     method == "TRACE");
            bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
                           method == "COPY" || method == "MOVE" || method == "LOCK" ||
                           method == "UNLOCK");

            if (sendChunked || cl > -1 || no_writestream || webdav)
            {
                headersSent = true;

                try {
                    result.InnerAsyncResult = cnc.BeginWrite(request, headers, 0, headers.Length, new AsyncCallback(SetHeadersCB), result);
                    if (result.InnerAsyncResult == null)
                    {
                        // when does BeginWrite return null? Is the case when the request is aborted?
                        if (!result.IsCompleted)
                        {
                            result.SetCompleted(true, 0);
                        }
                        result.DoCallback();
                    }
                } catch (Exception exc) {
                    result.SetCompleted(true, exc);
                    result.DoCallback();
                }
            }
            else
            {
                result.SetCompleted(true, 0);
                result.DoCallback();
            }
        }
Example #11
0
		public override void Abort ()
		{
			if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
				return;

			if (haveResponse && finished_reading)
				return;

			haveResponse = true;
			if (abortHandler != null) {
				try {
					abortHandler (this, EventArgs.Empty);
				} catch (Exception) {}
				abortHandler = null;
			}

			if (asyncWrite != null) {
				WebAsyncResult r = asyncWrite;
				if (!r.IsCompleted) {
					try {
						WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled); 
						r.SetCompleted (false, wexc);
						r.DoCallback ();
					} catch {}
				}
				asyncWrite = null;
			}			

			if (asyncRead != null) {
				WebAsyncResult r = asyncRead;
				if (!r.IsCompleted) {
					try {
						WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled); 
						r.SetCompleted (false, wexc);
						r.DoCallback ();
					} catch {}
				}
				asyncRead = null;
			}			

			if (writeStream != null) {
				try {
					writeStream.Close ();
					writeStream = null;
				} catch {}
			}

			if (webResponse != null) {
				try {
					webResponse.Close ();
					webResponse = null;
				} catch {}
			}
		}		
Example #12
0
 private void ReadCallbackWrapper(IAsyncResult r)
 {
     if (r.AsyncState != null)
     {
         WebAsyncResult webAsyncResult = (WebAsyncResult)r.AsyncState;
         webAsyncResult.InnerAsyncResult = r;
         webAsyncResult.DoCallback();
     }
     else
     {
         EndRead(r);
     }
 }
Example #13
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            if (aborted)
            {
                throw new WebException("The request was previosly aborted.");
            }

            bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
                          method == "TRACE" || method == "DELETE");

            if (method == null || !send)
            {
                throw new ProtocolViolationException("Cannot send data when method is: " + method);
            }

            CommonChecks(send);

            lock (locker)
            {
                if (asyncWrite != null)
                {
                    throw new InvalidOperationException("Cannot re-call start of asynchronous " +
                                                        "method while a previous call is still in progress.");
                }

                asyncWrite    = new WebAsyncResult(this, callback, state);
                initialMethod = method;
                if (haveRequest)
                {
                    if (writeStream != null)
                    {
                        asyncWrite.SetCompleted(true, writeStream);
                        asyncWrite.DoCallback();
                        return(asyncWrite);
                    }
                }

                gotRequestStream = true;
                WebAsyncResult result = asyncWrite;
                if (!requestSent)
                {
                    requestSent  = true;
                    redirects    = 0;
                    servicePoint = GetServicePoint();
                    abortHandler = servicePoint.SendRequest(this, connectionGroup);
                }
                return(result);
            }
        }
Example #14
0
        public override void Abort()
        {
            haveResponse = true;
            aborted      = true;
            if (asyncWrite != null)
            {
                WebAsyncResult r    = asyncWrite;
                WebException   wexc = new WebException("Aborted.", WebExceptionStatus.RequestCanceled);
                r.SetCompleted(false, wexc);
                r.DoCallback();
                asyncWrite = null;
            }

            if (asyncRead != null)
            {
                WebAsyncResult r    = asyncRead;
                WebException   wexc = new WebException("Aborted.", WebExceptionStatus.RequestCanceled);
                r.SetCompleted(false, wexc);
                r.DoCallback();
                asyncRead = null;
            }

            if (abortHandler != null)
            {
                try {
                    abortHandler(this, EventArgs.Empty);
                } catch (Exception) {}
                abortHandler = null;
            }

            if (writeStream != null)
            {
                try {
                    writeStream.Close();
                    writeStream = null;
                } catch {}
            }

            if (webResponse != null)
            {
                try {
                    webResponse.Close();
                    webResponse = null;
                } catch {}
            }
        }
        internal IAsyncResult BeginRead(HttpWebRequest request, byte[] buffer, int offset, int size, AsyncCallback cb, object state)
        {
            lock (this)
            {
                if (this.Data.request != request)
                {
                    throw new ObjectDisposedException(typeof(System.Net.Sockets.NetworkStream).FullName);
                }
                if (this.nstream == null)
                {
                    return(null);
                }
            }
            IAsyncResult asyncResult = null;

            if (this.chunkedRead)
            {
                if (!this.chunkStream.WantMore)
                {
                    goto IL_9A;
                }
            }
            try
            {
                asyncResult = this.nstream.BeginRead(buffer, offset, size, cb, state);
                cb          = null;
            }
            catch (Exception)
            {
                this.HandleError(WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
                throw;
            }
IL_9A:
            if (this.chunkedRead)
            {
                WebAsyncResult webAsyncResult = new WebAsyncResult(cb, state, buffer, offset, size);
                webAsyncResult.InnerAsyncResult = asyncResult;
                if (asyncResult == null)
                {
                    webAsyncResult.SetCompleted(true, null);
                    webAsyncResult.DoCallback();
                }
                return(webAsyncResult);
            }
            return(asyncResult);
        }
Example #16
0
        internal IAsyncResult BeginRead(HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
        {
            lock (this)
            {
                if (Data.request != request)
                {
                    throw new ObjectDisposedException(typeof(NetworkStream).FullName);
                }
                if (nstream == null)
                {
                    return(null);
                }
            }

            IAsyncResult result = null;

            if (!chunkedRead || chunkStream.WantMore)
            {
                try
                {
                    result = nstream.BeginRead(buffer, offset, size, cb, state);
                    cb     = null;
                }
                catch (Exception)
                {
                    HandleError(WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
                    throw;
                }
            }

            if (chunkedRead)
            {
                WebAsyncResult wr = new WebAsyncResult(cb, state, buffer, offset, size);
                wr.InnerAsyncResult = result;
                if (result == null)
                {
                    // Will be completed from the data in ChunkStream
                    wr.SetCompleted(true, (Exception)null);
                    wr.DoCallback();
                }
                return(wr);
            }

            return(result);
        }
Example #17
0
		public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) 
		{
			if (Aborted)
				throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);

			bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
					method == "TRACE");
			if (method == null || !send)
				throw new ProtocolViolationException ("Cannot send data when method is: " + method);

			if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
				throw new ProtocolViolationException ("Content-Length not set");

			string transferEncoding = TransferEncoding;
			if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
				throw new ProtocolViolationException ("SendChunked should be true.");

			lock (locker)
			{
				if (asyncWrite != null) {
					throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
								"method while a previous call is still in progress.");
				}
	
				asyncWrite = new WebAsyncResult (this, callback, state);
				initialMethod = method;
				if (haveRequest) {
					if (writeStream != null) {
						asyncWrite.SetCompleted (true, writeStream);
						asyncWrite.DoCallback ();
						return asyncWrite;
					}
				}
				
				gotRequestStream = true;
				WebAsyncResult result = asyncWrite;
				if (!requestSent) {
					requestSent = true;
					redirects = 0;
					servicePoint = GetServicePoint ();
					abortHandler = servicePoint.SendRequest (this, connectionGroup);
				}
				return result;
			}
		}
Example #18
0
        private void WriteCallbackWrapper(IAsyncResult r)
        {
            WebAsyncResult webAsyncResult = r as WebAsyncResult;

            if (webAsyncResult == null || !webAsyncResult.AsyncWriteAll)
            {
                if (r.AsyncState != null)
                {
                    webAsyncResult = (WebAsyncResult)r.AsyncState;
                    webAsyncResult.InnerAsyncResult = r;
                    webAsyncResult.DoCallback();
                }
                else
                {
                    EndWrite(r);
                }
            }
        }
        private void WriteCallbackWrapper(IAsyncResult r)
        {
            WebAsyncResult webAsyncResult = r as WebAsyncResult;

            if (webAsyncResult != null && webAsyncResult.AsyncWriteAll)
            {
                return;
            }
            if (r.AsyncState != null)
            {
                webAsyncResult = (WebAsyncResult)r.AsyncState;
                webAsyncResult.InnerAsyncResult = r;
                webAsyncResult.DoCallback();
            }
            else
            {
                this.EndWrite(r);
            }
        }
Example #20
0
        internal void SetWriteStream(WebConnectionStream stream)
        {
            if (aborted)
            {
                return;
            }

            writeStream = stream;
            if (bodyBuffer != null)
            {
                webHeaders.RemoveInternal("Transfer-Encoding");
                contentLength           = bodyBufferLength;
                writeStream.SendChunked = false;
            }

            SendRequestHeaders();

            haveRequest = true;

            if (bodyBuffer != null)
            {
                // The body has been written and buffered. The request "user"
                // won't write it again, so we must do it.
                writeStream.Write(bodyBuffer, 0, bodyBufferLength);
                bodyBuffer = null;
                writeStream.Close();
            }
            else if (method == "PUT" || method == "POST" || method == "OPTIONS")
            {
                if (getResponseCalled && !writeStream.RequestWritten)
                {
                    writeStream.WriteRequest();
                }
            }

            if (asyncWrite != null)
            {
                asyncWrite.SetCompleted(false, stream);
                asyncWrite.DoCallback();
                asyncWrite = null;
            }
        }
Example #21
0
        internal void SetWriteStreamError(WebExceptionStatus status)
        {
            if (aborted)
            {
                return;
            }

            WebAsyncResult r = asyncWrite;

            if (r == null)
            {
                r = asyncRead;
            }

            if (r != null)
            {
                r.SetCompleted(false, new WebException("Error: " + status, status));
                r.DoCallback();
            }
        }
Example #22
0
		internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
		{
			if (Aborted)
				return;

			WebAsyncResult r = asyncWrite;
			if (r == null)
				r = asyncRead;

			if (r != null) {
				string msg;
				WebException wex;
				if (exc == null) {
					msg = "Error: " + status;
					wex = new WebException (msg, status);
				} else {
					msg = String.Format ("Error: {0} ({1})", status, exc.Message);
					wex = new WebException (msg, exc, status);
				}
				r.SetCompleted (false, wex);
				r.DoCallback ();
			}
		}
Example #23
0
		internal void SetWriteStream (WebConnectionStream stream)
		{
			if (Aborted)
				return;
			
			writeStream = stream;
			if (bodyBuffer != null) {
				webHeaders.RemoveInternal ("Transfer-Encoding");
				contentLength = bodyBufferLength;
				writeStream.SendChunked = false;
			}

			SendRequestHeaders (false);

			haveRequest = true;
			
			if (bodyBuffer != null) {
				// The body has been written and buffered. The request "user"
				// won't write it again, so we must do it.
				if (ntlm_auth_state != NtlmAuthState.Challenge) {
					writeStream.Write (bodyBuffer, 0, bodyBufferLength);
					bodyBuffer = null;
					writeStream.Close ();
				}
			} else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
					method != "TRACE") {
				if (getResponseCalled && !writeStream.RequestWritten)
					writeStream.WriteRequest ();
			}

			if (asyncWrite != null) {
				asyncWrite.SetCompleted (false, stream);
				asyncWrite.DoCallback ();
				asyncWrite = null;
			}
		}
Example #24
0
		public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
							AsyncCallback cb, object state)
		{
			if (!isRead)
				throw new NotSupportedException ("this stream does not allow reading");

			if (buffer == null)
				throw new ArgumentNullException ("buffer");

			int length = buffer.Length;
			if (offset < 0 || length < offset)
				throw new ArgumentOutOfRangeException ("offset");
			if (size < 0 || (length - offset) < size)
				throw new ArgumentOutOfRangeException ("size");

			lock (locker) {
				pendingReads++;
				pending.Reset ();
			}

			WebAsyncResult result = new WebAsyncResult (cb, state, buffer, offset, size);
			if (totalRead >= contentLength) {
				result.SetCompleted (true, -1);
				result.DoCallback ();
				return result;
			}
			
			int remaining = readBufferSize - readBufferOffset;
			if (remaining > 0) {
				int copy = (remaining > size) ? size : remaining;
				Buffer.BlockCopy (readBuffer, readBufferOffset, buffer, offset, copy);
				readBufferOffset += copy;
				offset += copy;
				size -= copy;
				totalRead += copy;
				if (size == 0 || totalRead >= contentLength) {
					result.SetCompleted (true, copy);
					result.DoCallback ();
					return result;
				}
				result.NBytes = copy;
			}

			if (cb != null)
				cb = cb_wrapper;

			if (contentLength != Int64.MaxValue && contentLength - totalRead < size)
				size = (int)(contentLength - totalRead);

			if (!read_eof) {
				result.InnerAsyncResult = cnc.BeginRead (request, buffer, offset, size, cb, result);
			} else {
				result.SetCompleted (true, result.NBytes);
				result.DoCallback ();
			}
			return result;
		}
Example #25
0
        public override IAsyncResult BeginWrite(byte [] buffer, int offset, int size,
                                                AsyncCallback cb, object state)
        {
            if (request.Aborted)
            {
                throw new WebException("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
            }

            if (isRead)
            {
                throw new NotSupportedException("this stream does not allow writing");
            }

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            int length = buffer.Length;

            if (offset < 0 || length < offset)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || (length - offset) < size)
            {
                throw new ArgumentOutOfRangeException("size");
            }

            if (sendChunked)
            {
                lock (locker) {
                    pendingWrites++;
                    pending.Reset();
                }
            }

            WebAsyncResult result   = new WebAsyncResult(cb, state);
            AsyncCallback  callback = new AsyncCallback(WriteRequestAsyncCB);

            if (sendChunked)
            {
                requestWritten = true;

                string cSize     = String.Format("{0:X}\r\n", size);
                byte[] head      = Encoding.ASCII.GetBytes(cSize);
                int    chunkSize = 2 + size + head.Length;
                byte[] newBuffer = new byte [chunkSize];
                Buffer.BlockCopy(head, 0, newBuffer, 0, head.Length);
                Buffer.BlockCopy(buffer, offset, newBuffer, head.Length, size);
                Buffer.BlockCopy(crlf, 0, newBuffer, head.Length + size, crlf.Length);

                buffer = newBuffer;
                offset = 0;
                size   = chunkSize;
            }
            else
            {
                CheckWriteOverflow(request.ContentLength, totalWritten, size);

                if (allowBuffering)
                {
                    if (writeBuffer == null)
                    {
                        writeBuffer = new MemoryStream();
                    }
                    writeBuffer.Write(buffer, offset, size);
                    totalWritten += size;

                    if (request.ContentLength <= 0 || totalWritten < request.ContentLength)
                    {
                        result.SetCompleted(true, 0);
                        result.DoCallback();
                        return(result);
                    }

                    result.AsyncWriteAll = true;
                    requestWritten       = true;
                    buffer = writeBuffer.GetBuffer();
                    offset = 0;
                    size   = (int)totalWritten;
                }
            }

            try {
                result.InnerAsyncResult = cnc.BeginWrite(request, buffer, offset, size, callback, result);
                if (result.InnerAsyncResult == null)
                {
                    if (!result.IsCompleted)
                    {
                        result.SetCompleted(true, 0);
                    }
                    result.DoCallback();
                }
            } catch (Exception) {
                if (!IgnoreIOErrors)
                {
                    throw;
                }
                result.SetCompleted(true, 0);
                result.DoCallback();
            }
            totalWritten += size;
            return(result);
        }
Example #26
0
        public override int EndRead(IAsyncResult r)
        {
            WebAsyncResult result = (WebAsyncResult)r;

            if (result.EndCalled)
            {
                int xx = result.NBytes;
                return((xx >= 0) ? xx : 0);
            }

            result.EndCalled = true;

            if (!result.IsCompleted)
            {
                int nbytes = -1;
                try {
                    nbytes = cnc.EndRead(request, result);
                } catch (Exception exc) {
                    lock (locker) {
                        pendingReads--;
                        if (pendingReads == 0)
                        {
                            pending.Set();
                        }
                    }

                    nextReadCalled = true;
                    cnc.Close(true);
                    result.SetCompleted(false, exc);
                    result.DoCallback();
                    throw;
                }

                if (nbytes < 0)
                {
                    nbytes   = 0;
                    read_eof = true;
                }

                totalRead += nbytes;
                result.SetCompleted(false, nbytes + result.NBytes);
                result.DoCallback();
                if (nbytes == 0)
                {
                    contentLength = totalRead;
                }
            }

            lock (locker) {
                pendingReads--;
                if (pendingReads == 0)
                {
                    pending.Set();
                }
            }

            if (totalRead >= contentLength && !nextReadCalled)
            {
                ReadAll();
            }

            int nb = result.NBytes;

            return((nb >= 0) ? nb : 0);
        }
Example #27
0
        public override IAsyncResult BeginRead(byte [] buffer, int offset, int size,
                                               AsyncCallback cb, object state)
        {
            if (!isRead)
            {
                throw new NotSupportedException("this stream does not allow reading");
            }

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            int length = buffer.Length;

            if (offset < 0 || length < offset)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || (length - offset) < size)
            {
                throw new ArgumentOutOfRangeException("size");
            }

            lock (locker) {
                pendingReads++;
                pending.Reset();
            }

            WebAsyncResult result = new WebAsyncResult(cb, state, buffer, offset, size);

            if (totalRead >= contentLength)
            {
                result.SetCompleted(true, -1);
                result.DoCallback();
                return(result);
            }

            int remaining = readBufferSize - readBufferOffset;

            if (remaining > 0)
            {
                int copy = (remaining > size) ? size : remaining;
                Buffer.BlockCopy(readBuffer, readBufferOffset, buffer, offset, copy);
                readBufferOffset += copy;
                offset           += copy;
                size             -= copy;
                totalRead        += copy;
                if (size == 0 || totalRead >= contentLength)
                {
                    result.SetCompleted(true, copy);
                    result.DoCallback();
                    return(result);
                }
                result.NBytes = copy;
            }

            if (cb != null)
            {
                cb = cb_wrapper;
            }

            if (contentLength != Int32.MaxValue && contentLength - totalRead < size)
            {
                size = contentLength - totalRead;
            }

            if (!read_eof)
            {
                result.InnerAsyncResult = cnc.BeginRead(request, buffer, offset, size, cb, result);
            }
            else
            {
                result.SetCompleted(true, result.NBytes);
                result.DoCallback();
            }
            return(result);
        }
Example #28
0
		internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
		{
			Stream s = null;
			lock (this) {
				if (Data.request != request)
					throw new ObjectDisposedException (typeof (NetworkStream).FullName);
				if (nstream == null)
					return null;
				s = nstream;
			}

			IAsyncResult result = null;
			if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
				try {
					result = s.BeginRead (buffer, offset, size, cb, state);
					cb = null;
				} catch (Exception) {
					HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
					throw;
				}
			}

			if (chunkedRead) {
				WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
				wr.InnerAsyncResult = result;
				if (result == null) {
					// Will be completed from the data in ChunkStream
					wr.SetCompleted (true, (Exception) null);
					wr.DoCallback ();
				}
				return wr;
			}

			return result;
		}
Example #29
0
        public override void EndWrite(IAsyncResult r)
        {
            if (r == null)
            {
                throw new ArgumentNullException("r");
            }

            WebAsyncResult result = r as WebAsyncResult;

            if (result == null)
            {
                throw new ArgumentException("Invalid IAsyncResult");
            }

            if (result.EndCalled)
            {
                return;
            }

            result.EndCalled = true;
            if (result.AsyncWriteAll)
            {
                result.WaitUntilComplete();
                if (result.GotException)
                {
                    throw result.Exception;
                }
                return;
            }

            if (allowBuffering && !sendChunked)
            {
                return;
            }

            if (result.GotException)
            {
                throw result.Exception;
            }

            try {
                cnc.EndWrite2(request, result.InnerAsyncResult);
                result.SetCompleted(false, 0);
                result.DoCallback();
            } catch (Exception e) {
                if (IgnoreIOErrors)
                {
                    result.SetCompleted(false, 0);
                }
                else
                {
                    result.SetCompleted(false, e);
                }
                result.DoCallback();
                if (!IgnoreIOErrors)
                {
                    throw;
                }
            } finally {
                if (sendChunked)
                {
                    lock (locker) {
                        pendingWrites--;
                        if (pendingWrites == 0)
                        {
                            pending.Set();
                        }
                    }
                }
            }
        }
Example #30
0
		public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) 
		{
			if (Aborted)
				throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);

			bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
					method == "TRACE");
			if (method == null || !send)
				throw new ProtocolViolationException ("Cannot send data when method is: " + method);

			if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
				throw new ProtocolViolationException ("Content-Length not set");

			string transferEncoding = TransferEncoding;
			if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
				throw new ProtocolViolationException ("SendChunked should be true.");

			lock (locker)
			{
				if (getResponseCalled)
					throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");

				if (asyncWrite != null) {
					throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
								"method while a previous call is still in progress.");
				}
	
				asyncWrite = new WebAsyncResult (this, callback, state);
				initialMethod = method;
				if (haveRequest) {
					if (writeStream != null) {
						asyncWrite.SetCompleted (true, writeStream);
						asyncWrite.DoCallback ();
						return asyncWrite;
					}
				}
				
				gotRequestStream = true;
				WebAsyncResult result = asyncWrite;
				if (!requestSent) {
					requestSent = true;
					redirects = 0;
					servicePoint = GetServicePoint ();
					abortHandler = servicePoint.SendRequest (this, connectionGroup);
				}
				return result;
			}
		}
Example #31
0
		void GetResponseAsyncCB2 (WebAsyncResult aread)
		{
			if (haveResponse) {
				Exception saved = saved_exc;
				if (webResponse != null) {
					Monitor.Exit (locker);
					if (saved == null) {
						aread.SetCompleted (true, webResponse);
					} else {
						aread.SetCompleted (true, saved);
					}
					aread.DoCallback ();
					return;
				} else if (saved != null) {
					Monitor.Exit (locker);
					aread.SetCompleted (true, saved);
					aread.DoCallback ();
					return;
				}
			}

			if (!requestSent) {
				requestSent = true;
				redirects = 0;
				servicePoint = GetServicePoint ();
				abortHandler = servicePoint.SendRequest (this, connectionGroup);
			}

			Monitor.Exit (locker);
		}
Example #32
0
		public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
							AsyncCallback cb, object state)
		{
			if (request.Aborted)
				throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);

			if (isRead)
				throw new NotSupportedException ("this stream does not allow writing");

			if (buffer == null)
				throw new ArgumentNullException ("buffer");

			int length = buffer.Length;
			if (offset < 0 || length < offset)
				throw new ArgumentOutOfRangeException ("offset");
			if (size < 0 || (length - offset) < size)
				throw new ArgumentOutOfRangeException ("size");

			if (sendChunked) {
				lock (locker) {
					pendingWrites++;
					pending.Reset ();
				}
			}

			WebAsyncResult result = new WebAsyncResult (cb, state);
			AsyncCallback callback = new AsyncCallback (WriteAsyncCB);

			if (sendChunked) {
				requestWritten = true;

				string cSize = String.Format ("{0:X}\r\n", size);
				byte[] head = Encoding.ASCII.GetBytes (cSize);
				int chunkSize = 2 + size + head.Length;
				byte[] newBuffer = new byte [chunkSize];
				Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
				Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
				Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);

				if (allowBuffering) {
					if (writeBuffer == null)
						writeBuffer = new MemoryStream ();
					writeBuffer.Write (buffer, offset, size);
					totalWritten += size;
				}

				buffer = newBuffer;
				offset = 0;
				size = chunkSize;
			} else {
				CheckWriteOverflow (request.ContentLength, totalWritten, size);

				if (allowBuffering) {
					if (writeBuffer == null)
						writeBuffer = new MemoryStream ();
					writeBuffer.Write (buffer, offset, size);
					totalWritten += size;

					if (request.ContentLength <= 0 || totalWritten < request.ContentLength) {
						result.SetCompleted (true, 0);
						result.DoCallback ();
						return result;
					}

					result.AsyncWriteAll = true;
					requestWritten = true;
					buffer = writeBuffer.GetBuffer ();
					offset = 0;
					size = (int)totalWritten;
				}
			}

			try {
				result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
				if (result.InnerAsyncResult == null) {
					if (!result.IsCompleted)
						result.SetCompleted (true, 0);
					result.DoCallback ();
				}
			} catch (Exception) {
				if (!IgnoreIOErrors)
					throw;
				result.SetCompleted (true, 0);
				result.DoCallback ();
			}
			totalWritten += size;
			return result;
		}
Example #33
0
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback cb, object state)
        {
            if (request.Aborted)
            {
                throw new WebException("The request was canceled.", null, WebExceptionStatus.RequestCanceled);
            }
            if (isRead)
            {
                throw new NotSupportedException("this stream does not allow writing");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            int num = buffer.Length;

            if (offset < 0 || num < offset)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || num - offset < size)
            {
                throw new ArgumentOutOfRangeException("size");
            }
            if (sendChunked)
            {
                lock (locker)
                {
                    pendingWrites++;
                    pending.Reset();
                }
            }
            WebAsyncResult webAsyncResult = new WebAsyncResult(cb, state);

            if (!sendChunked)
            {
                CheckWriteOverflow(request.ContentLength, totalWritten, size);
            }
            if (allowBuffering && !sendChunked)
            {
                if (writeBuffer == null)
                {
                    writeBuffer = new MemoryStream();
                }
                writeBuffer.Write(buffer, offset, size);
                totalWritten += size;
                if (request.ContentLength > 0 && totalWritten == request.ContentLength)
                {
                    try
                    {
                        webAsyncResult.AsyncWriteAll    = true;
                        webAsyncResult.InnerAsyncResult = WriteRequestAsync(WriteRequestAsyncCB, webAsyncResult);
                        if (webAsyncResult.InnerAsyncResult != null)
                        {
                            return(webAsyncResult);
                        }
                        if (!webAsyncResult.IsCompleted)
                        {
                            webAsyncResult.SetCompleted(synch: true, 0);
                        }
                        webAsyncResult.DoCallback();
                        return(webAsyncResult);
                    }
                    catch (Exception e)
                    {
                        webAsyncResult.SetCompleted(synch: true, e);
                        webAsyncResult.DoCallback();
                        return(webAsyncResult);
                    }
                }
                webAsyncResult.SetCompleted(synch: true, 0);
                webAsyncResult.DoCallback();
                return(webAsyncResult);
            }
            AsyncCallback cb2 = null;

            if (cb != null)
            {
                cb2 = WriteCallbackWrapper;
            }
            if (sendChunked)
            {
                WriteRequest();
                string s     = $"{size:X}\r\n";
                byte[] bytes = Encoding.ASCII.GetBytes(s);
                int    num2  = 2 + size + bytes.Length;
                byte[] array = new byte[num2];
                Buffer.BlockCopy(bytes, 0, array, 0, bytes.Length);
                Buffer.BlockCopy(buffer, offset, array, bytes.Length, size);
                Buffer.BlockCopy(crlf, 0, array, bytes.Length + size, crlf.Length);
                buffer = array;
                offset = 0;
                size   = num2;
            }
            webAsyncResult.InnerAsyncResult = cnc.BeginWrite(request, buffer, offset, size, cb2, webAsyncResult);
            totalWritten += size;
            return(webAsyncResult);
        }
Example #34
0
        public override int EndRead(IAsyncResult r)
        {
            WebAsyncResult webAsyncResult = (WebAsyncResult)r;

            if (webAsyncResult.EndCalled)
            {
                int nBytes = webAsyncResult.NBytes;
                return((nBytes >= 0) ? nBytes : 0);
            }
            webAsyncResult.EndCalled = true;
            if (!webAsyncResult.IsCompleted)
            {
                int num = -1;
                try
                {
                    num = cnc.EndRead(request, webAsyncResult);
                }
                catch (Exception e)
                {
                    lock (locker)
                    {
                        pendingReads--;
                        if (pendingReads == 0)
                        {
                            pending.Set();
                        }
                    }
                    nextReadCalled = true;
                    cnc.Close(sendNext: true);
                    webAsyncResult.SetCompleted(synch: false, e);
                    webAsyncResult.DoCallback();
                    throw;
                    IL_00bb :;
                }
                if (num < 0)
                {
                    num      = 0;
                    read_eof = true;
                }
                totalRead += num;
                webAsyncResult.SetCompleted(synch: false, num + webAsyncResult.NBytes);
                webAsyncResult.DoCallback();
                if (num == 0)
                {
                    contentLength = totalRead;
                }
            }
            lock (locker)
            {
                pendingReads--;
                if (pendingReads == 0)
                {
                    pending.Set();
                }
            }
            if (totalRead >= contentLength && !nextReadCalled)
            {
                ReadAll();
            }
            int nBytes2 = webAsyncResult.NBytes;

            return((nBytes2 >= 0) ? nBytes2 : 0);
        }
Example #35
0
		internal void SetHeadersAsync (byte[] buffer, WebAsyncResult result)
		{
			if (headersSent)
				return;

			headers = buffer;
			long cl = request.ContentLength;
			string method = request.Method;
			bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
						method == "TRACE");
			bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
			               method == "COPY" || method == "MOVE" || method == "LOCK" ||
			               method == "UNLOCK");
			if (sendChunked || cl > -1 || no_writestream || webdav) {

				headersSent = true;

				try {
					result.InnerAsyncResult = cnc.BeginWrite (request, headers, 0, headers.Length, new AsyncCallback(SetHeadersCB), result);
					if (result.InnerAsyncResult == null) {
						// when does BeginWrite return null? Is the case when the request is aborted?
						if (!result.IsCompleted)
							result.SetCompleted (true, 0);
						result.DoCallback ();
					}
				} catch (Exception exc) {
					result.SetCompleted (true, exc);
					result.DoCallback ();
				}
			} else {
				result.SetCompleted (true, 0);
				result.DoCallback ();
			}
		}
Example #36
0
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback cb, object state)
        {
            if (!isRead)
            {
                throw new NotSupportedException("this stream does not allow reading");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            int num = buffer.Length;

            if (offset < 0 || num < offset)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || num - offset < size)
            {
                throw new ArgumentOutOfRangeException("size");
            }
            lock (locker)
            {
                pendingReads++;
                pending.Reset();
            }
            WebAsyncResult webAsyncResult = new WebAsyncResult(cb, state, buffer, offset, size);

            if (totalRead >= contentLength)
            {
                webAsyncResult.SetCompleted(synch: true, -1);
                webAsyncResult.DoCallback();
                return(webAsyncResult);
            }
            int num2 = readBufferSize - readBufferOffset;

            if (num2 > 0)
            {
                int num3 = (num2 <= size) ? num2 : size;
                Buffer.BlockCopy(readBuffer, readBufferOffset, buffer, offset, num3);
                readBufferOffset += num3;
                offset           += num3;
                size             -= num3;
                totalRead        += num3;
                if (size == 0 || totalRead >= contentLength)
                {
                    webAsyncResult.SetCompleted(synch: true, num3);
                    webAsyncResult.DoCallback();
                    return(webAsyncResult);
                }
                webAsyncResult.NBytes = num3;
            }
            if (cb != null)
            {
                cb = ReadCallbackWrapper;
            }
            if (contentLength != int.MaxValue && contentLength - totalRead < size)
            {
                size = contentLength - totalRead;
            }
            if (!read_eof)
            {
                webAsyncResult.InnerAsyncResult = cnc.BeginRead(request, buffer, offset, size, cb, webAsyncResult);
            }
            else
            {
                webAsyncResult.SetCompleted(synch: true, webAsyncResult.NBytes);
                webAsyncResult.DoCallback();
            }
            return(webAsyncResult);
        }