How to call callback in remoting in c# - .net-remoting

I have a C# wrapper over C library.
In C lib I have function which takes callback as input.
In C# I have exposed callback like delegate.
Everything works fine in normal mode but when I try to call same function in remoting mode it gives exception like
Could not load file or assembly.
My scenario for remoting is like
1)SharedLib: I have a c# shared lib which has functions which are wrapper over C functions.
All functions are defined in this lib.
2)Server Console Application: Role of server is to get session from Shredlib and open a port so that client ask server for Session
3)Client Console application: Client listen to port opened by server and get session object from server.It defines a functions having same signature as delegate in sharedlib
On session object client calls method from sharedLib which take callback as input.
Client pass address of method having same signature like delegate to method from sharedLib which expects callback as input.
After this I got exception like "Could not load file or assembly."
If I pass null to parameter which take callback as input then everything works fine in remoting mode also.
So can anybody help in using callback in remoting mode.

Three suggestions:
1) Are the different AppDomains running at the same trust level? The second domain may not have permissions to load assemblies if the trust level is lower.
2) The remote application doesn't have all of the dependencies required available to it in the directories it loads assemblies from.
3) Are both applications running under the same version of .NET? If one is .NET 4.5 and one is .NET 3.5 and there's a .NET 4.0 assembly there, then the second process would not be able to run it.
You could try turning on Fusion assembly binding logging to see if there's a more detailed reason why the load fails.

Related

Prevent out-of-proc server shutdown while it has loaded in-proc server object instances

I have an application which uses an out of process COM server to access a COM object created by an in-proc COM server. This means that the out of process COM server has to load the in process COM DLL to create the final object which it would then return.
For example:
// Create an object which resides in the out of process COM server
container.CoCreateInstance("HelperServerProcess");
// Grab a reference to an object which resides in an in process COM server DLL,
// hosted by the out of process COM server
object = container.GenerateResults();
// Release the object instantiated by the out of process server
container = NULL; // or return, or go out of scope, etc
// This call will fail, because the out of process server has shutdown unloading
// the inproc DLL hosting <object>
object.DoStuff();
However, once the container object is released, the final server process reference (in CoReleaseServerProcess ) is released, and the server shuts down. This results in an E_RPC_SERVER_UNAVAILABLE error when trying to use the result object. At the same time the in-proc DLL hosted in this EXE server still has outstanding objects and therefor returns S_FALSE from CanUnloadNow.
I think adding IExternalConnection to the EXE server 's class factory to manually do reference counting on the remote references will not help, because the objects registered by the DLL in-proc server will use the DLLs class factory and try using IExternalConnection on this factory. Also, if the server spawns interactive child objects in its process space it wouldn't trigger IExternalConnection either way.
It also isn't possible to modify the DLL's reference counting to use CoAddRefServerProcess / CoReleaseServerProcess as the DLL doesn't have access to the container's shutdown code in case it triggers the last release, and third party DLLs can't be changed anyhow.
The only method which I can think of which might work is adding a loop after the server refcount hits zero, which calls CoFreeUnusedLibraries, and then somehow enumerates all loaded COM DLLs and waits until none are loaded and ensures the server refcount is still zero. This would leak processes if a loaded DLL does not implement CanUnloadNow correctly, and involves messing around with low level COM implmentation details which I would like to avoid.
Is there any easier way to ensure that the COM objects instantiated by class factories of in-proc servers keep the process alive, or to enumerate the class factories of DLLs loaded into the current process and query them for the number of references?
Update: Another method which may work, but sounds very much like the sort of things you aren't supposed to do: intercepting every spawned thread in the process, registering a CoInitialize hook via CoRegisterInitializeSpy, and adding server process reference for every thread that currently has COM initialized.
The out-of-proc EXE can delegate the DLL object rather than return it directly. Have GetResults() return an object that the EXE implements, and have that implementation use the DLL internally as needed. This way, the EXE will not be released until the caller releases the EXE's object, thus keeping the EXE's own refcount active. The EXE's object can implement the same interface that the DLL object implements. This way, the caller does not know (or care) that delegation is being used.

Unable to create a com object using proxy stub dll

