4 * Copyright 2002 Marcus Meissner
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30 #define NONAMELESSUNION
31 #define NONAMELESSSTRUCT
44 #include "wine/unicode.h"
45 #include "wine/winbase16.h"
46 #include "compobj_private.h"
49 #include "compobj_private.h"
51 #include "wine/debug.h"
53 WINE_DEFAULT_DEBUG_CHANNEL(ole);
55 #define REQTYPE_REQUEST 0
56 typedef struct _wine_rpc_request_header {
61 } wine_rpc_request_header;
63 #define REQTYPE_RESPONSE 1
64 typedef struct _wine_rpc_response_header {
68 } wine_rpc_response_header;
70 /* used when shutting down a pipe, e.g. at the end of a process */
71 #define REQTYPE_DISCONNECT 2
72 typedef struct _wine_rpc_disconnect_header {
74 wine_marshal_id mid; /* mid of stub to delete */
75 } wine_rpc_disconnect_header;
78 #define REQSTATE_START 0
79 #define REQSTATE_REQ_QUEUED 1
80 #define REQSTATE_REQ_WAITING_FOR_REPLY 2
81 #define REQSTATE_REQ_GOT 3
82 #define REQSTATE_INVOKING 4
83 #define REQSTATE_RESP_QUEUED 5
84 #define REQSTATE_RESP_GOT 6
85 #define REQSTATE_DONE 6
87 typedef struct _wine_rpc_request {
89 HANDLE hPipe; /* temp copy of handle */
90 wine_rpc_request_header reqh;
91 wine_rpc_response_header resph;
95 static wine_rpc_request **reqs = NULL;
96 static int nrofreqs = 0;
98 /* This pipe is _thread_ based, each thread which talks to a remote
99 * apartment (mid) has its own pipe */
100 typedef struct _wine_pipe {
101 wine_marshal_id mid; /* target mid */
102 DWORD tid; /* thread which owns this outgoing pipe */
107 CRITICAL_SECTION crit;
110 static wine_pipe *pipes = NULL;
111 static int nrofpipes = 0;
113 typedef struct _PipeBuf {
114 IRpcChannelBufferVtbl *lpVtbl;
121 static HRESULT WINAPI
122 read_pipe(HANDLE hf, LPVOID ptr, DWORD size) {
124 if (!ReadFile(hf,ptr,size,&res,NULL)) {
125 FIXME("Failed to read from %p, le is %lx\n",hf,GetLastError());
129 FIXME("Read only %ld of %ld bytes from %p.\n",res,size,hf);
138 static int nrofreaders = 0;
142 memset(states,0,sizeof(states));
143 for (i=nrofreqs;i--;)
144 states[reqs[i]->state]++;
145 FIXME("%lx/%s/%d: rq %d, w %d, rg %d, rsq %d, rsg %d, d %d\n",
146 GetCurrentProcessId(),
149 states[REQSTATE_REQ_QUEUED],
150 states[REQSTATE_REQ_WAITING_FOR_REPLY],
151 states[REQSTATE_REQ_GOT],
152 states[REQSTATE_RESP_QUEUED],
153 states[REQSTATE_RESP_GOT],
154 states[REQSTATE_DONE]
161 static HRESULT WINAPI
162 write_pipe(HANDLE hf, LPVOID ptr, DWORD size) {
164 if (!WriteFile(hf,ptr,size,&res,NULL)) {
165 FIXME("Failed to write to %p, le is %lx\n",hf,GetLastError());
169 FIXME("Wrote only %ld of %ld bytes to %p.\n",res,size,hf);
175 static DWORD WINAPI _StubReaderThread(LPVOID);
178 PIPE_RegisterPipe(wine_marshal_id *mid, HANDLE hPipe, BOOL startreader) {
181 wine_pipe *new_pipes;
183 for (i=0;i<nrofpipes;i++)
184 if (pipes[i].mid.processid==mid->processid)
187 new_pipes=(wine_pipe*)HeapReAlloc(GetProcessHeap(),0,pipes,sizeof(pipes[0])*(nrofpipes+1));
189 new_pipes=(wine_pipe*)HeapAlloc(GetProcessHeap(),0,sizeof(pipes[0]));
190 if (!new_pipes) return E_OUTOFMEMORY;
192 sprintf(pipefn,OLESTUBMGR"_%08lx",mid->processid);
193 memcpy(&(pipes[nrofpipes].mid),mid,sizeof(*mid));
194 pipes[nrofpipes].hPipe = hPipe;
195 InitializeCriticalSection(&(pipes[nrofpipes].crit));
198 pipes[nrofpipes-1].hThread = CreateThread(NULL,0,_StubReaderThread,(LPVOID)(pipes+(nrofpipes-1)),0,&(pipes[nrofpipes-1].tid));
200 pipes[nrofpipes-1].tid = GetCurrentThreadId();
206 PIPE_FindByMID(wine_marshal_id *mid) {
208 for (i=0;i<nrofpipes;i++)
209 if ((pipes[i].mid.processid==mid->processid) &&
210 (GetCurrentThreadId()==pipes[i].tid)
212 return pipes[i].hPipe;
213 return INVALID_HANDLE_VALUE;
217 PIPE_GetFromMID(wine_marshal_id *mid) {
219 for (i=0;i<nrofpipes;i++) {
220 if ((pipes[i].mid.processid==mid->processid) &&
221 (GetCurrentThreadId()==pipes[i].tid)
229 RPC_GetRequest(wine_rpc_request **req) {
230 static int reqid = 0xdeadbeef;
233 for (i=0;i<nrofreqs;i++) { /* try to reuse */
234 if (reqs[i]->state == REQSTATE_DONE) {
235 reqs[i]->reqh.reqid = reqid++;
236 reqs[i]->resph.reqid = reqs[i]->reqh.reqid;
237 reqs[i]->hPipe = INVALID_HANDLE_VALUE;
239 reqs[i]->state = REQSTATE_START;
245 reqs = (wine_rpc_request**)HeapReAlloc(
249 sizeof(wine_rpc_request*)*(nrofreqs+1)
252 reqs = (wine_rpc_request**)HeapAlloc(
255 sizeof(wine_rpc_request*)
258 return E_OUTOFMEMORY;
259 reqs[nrofreqs] = (wine_rpc_request*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(wine_rpc_request));
260 reqs[nrofreqs]->reqh.reqid = reqid++;
261 reqs[nrofreqs]->resph.reqid = reqs[nrofreqs]->reqh.reqid;
262 reqs[nrofreqs]->hPipe = INVALID_HANDLE_VALUE;
263 *req = reqs[nrofreqs];
264 reqs[nrofreqs]->state = REQSTATE_START;
270 RPC_FreeRequest(wine_rpc_request *req) {
271 req->state = REQSTATE_DONE; /* Just reuse slot. */
275 static HRESULT WINAPI
276 PipeBuf_QueryInterface(
277 LPRPCCHANNELBUFFER iface,REFIID riid,LPVOID *ppv
280 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown)) {
281 *ppv = (LPVOID)iface;
282 IUnknown_AddRef(iface);
285 return E_NOINTERFACE;
289 PipeBuf_AddRef(LPRPCCHANNELBUFFER iface) {
290 PipeBuf *This = (PipeBuf *)iface;
291 return InterlockedIncrement(&This->ref);
295 PipeBuf_Release(LPRPCCHANNELBUFFER iface) {
296 PipeBuf *This = (PipeBuf *)iface;
298 wine_rpc_disconnect_header header;
300 DWORD reqtype = REQTYPE_DISCONNECT;
302 ref = InterlockedDecrement(&This->ref);
306 FIXME("Free all stuff\n");
308 memcpy(&header.mid, &This->mid, sizeof(wine_marshal_id));
310 pipe = PIPE_FindByMID(&This->mid);
312 write_pipe(pipe, &reqtype, sizeof(reqtype));
313 write_pipe(pipe, &header, sizeof(wine_rpc_disconnect_header));
315 TRACE("written disconnect packet\n");
317 HeapFree(GetProcessHeap(),0,This);
321 static HRESULT WINAPI
323 LPRPCCHANNELBUFFER iface,RPCOLEMESSAGE* msg,REFIID riid
325 /*PipeBuf *This = (PipeBuf *)iface;*/
327 TRACE("(%p,%s)\n",msg,debugstr_guid(riid));
328 /* probably reuses IID in real. */
329 if (msg->cbBuffer && (msg->Buffer == NULL))
330 msg->Buffer = HeapAlloc(GetProcessHeap(),0,msg->cbBuffer);
335 COM_InvokeAndRpcSend(wine_rpc_request *req) {
336 IRpcStubBuffer *stub;
341 hres = MARSHAL_Find_Stub_Buffer(&(req->reqh.mid),&stub);
343 ERR("Stub not found?\n");
346 msg.Buffer = req->Buffer;
347 msg.iMethod = req->reqh.iMethod;
348 msg.cbBuffer = req->reqh.cbBuffer;
349 msg.dataRepresentation = NDR_LOCAL_DATA_REPRESENTATION;
350 req->state = REQSTATE_INVOKING;
351 req->resph.retval = IRpcStubBuffer_Invoke(stub,&msg,NULL);
352 IUnknown_Release(stub);
353 req->Buffer = msg.Buffer;
354 req->resph.cbBuffer = msg.cbBuffer;
355 reqtype = REQTYPE_RESPONSE;
356 hres = write_pipe(req->hPipe,&reqtype,sizeof(reqtype));
357 if (hres) return hres;
358 hres = write_pipe(req->hPipe,&(req->resph),sizeof(req->resph));
359 if (hres) return hres;
360 hres = write_pipe(req->hPipe,req->Buffer,req->resph.cbBuffer);
361 if (hres) return hres;
362 req->state = REQSTATE_DONE;
367 static HRESULT COM_RpcReceive(wine_pipe *xpipe);
370 RPC_QueueRequestAndWait(wine_rpc_request *req) {
372 wine_rpc_request *xreq;
375 wine_pipe *xpipe = PIPE_GetFromMID(&(req->reqh.mid));
378 FIXME("no pipe found.\n");
381 if (GetCurrentProcessId() == req->reqh.mid.processid) {
382 ERR("In current process?\n");
385 req->hPipe = xpipe->hPipe;
386 req->state = REQSTATE_REQ_WAITING_FOR_REPLY;
387 reqtype = REQTYPE_REQUEST;
388 hres = write_pipe(req->hPipe,&reqtype,sizeof(reqtype));
389 if (hres) return hres;
390 hres = write_pipe(req->hPipe,&(req->reqh),sizeof(req->reqh));
391 if (hres) return hres;
392 hres = write_pipe(req->hPipe,req->Buffer,req->reqh.cbBuffer);
393 if (hres) return hres;
395 /* This loop is about allowing re-entrancy. While waiting for the
396 * response to one RPC we may receive a request starting another. */
398 hres = COM_RpcReceive(xpipe);
401 for (i=0;i<nrofreqs;i++) {
403 if ((xreq->state==REQSTATE_REQ_GOT) && (xreq->hPipe==req->hPipe)) {
404 hres = COM_InvokeAndRpcSend(xreq);
408 if (req->state == REQSTATE_RESP_GOT)
412 WARN("-- 0x%08lx\n", hres);
416 static HRESULT WINAPI
418 LPRPCCHANNELBUFFER iface,RPCOLEMESSAGE* msg,ULONG *status
420 PipeBuf *This = (PipeBuf *)iface;
421 wine_rpc_request *req;
426 if (This->mid.processid == GetCurrentProcessId()) {
427 ERR("Need to call directly!\n");
431 hres = RPC_GetRequest(&req);
432 if (hres) return hres;
433 req->reqh.iMethod = msg->iMethod;
434 req->reqh.cbBuffer = msg->cbBuffer;
435 memcpy(&(req->reqh.mid),&(This->mid),sizeof(This->mid));
436 req->Buffer = msg->Buffer;
437 hres = RPC_QueueRequestAndWait(req);
439 RPC_FreeRequest(req);
442 msg->cbBuffer = req->resph.cbBuffer;
443 msg->Buffer = req->Buffer;
444 *status = req->resph.retval;
445 RPC_FreeRequest(req);
450 static HRESULT WINAPI
451 PipeBuf_FreeBuffer(LPRPCCHANNELBUFFER iface,RPCOLEMESSAGE* msg) {
452 FIXME("(%p), stub!\n",msg);
456 static HRESULT WINAPI
458 LPRPCCHANNELBUFFER iface,DWORD* pdwDestContext,void** ppvDestContext
460 FIXME("(%p,%p), stub!\n",pdwDestContext,ppvDestContext);
464 static HRESULT WINAPI
465 PipeBuf_IsConnected(LPRPCCHANNELBUFFER iface) {
466 FIXME("(), stub!\n");
470 static IRpcChannelBufferVtbl pipebufvt = {
471 PipeBuf_QueryInterface,
482 PIPE_GetNewPipeBuf(wine_marshal_id *mid, IRpcChannelBuffer **pipebuf) {
483 wine_marshal_id ourid;
489 hPipe = PIPE_FindByMID(mid);
490 if (hPipe == INVALID_HANDLE_VALUE) {
492 sprintf(pipefn,OLESTUBMGR"_%08lx",mid->processid);
495 GENERIC_READ|GENERIC_WRITE,
502 if (hPipe == INVALID_HANDLE_VALUE) {
503 FIXME("Could not open named pipe %s, le is %lx\n",pipefn,GetLastError());
506 hres = PIPE_RegisterPipe(mid, hPipe, FALSE);
507 if (hres) return hres;
508 memset(&ourid,0,sizeof(ourid));
509 ourid.processid = GetCurrentProcessId();
510 if (!WriteFile(hPipe,&ourid,sizeof(ourid),&res,NULL)||(res!=sizeof(ourid))) {
511 ERR("Failed writing startup mid!\n");
515 pbuf = (PipeBuf*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(PipeBuf));
516 pbuf->lpVtbl = &pipebufvt;
518 memcpy(&(pbuf->mid),mid,sizeof(*mid));
519 *pipebuf = (IRpcChannelBuffer*)pbuf;
524 create_server(REFCLSID rclsid) {
525 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
528 HRESULT hres = E_UNEXPECTED;
530 WCHAR exe[MAX_PATH+1];
531 DWORD exelen = sizeof(exe);
532 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
534 PROCESS_INFORMATION pinfo;
536 WINE_StringFromCLSID((LPCLSID)rclsid,xclsid);
538 sprintf(buf,"CLSID\\%s\\LocalServer32",xclsid);
539 hres = RegOpenKeyExA(HKEY_CLASSES_ROOT, buf, 0, KEY_READ, &key);
541 if (hres != ERROR_SUCCESS) {
542 WARN("CLSID %s not registered as LocalServer32\n", xclsid);
543 return REGDB_E_READREGDB; /* Probably */
546 memset(exe,0,sizeof(exe));
547 hres= RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)exe, &exelen);
550 WARN("No default value for LocalServer32 key\n");
551 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
554 memset(&sinfo,0,sizeof(sinfo));
555 sinfo.cb = sizeof(sinfo);
557 /* EXE servers are started with the -Embedding switch. MSDN also claims /Embedding is used,
558 9x does -Embedding, perhaps an 9x/NT difference? */
560 strcpyW(command, exe);
561 strcatW(command, embedding);
563 TRACE("activating local server '%s' for %s\n", debugstr_w(command), xclsid);
565 if (!CreateProcessW(exe, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
566 WARN("failed to run local server %s\n", debugstr_w(exe));
572 /* http://msdn.microsoft.com/library/en-us/dnmsj99/html/com0199.asp, Figure 4 */
573 HRESULT create_marshalled_proxy(REFCLSID rclsid, REFIID iid, LPVOID *ppv) {
578 char marshalbuffer[200];
580 LARGE_INTEGER seekto;
581 ULARGE_INTEGER newpos;
583 #define MAXTRIES 10000
585 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
587 strcpy(pipefn,PIPEPREF);
588 WINE_StringFromCLSID(rclsid,pipefn+strlen(PIPEPREF));
590 while (tries++<MAXTRIES) {
591 WaitNamedPipeA( pipefn, NMPWAIT_WAIT_FOREVER );
594 GENERIC_READ|GENERIC_WRITE,
601 if (hPipe == INVALID_HANDLE_VALUE) {
603 if ((hres = create_server(rclsid)))
607 WARN("Could not open named pipe to broker %s, le is %lx\n",pipefn,GetLastError());
613 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
614 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
622 return E_NOINTERFACE;
623 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
624 if (hres) return hres;
625 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
627 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
628 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
629 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
631 IStream_Release(pStm);
637 PIPE_StartRequestThread(HANDLE xhPipe) {
638 wine_marshal_id remoteid;
641 hres = read_pipe(xhPipe,&remoteid,sizeof(remoteid));
643 ERR("Failed to read remote mid!\n");
646 PIPE_RegisterPipe(&remoteid,xhPipe, TRUE);
650 COM_RpcReceive(wine_pipe *xpipe) {
653 HANDLE xhPipe = xpipe->hPipe;
655 /*FIXME("%lx %d reading reqtype\n",GetCurrentProcessId(),xhPipe);*/
656 hres = read_pipe(xhPipe,&reqtype,sizeof(reqtype));
658 EnterCriticalSection(&(xpipe->crit));
659 /*FIXME("%lx got reqtype %ld\n",GetCurrentProcessId(),reqtype);*/
661 if (reqtype == REQTYPE_DISCONNECT) { /* only received by servers */
662 wine_rpc_disconnect_header header;
663 IRpcStubBuffer *stub;
666 hres = read_pipe(xhPipe, &header, sizeof(header));
668 ERR("could not read disconnect header\n");
672 TRACE("read disconnect header\n");
674 hres = MARSHAL_Find_Stub_Buffer(&header.mid, &stub);
676 ERR("could not locate stub to disconnect, mid.objectid=%p\n", (void*)header.mid.objectid);
681 /* release reference added by MARSHAL_Find_Stub_Buffer call */
682 IRpcStubBuffer_Release(stub);
683 /* release it for real */
684 ret = IRpcStubBuffer_Release(stub);
687 MARSHAL_Invalidate_Stub_From_MID(&header.mid);
689 } else if (reqtype == REQTYPE_REQUEST) {
690 wine_rpc_request *xreq;
691 RPC_GetRequest(&xreq);
692 xreq->hPipe = xhPipe;
693 hres = read_pipe(xhPipe,&(xreq->reqh),sizeof(xreq->reqh));
695 xreq->resph.reqid = xreq->reqh.reqid;
696 xreq->Buffer = HeapAlloc(GetProcessHeap(),0, xreq->reqh.cbBuffer);
697 hres = read_pipe(xhPipe,xreq->Buffer,xreq->reqh.cbBuffer);
699 xreq->state = REQSTATE_REQ_GOT;
701 } else if (reqtype == REQTYPE_RESPONSE) {
702 wine_rpc_response_header resph;
705 hres = read_pipe(xhPipe,&resph,sizeof(resph));
707 for (i=nrofreqs;i--;) {
708 wine_rpc_request *xreq = reqs[i];
709 if (xreq->state != REQSTATE_REQ_WAITING_FOR_REPLY)
711 if (xreq->reqh.reqid == resph.reqid) {
712 memcpy(&(xreq->resph),&resph,sizeof(resph));
715 xreq->Buffer = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,xreq->Buffer,xreq->resph.cbBuffer);
717 xreq->Buffer = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,xreq->resph.cbBuffer);
719 hres = read_pipe(xhPipe,xreq->Buffer,xreq->resph.cbBuffer);
721 xreq->state = REQSTATE_RESP_GOT;
722 /*PulseEvent(hRpcChanged);*/
726 ERR("Did not find request for id %lx\n",resph.reqid);
730 ERR("Unknown reqtype %ld\n",reqtype);
733 LeaveCriticalSection(&(xpipe->crit));
738 _StubReaderThread(LPVOID param) {
739 wine_pipe *xpipe = (wine_pipe*)param;
740 HANDLE xhPipe = xpipe->hPipe;
743 TRACE("STUB reader thread %lx\n",GetCurrentProcessId());
746 hres = COM_RpcReceive(xpipe);
749 for (i=nrofreqs;i--;) {
750 wine_rpc_request *xreq = reqs[i];
751 if ((xreq->state == REQSTATE_REQ_GOT) && (xreq->hPipe == xhPipe)) {
752 hres = COM_InvokeAndRpcSend(xreq);
757 FIXME("Failed with hres %lx\n",hres);
763 _StubMgrThread(LPVOID param) {
767 sprintf(pipefn,OLESTUBMGR"_%08lx",GetCurrentProcessId());
768 TRACE("Stub Manager Thread starting on (%s)\n",pipefn);
771 listenPipe = CreateNamedPipeA(
774 PIPE_TYPE_BYTE|PIPE_WAIT,
775 PIPE_UNLIMITED_INSTANCES,
778 NMPWAIT_USE_DEFAULT_WAIT,
781 if (listenPipe == INVALID_HANDLE_VALUE) {
782 FIXME("pipe creation failed for %s, le is %lx\n",pipefn,GetLastError());
783 return 1; /* permanent failure, so quit stubmgr thread */
785 if (!ConnectNamedPipe(listenPipe,NULL)) {
786 ERR("Failure during ConnectNamedPipe %lx!\n",GetLastError());
787 CloseHandle(listenPipe);
790 PIPE_StartRequestThread(listenPipe);
797 static BOOL stubMgrRunning = FALSE;
800 if (!stubMgrRunning) {
801 stubMgrRunning = TRUE;
802 CreateThread(NULL,0,_StubMgrThread,NULL,0,&tid);
803 Sleep(2000); /* actually we just try opening the pipe until it succeeds */