Welcome to mirror list, hosted at ThFree Co, Russian Federation.

stackbuildersink.cs « remoting « runtime « system « mscorlib « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 574fdca4ee9c9749e0550371f6b63ae178c390f1 (plain)
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// ==++==
// 
//   Copyright (c) Microsoft Corporation.  All rights reserved.
// 
// ==--==
/*============================================================
**
** File:    StackBuilderSink.cs
**
**
** Purpose: Terminating sink which will build a stack and 
**          make a method call on an object
**
**
===========================================================*/
namespace System.Runtime.Remoting.Messaging {
    using System.Runtime.InteropServices;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Metadata;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Runtime.Versioning;
    using System.Security.Principal;
    /* Assembly Access */
    using System;
    using System.Globalization;
    using System.Threading;

    [Serializable]
    internal class StackBuilderSink : IMessageSink
    {

        //+============================================================
        //
        // Method:     Constructor, public
        //
        // Synopsis:   Store server object
        //
        // History:    06-May-1999  <EMAIL>MattSmit</EMAIL>   Created
        //-============================================================
        public StackBuilderSink(MarshalByRefObject server)
        {
            _server = server;
        }
        public StackBuilderSink(Object server)
        {
            _server = server;
            if (_server==null)
            {
                _bStatic = true;
            }
        }

        [System.Security.SecurityCritical]  // auto-generated
        public virtual IMessage SyncProcessMessage(IMessage msg)
        {
            // Validate message here 
            IMessage errMsg = InternalSink.ValidateMessage(msg);        
            if (errMsg != null)
            {
                return errMsg;
            }

            IMethodCallMessage mcMsg = msg as IMethodCallMessage;            

            IMessage retMessage;
            LogicalCallContext oldCallCtx = null;

            LogicalCallContext lcc = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
            object xADCall = lcc.GetData(CrossAppDomainSink.LCC_DATA_KEY);
            
            bool isCallContextSet = false;
            try
            {
                Object server = _server;

                BCLDebug.Assert((server!=null) == (!_bStatic),
                                "Invalid state in stackbuilder sink?");

                // validate the method base if necessary
                VerifyIsOkToCallMethod(server, mcMsg);
                
                // install call context onto the thread, holding onto
                // the one that is currently on the thread
   
                LogicalCallContext messageCallContext = null;
                if (mcMsg != null)
                {
                    messageCallContext = mcMsg.LogicalCallContext;                    
                }
                else
                {
                    messageCallContext = (LogicalCallContext)msg.Properties["__CallContext"];
                }
                                
                oldCallCtx = CallContext.SetLogicalCallContext(messageCallContext);
                isCallContextSet = true;

                messageCallContext.PropagateIncomingHeadersToCallContext(msg);

                PreserveThreadPrincipalIfNecessary(messageCallContext, oldCallCtx);
                

                // NOTE: target for dispatch will be NULL when the StackBuilderSink
                // is used for async delegates on static methods.

                // *** NOTE ***
                // Although we always pass _server to these calls in the EE,
                // when we execute using Message::Dispatch we are using TP as 
                // the this-ptr ... (what the call site thinks is the this-ptr)
                // when we execute using StackBuilderSink::PrivatePM we use
                // _server as the this-ptr (which could be different if there
                // is interception for strictly MBR types in the same AD).
                // ************
                if (IsOKToStackBlt(mcMsg, server) 
                    && ((Message)mcMsg).Dispatch(server))
                {
                    //retMessage = StackBasedReturnMessage.GetObjectFromPool((Message)mcMsg);
                    retMessage = new StackBasedReturnMessage();
                    ((StackBasedReturnMessage)retMessage).InitFields((Message)mcMsg);

                    // call context could be different then the one from before the call.
                    LogicalCallContext latestCallContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
                    // retrieve outgoing response headers
                    latestCallContext.PropagateOutgoingHeadersToMessage(retMessage);
                    
                    // Install call context back into Message (from the thread)
                    ((StackBasedReturnMessage)retMessage).SetLogicalCallContext(latestCallContext);
                } 
                else
                {
                    MethodBase mb = GetMethodBase(mcMsg); 
                    Object[] outArgs = null;
                    Object ret = null;                      
                    
                    RemotingMethodCachedData methodCache = 
                        InternalRemotingServices.GetReflectionCachedData(mb);

                    Message.DebugOut("StackBuilderSink::Calling PrivateProcessMessage\n");

                    Object[] args = Message.CoerceArgs(mcMsg, methodCache.Parameters);
                
                    ret = PrivateProcessMessage(
                                        mb.MethodHandle,
                                        args,
                                        server,
                                        out outArgs); 
                    CopyNonByrefOutArgsFromOriginalArgs(methodCache, args, ref outArgs);


                    // call context could be different then the one from before the call.
                    LogicalCallContext latestCallContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;

                    if (xADCall != null && ((bool)xADCall) == true && latestCallContext != null)
                    {
                        // Special case Principal since if might not be serializable before returning
                        // ReturnMessage
                        latestCallContext.RemovePrincipalIfNotSerializable();
                    }

                    retMessage = new ReturnMessage( 
                                        ret, 
                                        outArgs, 
                                        (outArgs == null ? 0 : outArgs.Length),
                                        latestCallContext,
                                        mcMsg);

                    // retrieve outgoing response headers
                    latestCallContext.PropagateOutgoingHeadersToMessage(retMessage);
                    // restore the call context on the thread
                    CallContext.SetLogicalCallContext(oldCallCtx);
                }


            } catch (Exception e)
            {
                Message.DebugOut(
                "StackBuilderSink::The server object probably threw an exception " +
                                 e.Message + e.StackTrace + "\n" );
                retMessage = new ReturnMessage(e, mcMsg);
                ((ReturnMessage)retMessage).SetLogicalCallContext(mcMsg.LogicalCallContext);
                        
                if (isCallContextSet)
                    CallContext.SetLogicalCallContext(oldCallCtx);
            }


            return retMessage;
        }