Using Visual c++ 6.0, I have created an ATL based .EXE server .
(VC6 as I am dealing with legacy code, a .exe server as I need to test operation in an out of process context, currently the .exe server is essentialy a no op)
I have built and registered the corresponding proxy stub DLL.
I have a client app that does
CoCreateInstance of IUnknown which invokes FinalConstruct in server object and succeeds (so server is correctly invoked)
OleRun of returned IUnknown interface succeeds
QueryInterface on IUnknown pointer for my server object fails with error code of 0x8000402 (No such interface supported) for the IMarshall interface
These steps were copied from (comip.h::CreateInstance)
The problem appears to be that the proxystub dll is not being invoked (it doesn't appear in the Modules list in the IDE, nor in loaded modules list in debug window)
The OleCom Object viewer for my class and interface can be seen here https://skydrive.live.com/redir?resid=AE43106917EBD9E1!191&authkey=!AIOWeS5P3o2mlpw
8891..ca4d is the class interface id for my object
A298...420c is the interface ID for my server object (IDispatch based)
TIA for any assistance
It's possible that your issue is that the component that is implementing the IRunnableObject interface isn't registering itself in the Running Object Table. This will mean that the CoCreateInstance itself will succeed, however, when the object it called on, the RPC code will be unable to find it.
This MSDN page indicates:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms694517(v=vs.85).aspx
Notes to Implementers
The object should register in the running object table if it has a
moniker assigned. The object should not hold any strong locks on itself;
instead, it should remain in the unstable, unlocked state. The object
should be locked when the first external connection is made to the object.
I'm a little worried about why you're also using the IMarshall interface. Normally it's not necessary to write custom marshaling code, thus you won't need to use this interface.
As long as you don't reference a custom interface the default marshaller in ole32.dll or oleauto32.dll will be used. That's most likely why you don't see your proxy being loaded.
In the case of most COM interfaces, the proxies and stubs for standard
marshaling are in-process component objects which are loaded from a
systemwide DLL provided by COM in Ole32.dll.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms692621(v=vs.85).aspx

Com client authentication

We have a setup here where every process is signed. We have a process with SYSTEM privilege that exposes COM interfaces. We do not want processes other than the ones signed by us to use the COM interfaces. Is there any way to accomplish this? We are also exploring other Windows IPC mechanisms that could allow this. Feel free to suggest other IPC Mechanisms that makes this possible.
Currently we are sending the pid, along with the request but that can be easily spoofed. Any suggestions?
Register a custom proxy/stub or inproc handler and have the proxy or handler incorporate code which checks the signature on the binary.
Make all access go via an inproc COM object which performs the validation and undergoes a challenge/response process with the server. Of course that can be spoofed too if they are handy with a debugger.
Just give up on it. Even a signed process can be spoofed - use CreateProcess with the suspended flag, inject a DLL, and overwrite the entrypoint with a JMP into the DLL. First call is a Sleep(1000) so allow it to run for 500ms, then replace your jump with the original code. Now you are running code in the DLL but the EXE hasn't been modified.
That's even without using the debugging APIs. Heck, they could patch your service to remove the check!

CreateMutex and ActiveX

I'm developing an Internet Explorer ActiveX plugin using Qt, and trying to make the installer ensure the plugin is not running before continuing. A standard approach to this is to create a named mutex in the application and try to open it in the installer.
This works fine when built as a standalone .exe, but when the plugin DLL is loaded by either idc.exe (to register the server or handle the type library) or IE itself (after adding a test against argv[0] to skip CreateMutex for the idc runs), the CreateMutex call crashes.
Here's how I'm calling it:
CreateMutex((LPSECURITY_ATTRIBUTES)MUTEX_ALL_ACCESS, FALSE, "mutex_name_here");
Is there a reason this should fail when run within the context of an ActiveX server, but work correctly when running standalone? Is there something else I'm missing here?
The first parameter to CreateMutex() is a pointer to a SECURITY_ATTRIBUTES structure (which contains a pointer to a security descriptor); it's not a set of requested access rights bits, which is what you're passing in. I'm not sure why that would work any better in a standalone application.
You probably want to pass in NULL for the first parameters so the mutex gets created with a default security descriptor.
The Desired Access bits would get passed to OpenMutex().

Does COM activation of LocalServer32 EXE from the same user account share an existing process or not?

I have a COM server LocalServer32 EXE started when a client application calls c_com_ptr::CreateInstance (using ATL wrappers.)
On Windows 7, when a second client application running under the same user account also calls c_com_ptr::CreateInstance, a second copy of the EXE is launched running under the same user account. I was under the impression, from a past life, that the second client would share the first EXE.
Is the LocalServer32 process shared, or not? When, or when not? Googling for an answer gives me a huge noise to signal ratio and I can't find the answer.
My CLSID registry key has the LocalServer32 value giving the EXE path, ProgID, Programmable (empty string), TypeLib (GUID), and a VersionIndependentProgId. I have an AppID key.
I do not want to run the EXE as a service, and I don't mind that the process is not shared. I just want to know the rules so I know what to expect (on Windows Server 2003 onwards.)
EDIT: Following Chris' answer below, I examined the CoRegisterClassObject call in my server. I'm using ATL, and I overrode MyServer::RegisterClassObjects to hook into the calling chain to CAtlExeModuleT::RegisterClassObjects and see that ATL is using CLSCTX_LOCAL_SERVER and REGCLS_MULTIPLEUSE.
Changing this to CLSCTX_LOCAL_SERVER and REGCLS_SINGLEUSE causes more processes to be started, depending on the number of COM objects created by the client, as expected.
Still, going back to REGCLS_MULTIPLEUSE, I get one COM server process per COM client process, each server process containing all of the COM objects for its client, as expected, except that if two COM clients are running under the same user account, they each get their own server which is not how I understood REGCLS_MULTIPLEUSE.
Could the difference be that the clients themselves are actually Windows services? (They are.) When a Windows service process running as a user account creates a COM object under REGCLS_MULTIPLEUSE, is this treated differently, causing the observed behavior? Why am I getting more than one process? (And just to clarify, I do not want my COM server to run as a Windows service, but the clients that use it do run as Windows services.)
Also, running the clients as either Local System, or Network Service, REGCLS_MULTIPLEUSE works as I would have expected: only a single COM server EXE process is started. The multiple processes are started when the COM clients are Windows services running under user accounts.
The routing of out-of-process activation requests is controlled by the registration of class objects with the COM Service Control Manager. If the SCM has a usable registered class object, that will be used to service the request. If it doesn't, it will start an exe process instance of the COM server to get one. Whether multiple activation requests are routed to a single COM server exe process therefore depends on the following factors at least (I'm not sure if this is a complete list):
the activation flags specified by the COM server when it calls CoRegisterClassObject to register with the SCM can cause future activation requests to result in a new exe process instance being started, the simplest and commonest case being the use of the flag REGCLS_SINGLEUSE, which allows the registered class object to be used for a single activation only.
Depending on how the class is registered, activation requests from different security contexts may be serviced by different COM server exe instances (it seems this won't apply in your scenario as your client applications run under the same security contexts).

Resources