1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
|
//------------------------------------------------------------------------------
// <copyright file="WebServiceHandler.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Services.Protocols {
using System.Diagnostics;
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using System.Collections;
using System.Web;
using System.Web.SessionState;
using System.Web.Services.Interop;
using System.Configuration;
using Microsoft.Win32;
using System.Threading;
using System.Text;
using System.Web.UI;
using System.Web.Util;
using System.Web.UI.WebControls;
using System.ComponentModel; // for CompModSwitches
using System.EnterpriseServices;
using System.Runtime.Remoting.Messaging;
using System.Web.Services.Diagnostics;
internal class WebServiceHandler {
ServerProtocol protocol;
Exception exception;
AsyncCallback asyncCallback;
ManualResetEvent asyncBeginComplete;
int asyncCallbackCalls;
bool wroteException;
object[] parameters = null;
internal WebServiceHandler(ServerProtocol protocol) {
this.protocol = protocol;
}
// Flush the trace file after each request so that the trace output makes it to the disk.
static void TraceFlush() {
Debug.Flush();
}
void PrepareContext() {
this.exception = null;
this.wroteException = false;
this.asyncCallback = null;
this.asyncBeginComplete = new ManualResetEvent(false);
this.asyncCallbackCalls = 0;
if (protocol.IsOneWay)
return;
HttpContext context = protocol.Context;
if (context == null) return; // context is null in non-network case
// we want the default to be no caching on the client
int cacheDuration = protocol.MethodAttribute.CacheDuration;
if (cacheDuration > 0) {
context.Response.Cache.SetCacheability(HttpCacheability.Server);
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(cacheDuration));
context.Response.Cache.SetSlidingExpiration(false);
// with soap 1.2 the action is a param in the content-type
context.Response.Cache.VaryByHeaders["Content-type"] = true;
context.Response.Cache.VaryByHeaders["SOAPAction"] = true;
context.Response.Cache.VaryByParams["*"] = true;
}
else {
context.Response.Cache.SetNoServerCaching();
context.Response.Cache.SetMaxAge(TimeSpan.Zero);
}
context.Response.BufferOutput = protocol.MethodAttribute.BufferResponse;
context.Response.ContentType = null;
}
void WriteException(Exception e) {
if (this.wroteException) return;
if (CompModSwitches.Remote.TraceVerbose) Debug.WriteLine("Server Exception: " + e.ToString());
if (e is TargetInvocationException) {
if (CompModSwitches.Remote.TraceVerbose) Debug.WriteLine("TargetInvocationException caught.");
e = e.InnerException;
}
this.wroteException = protocol.WriteException(e, protocol.Response.OutputStream);
if (!this.wroteException)
throw e;
}
void Invoke() {
PrepareContext();
protocol.CreateServerInstance();
string stringBuffer;
#if !MONO
RemoteDebugger debugger = null;
if (!protocol.IsOneWay && RemoteDebugger.IsServerCallInEnabled(protocol, out stringBuffer)) {
debugger = new RemoteDebugger();
debugger.NotifyServerCallEnter(protocol, stringBuffer);
}
#endif
try {
TraceMethod caller = Tracing.On ? new TraceMethod(this, "Invoke") : null;
TraceMethod userMethod = Tracing.On ? new TraceMethod(protocol.Target, protocol.MethodInfo.Name, this.parameters) : null;
if (Tracing.On) Tracing.Enter(protocol.MethodInfo.ToString(), caller, userMethod);
object[] returnValues = protocol.MethodInfo.Invoke(protocol.Target, this.parameters);
if (Tracing.On) Tracing.Exit(protocol.MethodInfo.ToString(), caller);
WriteReturns(returnValues);
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "Invoke", e);
if (!protocol.IsOneWay) {
WriteException(e);
throw;
}
}
finally {
protocol.DisposeServerInstance();
#if !MONO
if (debugger != null)
debugger.NotifyServerCallExit(protocol.Response);
#endif
}
}
// By keeping this in a separate method we avoid jitting system.enterpriseservices.dll in cases
// where transactions are not used.
void InvokeTransacted() {
Transactions.InvokeTransacted(new TransactedCallback(this.Invoke), protocol.MethodAttribute.TransactionOption);
}
void ThrowInitException() {
HandleOneWayException(new Exception(Res.GetString(Res.WebConfigExtensionError), protocol.OnewayInitException), "ThrowInitException");
}
void HandleOneWayException(Exception e, string method) {
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, string.IsNullOrEmpty(method) ? "HandleOneWayException" : method, e);
// exceptions for one-way calls are dropped because the response is already written
}
protected void CoreProcessRequest() {
try {
bool transacted = protocol.MethodAttribute.TransactionEnabled;
if (protocol.IsOneWay) {
WorkItemCallback callback = null;
TraceMethod callbackMethod = null;
if (protocol.OnewayInitException != null) {
callback = new WorkItemCallback(this.ThrowInitException);
callbackMethod = Tracing.On ? new TraceMethod(this, "ThrowInitException") : null;
}
else {
parameters = protocol.ReadParameters();
callback = transacted ? new WorkItemCallback(this.OneWayInvokeTransacted) : new WorkItemCallback(this.OneWayInvoke);
callbackMethod = Tracing.On ? transacted ? new TraceMethod(this, "OneWayInvokeTransacted") : new TraceMethod(this, "OneWayInvoke") : null;
}
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemIn, callbackMethod);
WorkItem.Post(callback);
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemOut, callbackMethod);
protocol.WriteOneWayResponse();
}
else if (transacted) {
parameters = protocol.ReadParameters();
InvokeTransacted();
}
else {
parameters = protocol.ReadParameters();
Invoke();
}
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "CoreProcessRequest", e);
if (!protocol.IsOneWay)
WriteException(e);
}
TraceFlush();
}
private HttpContext SwitchContext(HttpContext context) {
PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();
HttpContext oldContext = HttpContext.Current;
HttpContext.Current = context;
return oldContext;
}
private void OneWayInvoke() {
HttpContext oldContext = null;
if (protocol.Context != null)
oldContext = SwitchContext(protocol.Context);
try {
Invoke();
}
catch (Exception e) {
HandleOneWayException(e, "OneWayInvoke");
}
finally {
if (oldContext != null)
SwitchContext(oldContext);
}
}
private void OneWayInvokeTransacted() {
HttpContext oldContext = null;
if (protocol.Context != null)
oldContext = SwitchContext(protocol.Context);
try {
InvokeTransacted();
}
catch (Exception e) {
HandleOneWayException(e, "OneWayInvokeTransacted");
}
finally {
if (oldContext != null)
SwitchContext(oldContext);
}
}
private void Callback(IAsyncResult result) {
if (!result.CompletedSynchronously)
this.asyncBeginComplete.WaitOne();
DoCallback(result);
}
private void DoCallback(IAsyncResult result) {
if (this.asyncCallback != null) {
if (System.Threading.Interlocked.Increment(ref this.asyncCallbackCalls) == 1) {
this.asyncCallback(result);
}
}
}
protected IAsyncResult BeginCoreProcessRequest(AsyncCallback callback, object asyncState) {
IAsyncResult asyncResult;
if (protocol.MethodAttribute.TransactionEnabled)
throw new InvalidOperationException(Res.GetString(Res.WebAsyncTransaction));
parameters = protocol.ReadParameters();
if (protocol.IsOneWay) {
TraceMethod callbackMethod = Tracing.On ? new TraceMethod(this, "OneWayAsyncInvoke") : null;
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemIn, callbackMethod);
WorkItem.Post(new WorkItemCallback(this.OneWayAsyncInvoke));
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemOut, callbackMethod);
asyncResult = new CompletedAsyncResult(asyncState, true);
if (callback != null)
callback(asyncResult);
}
else
asyncResult = BeginInvoke(callback, asyncState);
return asyncResult;
}
private void OneWayAsyncInvoke() {
if (protocol.OnewayInitException != null)
HandleOneWayException(new Exception(Res.GetString(Res.WebConfigExtensionError), protocol.OnewayInitException), "OneWayAsyncInvoke");
else {
HttpContext oldContext = null;
if (protocol.Context != null)
oldContext = SwitchContext(protocol.Context);
try {
BeginInvoke(new AsyncCallback(this.OneWayCallback), null);
}
catch (Exception e) {
HandleOneWayException(e, "OneWayAsyncInvoke");
}
finally {
if (oldContext != null)
SwitchContext(oldContext);
}
}
}
private IAsyncResult BeginInvoke(AsyncCallback callback, object asyncState) {
IAsyncResult asyncResult;
try {
PrepareContext();
protocol.CreateServerInstance();
this.asyncCallback = callback;
TraceMethod caller = Tracing.On ? new TraceMethod(this, "BeginInvoke") : null;
TraceMethod userMethod = Tracing.On ? new TraceMethod(protocol.Target, protocol.MethodInfo.Name, this.parameters) : null;
if (Tracing.On) Tracing.Enter(protocol.MethodInfo.ToString(), caller, userMethod);
asyncResult = protocol.MethodInfo.BeginInvoke(protocol.Target, this.parameters, new AsyncCallback(this.Callback), asyncState);
if (Tracing.On) Tracing.Enter(protocol.MethodInfo.ToString(), caller);
if (asyncResult == null) throw new InvalidOperationException(Res.GetString(Res.WebNullAsyncResultInBegin));
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "BeginInvoke", e);
// save off the exception and throw it in EndCoreProcessRequest
exception = e;
asyncResult = new CompletedAsyncResult(asyncState, true);
this.asyncCallback = callback;
this.DoCallback(asyncResult);
}
this.asyncBeginComplete.Set();
TraceFlush();
return asyncResult;
}
private void OneWayCallback(IAsyncResult asyncResult) {
EndInvoke(asyncResult);
}
protected void EndCoreProcessRequest(IAsyncResult asyncResult) {
if (asyncResult == null) return;
if (protocol.IsOneWay)
protocol.WriteOneWayResponse();
else
EndInvoke(asyncResult);
}
private void EndInvoke(IAsyncResult asyncResult) {
try {
if (exception != null)
throw (exception);
object[] returnValues = protocol.MethodInfo.EndInvoke(protocol.Target, asyncResult);
WriteReturns(returnValues);
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "EndInvoke", e);
if (!protocol.IsOneWay)
WriteException(e);
}
finally {
protocol.DisposeServerInstance();
}
TraceFlush();
}
void WriteReturns(object[] returnValues) {
if (protocol.IsOneWay) return;
// By default ASP.NET will fully buffer the response. If BufferResponse=false
// then we still want to do partial buffering since each write is a named
// pipe call over to inetinfo.
bool fullyBuffered = protocol.MethodAttribute.BufferResponse;
Stream outputStream = protocol.Response.OutputStream;
if (!fullyBuffered) {
outputStream = new BufferedResponseStream(outputStream, 16 * 1024);
//#if DEBUG
((BufferedResponseStream)outputStream).FlushEnabled = false;
//#endif
}
protocol.WriteReturns(returnValues, outputStream);
// This will flush the buffered stream and the underlying stream. Its important
// that it flushes the Response.OutputStream because we always want BufferResponse=false
// to mean we are writing back a chunked response. This gives a consistent
// behavior to the client, independent of the size of the partial buffering.
if (!fullyBuffered) {
//#if DEBUG
((BufferedResponseStream)outputStream).FlushEnabled = true;
//#endif
outputStream.Flush();
}
}
}
internal class SyncSessionlessHandler : WebServiceHandler, IHttpHandler {
internal SyncSessionlessHandler(ServerProtocol protocol) : base(protocol) { }
public bool IsReusable {
get { return false; }
}
public void ProcessRequest(HttpContext context) {
TraceMethod method = Tracing.On ? new TraceMethod(this, "ProcessRequest") : null;
if (Tracing.On) Tracing.Enter("IHttpHandler.ProcessRequest", method, Tracing.Details(context.Request));
CoreProcessRequest();
if (Tracing.On) Tracing.Exit("IHttpHandler.ProcessRequest", method);
}
}
internal class SyncSessionHandler : SyncSessionlessHandler, IRequiresSessionState {
internal SyncSessionHandler(ServerProtocol protocol) : base(protocol) { }
}
internal class AsyncSessionlessHandler : SyncSessionlessHandler, IHttpAsyncHandler {
internal AsyncSessionlessHandler(ServerProtocol protocol) : base(protocol) { }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback callback, object asyncState) {
TraceMethod method = Tracing.On ? new TraceMethod(this, "BeginProcessRequest") : null;
if (Tracing.On) Tracing.Enter("IHttpAsyncHandler.BeginProcessRequest", method, Tracing.Details(context.Request));
IAsyncResult result = BeginCoreProcessRequest(callback, asyncState);
if (Tracing.On) Tracing.Exit("IHttpAsyncHandler.BeginProcessRequest", method);
return result;
}
public void EndProcessRequest(IAsyncResult asyncResult) {
TraceMethod method = Tracing.On ? new TraceMethod(this, "EndProcessRequest") : null;
if (Tracing.On) Tracing.Enter("IHttpAsyncHandler.EndProcessRequest", method);
EndCoreProcessRequest(asyncResult);
if (Tracing.On) Tracing.Exit("IHttpAsyncHandler.EndProcessRequest", method);
}
}
internal class AsyncSessionHandler : AsyncSessionlessHandler, IRequiresSessionState {
internal AsyncSessionHandler(ServerProtocol protocol) : base(protocol) { }
}
class CompletedAsyncResult : IAsyncResult {
object asyncState;
bool completedSynchronously;
internal CompletedAsyncResult(object asyncState, bool completedSynchronously) {
this.asyncState = asyncState;
this.completedSynchronously = completedSynchronously;
}
public object AsyncState { get { return asyncState; } }
public bool CompletedSynchronously { get { return completedSynchronously; } }
public bool IsCompleted { get { return true; } }
public WaitHandle AsyncWaitHandle { get { return null; } }
}
}
|