        [System.Security.SecurityCritical]  // auto-generated
        public virtual IMessageCtrl AsyncProcessMessage(
            IMessage msg, IMessageSink replySink) 
        { 
            IMethodCallMessage mcMsg = (IMethodCallMessage)msg;

            IMessageCtrl retCtrl = null;
            IMessage retMessage = null;
            LogicalCallContext oldCallCtx = null;
            bool isCallContextSet = false;
            try{
                try
                {
                    LogicalCallContext callCtx =  (LogicalCallContext)
                        mcMsg.Properties[Message.CallContextKey];
                        
                    Object server = _server;

                    // validate the method base if necessary
                    VerifyIsOkToCallMethod(server, mcMsg);
                    
                    // install call context onto the thread, holding onto
                    // the one that is currently on the thread

                    oldCallCtx = CallContext.SetLogicalCallContext(callCtx);
                    isCallContextSet = true;
                    // retrieve incoming headers
                    callCtx.PropagateIncomingHeadersToCallContext(msg);

                    PreserveThreadPrincipalIfNecessary(callCtx, oldCallCtx);

                    // see if this is a server message that was dispatched asynchronously
                    ServerChannelSinkStack sinkStack = 
                        msg.Properties["__SinkStack"] as ServerChannelSinkStack;
                    if (sinkStack != null)
                        sinkStack.ServerObject = server;
                    
                    BCLDebug.Assert((server!=null)==(!_bStatic),
                                    "Invalid state in stackbuilder sink?");   
                                                
                    MethodBase mb = GetMethodBase(mcMsg);
                    Object[] outArgs = null;
                    Object ret = null;                
                    RemotingMethodCachedData methodCache = 
                        InternalRemotingServices.GetReflectionCachedData(mb);                                
                    Object[] args = Message.CoerceArgs(mcMsg, methodCache.Parameters);

                    ret = PrivateProcessMessage(mb.MethodHandle,
                                                args,
                                                server,
                                                out outArgs);
                    CopyNonByrefOutArgsFromOriginalArgs(methodCache, args, ref outArgs);
                                                           
                    if(replySink != null)
                    {     
                        // call context could be different then the one from before the call.
                        LogicalCallContext latestCallContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
                        
                        if (latestCallContext != null)
                        {
                            // Special case Principal since if might not be serializable before returning
                            // ReturnMessage
                            latestCallContext.RemovePrincipalIfNotSerializable();
                        }
                        
                        retMessage = new ReturnMessage(
                                            ret, 
                                            outArgs, 
                                            (outArgs == null ? 0 : outArgs.Length), 
                                            latestCallContext, 
                                            mcMsg);

                        // retrieve outgoing response headers
                        latestCallContext.PropagateOutgoingHeadersToMessage(retMessage);
        
                    }
                } 
                catch (Exception e)
                {
                    if(replySink != null)
                    {
                        retMessage = new ReturnMessage(e, mcMsg);
                        ((ReturnMessage)retMessage).SetLogicalCallContext(
                                (LogicalCallContext)
                                    mcMsg.Properties[Message.CallContextKey]);

                    }
                }
                finally
                {
                    if (replySink != null)
                    {
                        // Call the reply sink without catching the exceptions
                        // in it. In v2.0 any exceptions in the callback for example
                        // would probably bring down the process
                        replySink.SyncProcessMessage(retMessage);
                    }
                }
            }
            finally {
                // restore the call context on the thread
                if (isCallContextSet)
                    CallContext.SetLogicalCallContext(oldCallCtx);
            }

            return retCtrl; 
        } // AsyncProcessMessage

        public IMessageSink NextSink
        {
            [System.Security.SecurityCritical]  // auto-generated
            get
            {
                // there is no nextSink for the StackBuilderSink
                return null;
            }
        }

        // This check if the call-site on the TP is in our own AD
        // It also handles the special case where the TP is on 
        // a well-known object and we cannot do stack-blting
        [System.Security.SecurityCritical]  // auto-generated
        internal bool IsOKToStackBlt(IMethodMessage mcMsg, Object server)
        {
            bool bOK = false;
            Message msg = mcMsg as Message;
            if(null != msg)
            {
                IInternalMessage iiMsg = (IInternalMessage) msg;
 
                // If there is a frame in the message we can always
                // Blt it (provided it is not a proxy to a well-known
                // object in our own appDomain)!
                // The GetThisPtr == server test allows for people to wrap
                // our proxy with their own interception .. in that case
                // we should not blt the stack.
                if (msg.GetFramePtr() != IntPtr.Zero
                    && msg.GetThisPtr() == server
                    && 
                    (   iiMsg.IdentityObject == null ||
                        (  iiMsg.IdentityObject != null 
                            && iiMsg.IdentityObject == iiMsg.ServerIdentityObject
                        )
                    )
                )
                {
                    bOK = true;
                }
            }

            return bOK;
        }
        
        [System.Security.SecurityCritical]  // auto-generated
        private static MethodBase GetMethodBase(IMethodMessage msg)
        {
            MethodBase mb = msg.MethodBase;
            if(null == mb)      
            {
                BCLDebug.Trace("REMOTE", "Method missing w/name ", msg.MethodName);
                    throw new RemotingException(
                        String.Format(
                            CultureInfo.CurrentCulture, Environment.GetResourceString(
                                "Remoting_Message_MethodMissing"),
                            msg.MethodName,
                            msg.TypeName));
            }
                    
            return mb;
        }

        [System.Security.SecurityCritical]  // auto-generated
        private static void VerifyIsOkToCallMethod(Object server, IMethodMessage msg)
        {
            bool bTypeChecked = false;
            MarshalByRefObject mbr = server as MarshalByRefObject;
            if (mbr != null)
            {
                bool fServer;
                Identity id = MarshalByRefObject.GetIdentity(mbr, out fServer);
                if (id != null)
                {
                    ServerIdentity srvId = id as ServerIdentity;
                    if ((srvId != null) && srvId.MarshaledAsSpecificType)
                    {
                        Type srvType = srvId.ServerType;
                        if (srvType != null)
                        {
                            MethodBase mb = GetMethodBase(msg);
                            RuntimeType declaringType = (RuntimeType)mb.DeclaringType;
                        
                            // make sure that srvType is not more restrictive than method base
                            // (i.e. someone marshaled with a specific type or interface exposed)
                            if ((declaringType != srvType) &&
                                !declaringType.IsAssignableFrom(srvType))
                            {
                                throw new RemotingException(
                                    String.Format(
                                        CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"),
                                        mb.DeclaringType.FullName, srvType.FullName));
                                    
                            }
                            // Set flag so we don't repeat this work below.
                            if (declaringType.IsInterface)
                            {
                                VerifyNotIRemoteDispatch(declaringType);
                            }  
                            bTypeChecked = true;
                        }
                    }
                }

                // We must always verify that the type corresponding to 
                // the method being invoked is compatible with the real server 
                // type.
                if (!bTypeChecked)
                {
                    MethodBase mb = GetMethodBase(msg); 
                    RuntimeType reflectedType = (RuntimeType)mb.ReflectedType;
                    if (!reflectedType.IsInterface)
                    {
                        if (!reflectedType.IsInstanceOfType(mbr))
                        {
                            throw new RemotingException(
                                String.Format(
                                    CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"),
                                    reflectedType.FullName, 
                                    mbr.GetType().FullName));
                        }
                    }
                    // This code prohibits calls made to System.EnterpriseServices.IRemoteDispatch
                    // so that remote call cannot bypass lowFilterLevel logic in the serializers.
                    // This special casing should be removed in the future
                    else
                    {
                        VerifyNotIRemoteDispatch(reflectedType);
                    }
                }
            }            

        } // VerifyIsOkToCallMethod

        // This code prohibits calls made to System.EnterpriseServices.IRemoteDispatch
        // so that remote call cannot bypass lowFilterLevel logic in the serializers.
        // This special casing should be removed in the future
        // Check whether we are calling IRemoteDispatch
        [System.Security.SecurityCritical]  // auto-generated
        private static void VerifyNotIRemoteDispatch(RuntimeType reflectedType)
        {
            if(reflectedType.FullName.Equals(sIRemoteDispatch) && 
               reflectedType.GetRuntimeAssembly().GetSimpleName().Equals(sIRemoteDispatchAssembly))
            {
                throw new RemotingException(
                    Environment.GetResourceString("Remoting_CantInvokeIRemoteDispatch"));
            }
        }

        // copies references of non-byref [In, Out] args from the input args to
        //   the output args array.
        internal void CopyNonByrefOutArgsFromOriginalArgs(RemotingMethodCachedData methodCache,
                                                         Object[] args,
                                                         ref Object[] marshalResponseArgs)
        {            
            int[] map = methodCache.NonRefOutArgMap;
            if (map.Length > 0)
            {
                if (marshalResponseArgs == null)
                    marshalResponseArgs = new Object[methodCache.Parameters.Length];
                
                foreach (int pos in map)
                {
                    marshalResponseArgs[pos] = args[pos];
                }
            }
        }


        // For the incoming call, we sometimes need to preserve the thread principal from
        //   the executing thread, instead of blindly bashing it with the one from the message.
        //   For instance, in cross process calls, the principal will always be null
        //   in the incoming message. However, when we are hosted in ASP.Net, ASP.Net will handle
        //   authentication and set up the thread principal. We should dispatch the call
        //   using the identity that it set up.
        [System.Security.SecurityCritical]  // auto-generated
        internal static void PreserveThreadPrincipalIfNecessary(
            LogicalCallContext messageCallContext, 
            LogicalCallContext threadCallContext)
        {
            BCLDebug.Assert(messageCallContext != null, "message should always have a call context");

            if (threadCallContext != null)
            {
                if (messageCallContext.Principal == null)
                {                
                    IPrincipal currentPrincipal = threadCallContext.Principal;
                    if (currentPrincipal != null)
                    {
                        messageCallContext.Principal = currentPrincipal;
                    }
                }
            }
        } // PreserveThreadPrincipalIfNecessary


        internal Object ServerObject
        {
            get { return _server; }
        }
        
        
        //+============================================================
        //
        // Method:     PrivateProcessMessage, public
        //
        // Synopsis:   does the actual work of building the stack, 
        //             finding the correct code address and calling it.
        //
        // History:    06-May-1999  <EMAIL>MattSmit</EMAIL>   Created
        //-============================================================
        [System.Security.SecurityCritical]  // auto-generated
        [ResourceExposure(ResourceScope.None)]
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern Object _PrivateProcessMessage(
            IntPtr md, Object[] args, Object server,
            out Object[] outArgs);
        [System.Security.SecurityCritical]  // auto-generated
        public Object  PrivateProcessMessage(
            RuntimeMethodHandle md, Object[] args, Object server,
            out Object[] outArgs)
        {
            return _PrivateProcessMessage(md.Value, args, server, out outArgs);
        }

        private Object _server;              // target object
        private static string sIRemoteDispatch = "System.EnterpriseServices.IRemoteDispatch";
        private static string sIRemoteDispatchAssembly = "System.EnterpriseServices";

        bool _bStatic;
     }
}