2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS Client/Server Runtime SubSystem
4 * FILE: subsystems/win32/csrsrv/api.c
5 * PURPOSE: CSR Server DLL API LPC Implementation
6 * "\windows\ApiPort" port process management functions
7 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
10 /* INCLUDES *******************************************************************/
17 /* GLOBALS ********************************************************************/
19 BOOLEAN (*CsrClientThreadSetup
)(VOID
) = NULL
;
20 UNICODE_STRING CsrApiPortName
;
21 volatile LONG CsrpStaticThreadCount
;
22 volatile LONG CsrpDynamicThreadTotal
;
23 extern ULONG CsrMaxApiRequestThreads
;
25 /* FUNCTIONS ******************************************************************/
28 * @name CsrCallServerFromServer
31 * The CsrCallServerFromServer routine calls a CSR API from within a server.
32 * It avoids using LPC messages since the request isn't coming from a client.
35 * Pointer to the CSR API Message to send to the server.
38 * Pointer to the CSR API Message to receive from the server.
40 * @return STATUS_SUCCESS in case of success, STATUS_ILLEGAL_FUNCTION
41 * if the ApiNumber is invalid, or STATUS_ACCESS_VIOLATION if there
42 * was a problem executing the API.
49 CsrCallServerFromServer(IN PCSR_API_MESSAGE ReceiveMsg
,
50 IN OUT PCSR_API_MESSAGE ReplyMsg
)
53 PCSR_SERVER_DLL ServerDll
;
55 CSR_REPLY_CODE ReplyCode
= CsrReplyImmediately
;
57 /* Get the Server ID */
58 ServerId
= CSR_API_NUMBER_TO_SERVER_ID(ReceiveMsg
->ApiNumber
);
60 /* Make sure that the ID is within limits, and the Server DLL loaded */
61 if ((ServerId
>= CSR_SERVER_DLL_MAX
) ||
62 (!(ServerDll
= CsrLoadedServerDll
[ServerId
])))
64 /* We are beyond the Maximum Server ID */
65 DPRINT1("CSRSS: %lx is invalid ServerDllIndex (%08x)\n", ServerId
, ServerDll
);
66 ReplyMsg
->Status
= (ULONG
)STATUS_ILLEGAL_FUNCTION
;
67 return STATUS_ILLEGAL_FUNCTION
;
71 /* Get the API ID, normalized with our Base ID */
72 ApiId
= CSR_API_NUMBER_TO_API_ID(ReceiveMsg
->ApiNumber
) - ServerDll
->ApiBase
;
74 /* Make sure that the ID is within limits, and the entry exists */
75 if ((ApiId
>= ServerDll
->HighestApiSupported
) ||
76 ((ServerDll
->ValidTable
) && !(ServerDll
->ValidTable
[ApiId
])))
78 /* We are beyond the Maximum API ID, or it doesn't exist */
79 DPRINT1("CSRSS: %lx (%s) is invalid ApiTableIndex for %Z or is an "
80 "invalid API to call from the server.\n",
81 ServerDll
->ValidTable
[ApiId
],
82 ((ServerDll
->NameTable
) && (ServerDll
->NameTable
[ApiId
])) ?
83 ServerDll
->NameTable
[ApiId
] : "*** UNKNOWN ***", &ServerDll
->Name
);
85 ReplyMsg
->Status
= (ULONG
)STATUS_ILLEGAL_FUNCTION
;
86 return STATUS_ILLEGAL_FUNCTION
;
92 DPRINT1("CSRSS: %s Api Request received from server process\n",
93 ServerDll
->NameTable
[ApiId
]);
96 /* Validation complete, start SEH */
99 /* Call the API, get the reply code and return the result */
100 ReplyMsg
->Status
= ServerDll
->DispatchTable
[ApiId
](ReceiveMsg
, &ReplyCode
);
102 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
104 /* If we got an exception, return access violation */
105 ReplyMsg
->Status
= STATUS_ACCESS_VIOLATION
;
110 return STATUS_SUCCESS
;
114 * @name CsrApiHandleConnectionRequest
116 * The CsrApiHandleConnectionRequest routine handles and accepts a new
117 * connection request to the CSR API LPC Port.
120 * Pointer to the incoming CSR API Message which contains the
121 * connection request.
123 * @return STATUS_SUCCESS in case of success, or status code which caused
124 * the routine to error.
126 * @remarks This routine is responsible for attaching the Shared Section to
127 * new clients connecting to CSR.
132 CsrApiHandleConnectionRequest(IN PCSR_API_MESSAGE ApiMessage
)
134 PCSR_THREAD CsrThread
= NULL
;
135 PCSR_PROCESS CsrProcess
= NULL
;
136 NTSTATUS Status
= STATUS_SUCCESS
;
137 PCSR_CONNECTION_INFO ConnectInfo
= &ApiMessage
->ConnectionInfo
;
138 BOOLEAN AllowConnection
= FALSE
;
139 REMOTE_PORT_VIEW RemotePortView
;
142 /* Acquire the Process Lock */
143 CsrAcquireProcessLock();
145 /* Lookup the CSR Thread */
146 CsrThread
= CsrLocateThreadByClientId(NULL
, &ApiMessage
->Header
.ClientId
);
148 /* Check if we have a thread */
151 /* Get the Process */
152 CsrProcess
= CsrThread
->Process
;
154 /* Make sure we have a Process as well */
157 /* Reference the Process */
158 CsrLockedReferenceProcess(CsrThread
->Process
);
160 /* Release the lock */
161 CsrReleaseProcessLock();
163 /* Duplicate the Object Directory */
164 Status
= NtDuplicateObject(NtCurrentProcess(),
166 CsrProcess
->ProcessHandle
,
167 &ConnectInfo
->ObjectDirectory
,
170 DUPLICATE_SAME_ACCESS
|
171 DUPLICATE_SAME_ATTRIBUTES
);
173 /* Acquire the lock */
174 CsrAcquireProcessLock();
176 /* Check for success */
177 if (NT_SUCCESS(Status
))
179 /* Attach the Shared Section */
180 Status
= CsrSrvAttachSharedSection(CsrProcess
, ConnectInfo
);
182 /* Check how this went */
183 if (NT_SUCCESS(Status
)) AllowConnection
= TRUE
;
186 /* Dereference the project */
187 CsrLockedDereferenceProcess(CsrProcess
);
191 /* Release the lock */
192 CsrReleaseProcessLock();
194 /* Setup the Port View Structure */
195 RemotePortView
.Length
= sizeof(REMOTE_PORT_VIEW
);
196 RemotePortView
.ViewSize
= 0;
197 RemotePortView
.ViewBase
= NULL
;
199 /* Save the Process ID */
200 ConnectInfo
->ProcessId
= NtCurrentTeb()->ClientId
.UniqueProcess
;
202 /* Accept the Connection */
203 Status
= NtAcceptConnectPort(&ServerPort
,
204 AllowConnection
? UlongToPtr(CsrProcess
->SequenceNumber
) : 0,
209 if (!NT_SUCCESS(Status
))
211 DPRINT1("CSRSS: NtAcceptConnectPort - failed. Status == %X\n", Status
);
213 else if (AllowConnection
)
217 DPRINT1("CSRSS: ClientId: %lx.%lx has ClientView: Base=%p, Size=%lx\n",
218 ApiMessage
->Header
.ClientId
.UniqueProcess
,
219 ApiMessage
->Header
.ClientId
.UniqueThread
,
220 RemotePortView
.ViewBase
,
221 RemotePortView
.ViewSize
);
224 /* Set some Port Data in the Process */
225 CsrProcess
->ClientPort
= ServerPort
;
226 CsrProcess
->ClientViewBase
= (ULONG_PTR
)RemotePortView
.ViewBase
;
227 CsrProcess
->ClientViewBounds
= (ULONG_PTR
)((ULONG_PTR
)RemotePortView
.ViewBase
+
228 (ULONG_PTR
)RemotePortView
.ViewSize
);
230 /* Complete the connection */
231 Status
= NtCompleteConnectPort(ServerPort
);
232 if (!NT_SUCCESS(Status
))
234 DPRINT1("CSRSS: NtCompleteConnectPort - failed. Status == %X\n", Status
);
239 DPRINT1("CSRSS: Rejecting Connection Request from ClientId: %lx.%lx\n",
240 ApiMessage
->Header
.ClientId
.UniqueProcess
,
241 ApiMessage
->Header
.ClientId
.UniqueThread
);
244 /* Return status to caller */
249 * @name CsrpCheckRequestThreads
251 * The CsrpCheckRequestThreads routine checks if there are no more threads
252 * to handle CSR API Requests, and creates a new thread if possible, to
257 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
258 * if a new thread couldn't be created.
265 CsrpCheckRequestThreads(VOID
)
271 /* Decrease the count, and see if we're out */
272 if (!(_InterlockedDecrement(&CsrpStaticThreadCount
)))
274 /* Check if we've still got space for a Dynamic Thread */
275 if (CsrpDynamicThreadTotal
< CsrMaxApiRequestThreads
)
277 /* Create a new dynamic thread */
278 Status
= RtlCreateUserThread(NtCurrentProcess(),
284 (PVOID
)CsrApiRequestThread
,
289 if (NT_SUCCESS(Status
))
291 /* Increase the thread counts */
292 _InterlockedIncrement(&CsrpStaticThreadCount
);
293 _InterlockedIncrement(&CsrpDynamicThreadTotal
);
295 /* Add a new server thread */
296 if (CsrAddStaticServerThread(hThread
,
298 CsrThreadIsServerThread
))
301 NtResumeThread(hThread
, NULL
);
305 /* Failed to create a new static thread */
306 _InterlockedDecrement(&CsrpStaticThreadCount
);
307 _InterlockedDecrement(&CsrpDynamicThreadTotal
);
310 DPRINT1("Failing\n");
311 NtTerminateThread(hThread
, 0);
315 return STATUS_UNSUCCESSFUL
;
322 return STATUS_SUCCESS
;
326 * @name CsrApiRequestThread
328 * The CsrApiRequestThread routine handles incoming messages or connection
329 * requests on the CSR API LPC Port.
332 * System-default user-defined parameter. Unused.
334 * @return The thread exit code, if the thread is terminated.
336 * @remarks Before listening on the port, the routine will first attempt
337 * to connect to the user subsystem.
342 CsrApiRequestThread(IN PVOID Parameter
)
344 PTEB Teb
= NtCurrentTeb();
345 LARGE_INTEGER TimeOut
;
346 PCSR_THREAD CurrentThread
, CsrThread
;
348 CSR_REPLY_CODE ReplyCode
;
349 PCSR_API_MESSAGE ReplyMsg
;
350 CSR_API_MESSAGE ReceiveMsg
;
351 PCSR_PROCESS CsrProcess
;
352 PHARDERROR_MSG HardErrorMsg
;
354 PCSR_SERVER_DLL ServerDll
;
355 PCLIENT_DIED_MSG ClientDiedMsg
;
356 PDBGKM_MSG DebugMessage
;
357 ULONG ServerId
, ApiId
, MessageType
, i
;
360 /* Setup LPC loop port and message */
362 ReplyPort
= CsrApiPort
;
364 /* Connect to user32 */
365 while (!CsrConnectToUser())
367 /* Set up the timeout for the connect (30 seconds) */
368 TimeOut
.QuadPart
= -30 * 1000 * 1000 * 10;
370 /* Keep trying until we get a response */
371 Teb
->Win32ClientInfo
[0] = 0;
372 NtDelayExecution(FALSE
, &TimeOut
);
376 CurrentThread
= Teb
->CsrClientThread
;
378 /* If we got an event... */
381 /* Set it, to let stuff waiting on us load */
382 Status
= NtSetEvent((HANDLE
)Parameter
, NULL
);
383 ASSERT(NT_SUCCESS(Status
));
385 /* Increase the Thread Counts */
386 _InterlockedIncrement(&CsrpStaticThreadCount
);
387 _InterlockedIncrement(&CsrpDynamicThreadTotal
);
390 /* Now start the loop */
393 /* Make sure the real CID is set */
394 Teb
->RealClientId
= Teb
->ClientId
;
397 if (Teb
->CountOfOwnedCriticalSections
)
399 DPRINT1("CSRSRV: FATAL ERROR. CsrThread is Idle while holding %lu critical sections\n",
400 Teb
->CountOfOwnedCriticalSections
);
401 DPRINT1("CSRSRV: Last Receive Message %lx ReplyMessage %lx\n",
402 &ReceiveMsg
, ReplyMsg
);
406 /* Wait for a message to come through */
407 Status
= NtReplyWaitReceivePort(ReplyPort
,
412 /* Check if we didn't get success */
413 if (Status
!= STATUS_SUCCESS
)
415 /* Was it a failure or another success code? */
416 if (!NT_SUCCESS(Status
))
418 /* Check for specific status cases */
419 if ((Status
!= STATUS_INVALID_CID
) &&
420 (Status
!= STATUS_UNSUCCESSFUL
) &&
421 ((Status
== STATUS_INVALID_HANDLE
) || (ReplyPort
== CsrApiPort
)))
423 /* Notify the debugger */
424 DPRINT1("CSRSS: ReceivePort failed - Status == %X\n", Status
);
425 DPRINT1("CSRSS: ReplyPortHandle %lx CsrApiPort %lx\n", ReplyPort
, CsrApiPort
);
428 /* We failed big time, so start out fresh */
430 ReplyPort
= CsrApiPort
;
435 /* A bizare "success" code, just try again */
436 DPRINT1("NtReplyWaitReceivePort returned \"success\" status 0x%x\n", Status
);
441 /* Use whatever Client ID we got */
442 Teb
->RealClientId
= ReceiveMsg
.Header
.ClientId
;
444 /* Get the Message Type */
445 MessageType
= ReceiveMsg
.Header
.u2
.s2
.Type
;
447 /* Handle connection requests */
448 if (MessageType
== LPC_CONNECTION_REQUEST
)
450 /* Handle the Connection Request */
451 CsrApiHandleConnectionRequest(&ReceiveMsg
);
454 ReplyPort
= CsrApiPort
;
458 /* It's some other kind of request. Get the lock for the lookup */
459 CsrAcquireProcessLock();
461 /* Now do the lookup to get the CSR_THREAD */
462 CsrThread
= CsrLocateThreadByClientId(&CsrProcess
,
463 &ReceiveMsg
.Header
.ClientId
);
465 /* Did we find a thread? */
468 /* This wasn't a CSR Thread, release lock */
469 CsrReleaseProcessLock();
471 /* If this was an exception, handle it */
472 if (MessageType
== LPC_EXCEPTION
)
474 ReplyMsg
= &ReceiveMsg
;
475 ReplyPort
= CsrApiPort
;
476 ReplyMsg
->Status
= DBG_CONTINUE
;
478 else if (MessageType
== LPC_PORT_CLOSED
||
479 MessageType
== LPC_CLIENT_DIED
)
481 /* The Client or Port are gone, loop again */
483 ReplyPort
= CsrApiPort
;
485 else if (MessageType
== LPC_ERROR_EVENT
)
487 /* If it's a hard error, handle this too */
488 HardErrorMsg
= (PHARDERROR_MSG
)&ReceiveMsg
;
490 /* Default it to unhandled */
491 HardErrorMsg
->Response
= ResponseNotHandled
;
493 /* Check if there are free api threads */
494 CsrpCheckRequestThreads();
495 if (CsrpStaticThreadCount
)
497 /* Loop every Server DLL */
498 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
500 /* Get the Server DLL */
501 ServerDll
= CsrLoadedServerDll
[i
];
503 /* Check if it's valid and if it has a Hard Error Callback */
504 if ((ServerDll
) && (ServerDll
->HardErrorCallback
))
507 ServerDll
->HardErrorCallback(NULL
/* CsrThread == NULL */, HardErrorMsg
);
509 /* If it's handled, get out of here */
510 if (HardErrorMsg
->Response
!= ResponseNotHandled
) break;
515 /* Increase the thread count */
516 _InterlockedIncrement(&CsrpStaticThreadCount
);
518 /* If the response was 0xFFFFFFFF, we'll ignore it */
519 if (HardErrorMsg
->Response
== 0xFFFFFFFF)
522 ReplyPort
= CsrApiPort
;
526 ReplyMsg
= &ReceiveMsg
;
529 else if (MessageType
== LPC_REQUEST
)
531 /* This is an API Message coming from a non-CSR Thread */
532 ReplyMsg
= &ReceiveMsg
;
533 ReplyPort
= CsrApiPort
;
534 ReplyMsg
->Status
= STATUS_ILLEGAL_FUNCTION
;
536 else if (MessageType
== LPC_DATAGRAM
)
538 /* This is an API call, get the Server ID */
539 ServerId
= CSR_API_NUMBER_TO_SERVER_ID(ReceiveMsg
.ApiNumber
);
541 /* Make sure that the ID is within limits, and the Server DLL loaded */
543 if ((ServerId
>= CSR_SERVER_DLL_MAX
) ||
544 (!(ServerDll
= CsrLoadedServerDll
[ServerId
])))
546 /* We are beyond the Maximum Server ID */
547 DPRINT1("CSRSS: %lx is invalid ServerDllIndex (%08x)\n",
548 ServerId
, ServerDll
);
552 ReplyPort
= CsrApiPort
;
556 /* Get the API ID, normalized with our Base ID */
557 ApiId
= CSR_API_NUMBER_TO_API_ID(ReceiveMsg
.ApiNumber
) - ServerDll
->ApiBase
;
559 /* Make sure that the ID is within limits, and the entry exists */
560 if (ApiId
>= ServerDll
->HighestApiSupported
)
562 /* We are beyond the Maximum API ID, or it doesn't exist */
563 DPRINT1("CSRSS: %lx is invalid ApiTableIndex for %Z\n",
564 CSR_API_NUMBER_TO_API_ID(ReceiveMsg
.ApiNumber
),
567 ReplyPort
= CsrApiPort
;
574 DPRINT1("[%02x] CSRSS: [%02x,%02x] - %s Api called from %08x\n",
575 Teb
->ClientId
.UniqueThread
,
576 ReceiveMsg
.Header
.ClientId
.UniqueProcess
,
577 ReceiveMsg
.Header
.ClientId
.UniqueThread
,
578 ServerDll
->NameTable
[ApiId
],
583 ReceiveMsg
.Status
= STATUS_SUCCESS
;
585 /* Validation complete, start SEH */
588 /* Make sure we have enough threads */
589 CsrpCheckRequestThreads();
591 /* Call the API and get the reply code */
593 ReplyPort
= CsrApiPort
;
594 ServerDll
->DispatchTable
[ApiId
](&ReceiveMsg
, &ReplyCode
);
596 /* Increase the static thread count */
597 _InterlockedIncrement(&CsrpStaticThreadCount
);
599 _SEH2_EXCEPT(CsrUnhandledExceptionFilter(_SEH2_GetExceptionInformation()))
602 ReplyPort
= CsrApiPort
;
608 /* Some other ignored message type */
610 ReplyPort
= CsrApiPort
;
617 /* We have a valid thread, was this an LPC Request? */
618 if (MessageType
!= LPC_REQUEST
)
620 /* It's not an API, check if the client died */
621 if (MessageType
== LPC_CLIENT_DIED
)
623 /* Get the information and check if it matches our thread */
624 ClientDiedMsg
= (PCLIENT_DIED_MSG
)&ReceiveMsg
;
625 if (ClientDiedMsg
->CreateTime
.QuadPart
== CsrThread
->CreateTime
.QuadPart
)
627 /* Reference the thread */
628 CsrLockedReferenceThread(CsrThread
);
630 /* Destroy the thread in the API Message */
631 CsrDestroyThread(&ReceiveMsg
.Header
.ClientId
);
633 /* Check if the thread was actually ourselves */
634 if (CsrProcess
->ThreadCount
== 1)
636 /* Kill the process manually here */
637 CsrDestroyProcess(&CsrThread
->ClientId
, 0);
640 /* Remove our extra reference */
641 CsrLockedDereferenceThread(CsrThread
);
644 /* Release the lock and keep looping */
645 CsrReleaseProcessLock();
648 ReplyPort
= CsrApiPort
;
652 /* Reference the thread and release the lock */
653 CsrLockedReferenceThread(CsrThread
);
654 CsrReleaseProcessLock();
656 /* Check if this was an exception */
657 if (MessageType
== LPC_EXCEPTION
)
659 /* Kill the process */
660 NtTerminateProcess(CsrProcess
->ProcessHandle
, STATUS_ABANDONED
);
662 /* Destroy it from CSR */
663 CsrDestroyProcess(&ReceiveMsg
.Header
.ClientId
, STATUS_ABANDONED
);
665 /* Return a Debug Message */
666 DebugMessage
= (PDBGKM_MSG
)&ReceiveMsg
;
667 DebugMessage
->ReturnedStatus
= DBG_CONTINUE
;
668 ReplyMsg
= &ReceiveMsg
;
669 ReplyPort
= CsrApiPort
;
671 /* Remove our extra reference */
672 CsrDereferenceThread(CsrThread
);
674 else if (MessageType
== LPC_ERROR_EVENT
)
676 /* If it's a hard error, handle this too */
677 HardErrorMsg
= (PHARDERROR_MSG
)&ReceiveMsg
;
679 /* Default it to unhandled */
680 HardErrorMsg
->Response
= ResponseNotHandled
;
682 /* Check if there are free api threads */
683 CsrpCheckRequestThreads();
684 if (CsrpStaticThreadCount
)
686 /* Loop every Server DLL */
687 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
689 /* Get the Server DLL */
690 ServerDll
= CsrLoadedServerDll
[i
];
692 /* Check if it's valid and if it has a Hard Error Callback */
693 if ((ServerDll
) && (ServerDll
->HardErrorCallback
))
696 ServerDll
->HardErrorCallback(CsrThread
, HardErrorMsg
);
698 /* If it's handled, get out of here */
699 if (HardErrorMsg
->Response
!= ResponseNotHandled
) break;
704 /* Increase the thread count */
705 _InterlockedIncrement(&CsrpStaticThreadCount
);
707 /* If the response was 0xFFFFFFFF, we'll ignore it */
708 if (HardErrorMsg
->Response
== 0xFFFFFFFF)
711 ReplyPort
= CsrApiPort
;
715 CsrDereferenceThread(CsrThread
);
716 ReplyMsg
= &ReceiveMsg
;
717 ReplyPort
= CsrApiPort
;
723 CsrDereferenceThread(CsrThread
);
731 /* We got an API Request */
732 CsrLockedReferenceThread(CsrThread
);
733 CsrReleaseProcessLock();
735 /* This is an API call, get the Server ID */
736 ServerId
= CSR_API_NUMBER_TO_SERVER_ID(ReceiveMsg
.ApiNumber
);
738 /* Make sure that the ID is within limits, and the Server DLL loaded */
740 if ((ServerId
>= CSR_SERVER_DLL_MAX
) ||
741 (!(ServerDll
= CsrLoadedServerDll
[ServerId
])))
743 /* We are beyond the Maximum Server ID */
744 DPRINT1("CSRSS: %lx is invalid ServerDllIndex (%08x)\n",
745 ServerId
, ServerDll
);
748 ReplyPort
= CsrApiPort
;
749 ReplyMsg
= &ReceiveMsg
;
750 ReplyMsg
->Status
= STATUS_ILLEGAL_FUNCTION
;
751 CsrDereferenceThread(CsrThread
);
755 /* Get the API ID, normalized with our Base ID */
756 ApiId
= CSR_API_NUMBER_TO_API_ID(ReceiveMsg
.ApiNumber
) - ServerDll
->ApiBase
;
758 /* Make sure that the ID is within limits, and the entry exists */
759 if (ApiId
>= ServerDll
->HighestApiSupported
)
761 /* We are beyond the Maximum API ID, or it doesn't exist */
762 DPRINT1("CSRSS: %lx is invalid ApiTableIndex for %Z\n",
763 CSR_API_NUMBER_TO_API_ID(ReceiveMsg
.ApiNumber
),
766 ReplyPort
= CsrApiPort
;
767 ReplyMsg
= &ReceiveMsg
;
768 ReplyMsg
->Status
= STATUS_ILLEGAL_FUNCTION
;
769 CsrDereferenceThread(CsrThread
);
775 DPRINT1("[%02x] CSRSS: [%02x,%02x] - %s Api called from %08x\n",
776 Teb
->ClientId
.UniqueThread
,
777 ReceiveMsg
.Header
.ClientId
.UniqueProcess
,
778 ReceiveMsg
.Header
.ClientId
.UniqueThread
,
779 ServerDll
->NameTable
[ApiId
],
784 ReplyMsg
= &ReceiveMsg
;
785 ReceiveMsg
.Status
= STATUS_SUCCESS
;
787 /* Now we reply to a particular client */
788 ReplyPort
= CsrThread
->Process
->ClientPort
;
790 /* Check if there's a capture buffer */
791 if (ReceiveMsg
.CsrCaptureData
)
793 /* Capture the arguments */
794 if (!CsrCaptureArguments(CsrThread
, &ReceiveMsg
))
796 /* Ignore this message if we failed to get the arguments */
797 CsrDereferenceThread(CsrThread
);
802 /* Validation complete, start SEH */
805 /* Make sure we have enough threads */
806 CsrpCheckRequestThreads();
808 Teb
->CsrClientThread
= CsrThread
;
810 /* Call the API, get the reply code and return the result */
811 ReplyCode
= CsrReplyImmediately
;
812 ReplyMsg
->Status
= ServerDll
->DispatchTable
[ApiId
](&ReceiveMsg
, &ReplyCode
);
814 /* Increase the static thread count */
815 _InterlockedIncrement(&CsrpStaticThreadCount
);
817 Teb
->CsrClientThread
= CurrentThread
;
819 if (ReplyCode
== CsrReplyAlreadyDone
)
821 if (ReceiveMsg
.CsrCaptureData
)
823 CsrReleaseCapturedArguments(&ReceiveMsg
);
826 ReplyPort
= CsrApiPort
;
827 CsrDereferenceThread(CsrThread
);
829 else if (ReplyCode
== CsrReplyDeadClient
)
831 /* Reply to the death message */
832 NtReplyPort(ReplyPort
, &ReplyMsg
->Header
);
834 /* Reply back to the API port now */
836 ReplyPort
= CsrApiPort
;
838 CsrDereferenceThread(CsrThread
);
840 else if (ReplyCode
== CsrReplyPending
)
843 ReplyPort
= CsrApiPort
;
847 if (ReceiveMsg
.CsrCaptureData
)
849 CsrReleaseCapturedArguments(&ReceiveMsg
);
851 CsrDereferenceThread(CsrThread
);
854 _SEH2_EXCEPT(CsrUnhandledExceptionFilter(_SEH2_GetExceptionInformation()))
857 ReplyPort
= CsrApiPort
;
862 /* We're out of the loop for some reason, terminate! */
863 NtTerminateThread(NtCurrentThread(), Status
);
868 * @name CsrApiPortInitialize
870 * The CsrApiPortInitialize routine initializes the LPC Port used for
871 * communications with the Client/Server Runtime (CSR) and initializes the
872 * static thread that will handle connection requests and APIs.
876 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
884 CsrApiPortInitialize(VOID
)
887 OBJECT_ATTRIBUTES ObjectAttributes
;
889 HANDLE hRequestEvent
, hThread
;
891 PLIST_ENTRY ListHead
, NextEntry
;
892 PCSR_THREAD ServerThread
;
894 /* Calculate how much space we'll need for the Port Name */
895 Size
= CsrDirectoryName
.Length
+ sizeof(CSR_PORT_NAME
) + sizeof(WCHAR
);
897 /* Create the buffer for it */
898 CsrApiPortName
.Buffer
= RtlAllocateHeap(CsrHeap
, 0, Size
);
899 if (!CsrApiPortName
.Buffer
) return STATUS_NO_MEMORY
;
901 /* Setup the rest of the empty string */
902 CsrApiPortName
.Length
= 0;
903 CsrApiPortName
.MaximumLength
= (USHORT
)Size
;
904 RtlAppendUnicodeStringToString(&CsrApiPortName
, &CsrDirectoryName
);
905 RtlAppendUnicodeToString(&CsrApiPortName
, UNICODE_PATH_SEP
);
906 RtlAppendUnicodeToString(&CsrApiPortName
, CSR_PORT_NAME
);
909 DPRINT1("CSRSS: Creating %wZ port and associated threads\n", &CsrApiPortName
);
910 DPRINT1("CSRSS: sizeof( CONNECTINFO ) == %ld sizeof( API_MSG ) == %ld\n",
911 sizeof(CSR_CONNECTION_INFO
), sizeof(CSR_API_MESSAGE
));
914 /* FIXME: Create a Security Descriptor */
916 /* Initialize the Attributes */
917 InitializeObjectAttributes(&ObjectAttributes
,
923 /* Create the Port Object */
924 Status
= NtCreatePort(&CsrApiPort
,
926 LPC_MAX_DATA_LENGTH
, // HACK: the real value is: sizeof(CSR_CONNECTION_INFO),
927 LPC_MAX_MESSAGE_LENGTH
, // HACK: the real value is: sizeof(CSR_API_MESSAGE),
929 if (NT_SUCCESS(Status
))
931 /* Create the event the Port Thread will use */
932 Status
= NtCreateEvent(&hRequestEvent
,
935 SynchronizationEvent
,
937 if (NT_SUCCESS(Status
))
939 /* Create the Request Thread */
940 Status
= RtlCreateUserThread(NtCurrentProcess(),
946 (PVOID
)CsrApiRequestThread
,
947 (PVOID
)hRequestEvent
,
950 if (NT_SUCCESS(Status
))
952 /* Add this as a static thread to CSRSRV */
953 CsrAddStaticServerThread(hThread
, &ClientId
, CsrThreadIsServerThread
);
955 /* Get the Thread List Pointers */
956 ListHead
= &CsrRootProcess
->ThreadList
;
957 NextEntry
= ListHead
->Flink
;
959 /* Start looping the list */
960 while (NextEntry
!= ListHead
)
963 ServerThread
= CONTAINING_RECORD(NextEntry
, CSR_THREAD
, Link
);
966 Status
= NtResumeThread(ServerThread
->ThreadHandle
, NULL
);
968 /* Is this a Server Thread? */
969 if (ServerThread
->Flags
& CsrThreadIsServerThread
)
971 /* If so, then wait for it to initialize */
972 Status
= NtWaitForSingleObject(hRequestEvent
, FALSE
, NULL
);
973 ASSERT(NT_SUCCESS(Status
));
977 NextEntry
= NextEntry
->Flink
;
980 /* We don't need this anymore */
981 NtClose(hRequestEvent
);
991 * @name CsrConnectToUser
994 * The CsrConnectToUser connects to the User subsystem.
998 * @return A pointer to the CSR Thread
1005 CsrConnectToUser(VOID
)
1007 #if 0 // This code is OK, however it is ClientThreadSetup which sucks.
1009 ANSI_STRING DllName
;
1010 UNICODE_STRING TempName
;
1013 PTEB Teb
= NtCurrentTeb();
1014 PCSR_THREAD CsrThread
;
1017 /* Check if we didn't already find it */
1018 if (!CsrClientThreadSetup
)
1020 /* Get the DLL Handle for user32.dll */
1021 RtlInitAnsiString(&DllName
, "user32");
1022 RtlAnsiStringToUnicodeString(&TempName
, &DllName
, TRUE
);
1023 Status
= LdrGetDllHandle(NULL
,
1027 RtlFreeUnicodeString(&TempName
);
1029 /* If we got the handle, get the Client Thread Startup Entrypoint */
1030 if (NT_SUCCESS(Status
))
1032 RtlInitAnsiString(&StartupName
,"ClientThreadSetup");
1033 Status
= LdrGetProcedureAddress(hUser32
,
1036 (PVOID
)&CsrClientThreadSetup
);
1040 /* Connect to user32 */
1043 Connected
= CsrClientThreadSetup();
1045 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1052 DPRINT1("CSRSS: CsrConnectToUser failed\n");
1056 /* Save pointer to this thread in TEB */
1057 CsrAcquireProcessLock();
1058 CsrThread
= CsrLocateThreadInProcess(NULL
, &Teb
->ClientId
);
1059 CsrReleaseProcessLock();
1060 if (CsrThread
) Teb
->CsrClientThread
= CsrThread
;
1067 PTEB Teb
= NtCurrentTeb();
1068 PCSR_THREAD CsrThread
;
1070 /* Save pointer to this thread in TEB */
1071 CsrThread
= CsrLocateThreadInProcess(NULL
, &Teb
->ClientId
);
1072 if (CsrThread
) Teb
->CsrClientThread
= CsrThread
;
1080 * @name CsrQueryApiPort
1083 * The CsrQueryApiPort routine returns a handle to the CSR API LPC port.
1087 * @return A handle to the port.
1094 CsrQueryApiPort(VOID
)
1096 DPRINT("CSRSRV: %s called\n", __FUNCTION__
);
1101 * @name CsrCaptureArguments
1102 * @implemented NT5.1
1104 * The CsrCaptureArguments routine validates a CSR Capture Buffer and
1105 * re-captures it into a server CSR Capture Buffer.
1108 * Pointer to the CSR Thread performing the validation.
1111 * Pointer to the CSR API Message containing the Capture Buffer
1112 * that needs to be validated.
1114 * @return TRUE if validation succeeded, FALSE otherwise.
1121 CsrCaptureArguments(IN PCSR_THREAD CsrThread
,
1122 IN PCSR_API_MESSAGE ApiMessage
)
1124 PCSR_CAPTURE_BUFFER LocalCaptureBuffer
= NULL
, RemoteCaptureBuffer
= NULL
;
1125 SIZE_T BufferDistance
;
1129 /* Use SEH to make sure this is valid */
1132 /* Get the buffer we got from whoever called NTDLL */
1133 LocalCaptureBuffer
= ApiMessage
->CsrCaptureData
;
1134 Length
= LocalCaptureBuffer
->Size
;
1136 /* Now check if the buffer is inside our mapped section */
1137 if (((ULONG_PTR
)LocalCaptureBuffer
< CsrThread
->Process
->ClientViewBase
) ||
1138 (((ULONG_PTR
)LocalCaptureBuffer
+ Length
) >= CsrThread
->Process
->ClientViewBounds
))
1140 /* Return failure */
1141 DPRINT1("*** CSRSS: CaptureBuffer outside of ClientView\n");
1142 ApiMessage
->Status
= STATUS_INVALID_PARAMETER
;
1143 _SEH2_YIELD(return FALSE
);
1146 /* Check if the Length is valid */
1147 if ((FIELD_OFFSET(CSR_CAPTURE_BUFFER
, PointerOffsetsArray
) +
1148 (LocalCaptureBuffer
->PointerCount
* sizeof(PVOID
)) > Length
) ||
1151 /* Return failure */
1152 DPRINT1("*** CSRSS: CaptureBuffer %p has bad length\n", LocalCaptureBuffer
);
1154 ApiMessage
->Status
= STATUS_INVALID_PARAMETER
;
1155 _SEH2_YIELD(return FALSE
);
1158 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1160 /* Return failure */
1161 ApiMessage
->Status
= STATUS_INVALID_PARAMETER
;
1162 _SEH2_YIELD(return FALSE
);
1165 /* We validated the incoming buffer, now allocate the remote one */
1166 RemoteCaptureBuffer
= RtlAllocateHeap(CsrHeap
, 0, Length
);
1167 if (!RemoteCaptureBuffer
)
1169 /* We're out of memory */
1170 ApiMessage
->Status
= STATUS_NO_MEMORY
;
1174 /* Copy the client's buffer */
1175 RtlMoveMemory(RemoteCaptureBuffer
, LocalCaptureBuffer
, Length
);
1177 /* Calculate the difference between our buffer and the client's */
1178 BufferDistance
= (ULONG_PTR
)RemoteCaptureBuffer
- (ULONG_PTR
)LocalCaptureBuffer
;
1181 * Convert all the pointer offsets into real pointers, and make
1182 * them point to the remote data buffer instead of the local one.
1184 for (i
= 0 ; i
< RemoteCaptureBuffer
->PointerCount
; ++i
)
1186 if (RemoteCaptureBuffer
->PointerOffsetsArray
[i
] != 0)
1188 RemoteCaptureBuffer
->PointerOffsetsArray
[i
] += (ULONG_PTR
)ApiMessage
;
1190 /* Validate the bounds of the current pointer */
1191 if ((*(PULONG_PTR
)RemoteCaptureBuffer
->PointerOffsetsArray
[i
] >= CsrThread
->Process
->ClientViewBase
) &&
1192 (*(PULONG_PTR
)RemoteCaptureBuffer
->PointerOffsetsArray
[i
] < CsrThread
->Process
->ClientViewBounds
))
1194 /* Modify the pointer to take into account its new position */
1195 *(PULONG_PTR
)RemoteCaptureBuffer
->PointerOffsetsArray
[i
] += BufferDistance
;
1199 /* Invalid pointer, fail */
1200 DPRINT1("*** CSRSS: CaptureBuffer MessagePointer outside of ClientView\n");
1202 ApiMessage
->Status
= STATUS_INVALID_PARAMETER
;
1207 /* Check if we got success */
1208 if (ApiMessage
->Status
!= STATUS_SUCCESS
)
1210 /* Failure. Free the buffer and return*/
1211 RtlFreeHeap(CsrHeap
, 0, RemoteCaptureBuffer
);
1216 /* Success, save the previous buffer */
1217 RemoteCaptureBuffer
->PreviousCaptureBuffer
= LocalCaptureBuffer
;
1218 ApiMessage
->CsrCaptureData
= RemoteCaptureBuffer
;
1226 * @name CsrReleaseCapturedArguments
1227 * @implemented NT5.1
1229 * The CsrReleaseCapturedArguments routine releases a Capture Buffer
1230 * that was previously captured with CsrCaptureArguments.
1233 * Pointer to the CSR API Message containing the Capture Buffer
1234 * that needs to be released.
1243 CsrReleaseCapturedArguments(IN PCSR_API_MESSAGE ApiMessage
)
1245 PCSR_CAPTURE_BUFFER RemoteCaptureBuffer
, LocalCaptureBuffer
;
1246 SIZE_T BufferDistance
;
1249 /* Get the capture buffers */
1250 RemoteCaptureBuffer
= ApiMessage
->CsrCaptureData
;
1251 LocalCaptureBuffer
= RemoteCaptureBuffer
->PreviousCaptureBuffer
;
1253 /* Do not continue if there is no captured buffer */
1254 if (!RemoteCaptureBuffer
) return;
1256 /* Free the previous one */
1257 RemoteCaptureBuffer
->PreviousCaptureBuffer
= NULL
;
1259 /* Calculate the difference between our buffer and the client's */
1260 BufferDistance
= (ULONG_PTR
)RemoteCaptureBuffer
- (ULONG_PTR
)LocalCaptureBuffer
;
1263 * Convert back all the pointers into pointer offsets, and make them
1264 * point to the local data buffer instead of the remote one (revert
1265 * the logic of CsrCaptureArguments).
1267 for (i
= 0 ; i
< RemoteCaptureBuffer
->PointerCount
; ++i
)
1269 if (RemoteCaptureBuffer
->PointerOffsetsArray
[i
] != 0)
1271 *(PULONG_PTR
)RemoteCaptureBuffer
->PointerOffsetsArray
[i
] -= BufferDistance
;
1272 RemoteCaptureBuffer
->PointerOffsetsArray
[i
] -= (ULONG_PTR
)ApiMessage
;
1276 /* Copy the data back */
1277 RtlMoveMemory(LocalCaptureBuffer
, RemoteCaptureBuffer
, RemoteCaptureBuffer
->Size
);
1279 /* Free our allocated buffer */
1280 RtlFreeHeap(CsrHeap
, 0, RemoteCaptureBuffer
);
1285 * @name CsrValidateMessageBuffer
1286 * @implemented NT5.1
1288 * The CsrValidateMessageBuffer routine validates a captured message buffer
1289 * present in the CSR Api Message
1292 * Pointer to the CSR API Message containing the CSR Capture Buffer.
1295 * Pointer to the message buffer to validate.
1297 * @param ElementCount
1298 * Number of elements contained in the message buffer.
1300 * @param ElementSize
1301 * Size of each element.
1303 * @return TRUE if validation suceeded, FALSE otherwise.
1310 CsrValidateMessageBuffer(IN PCSR_API_MESSAGE ApiMessage
,
1312 IN ULONG ElementCount
,
1313 IN ULONG ElementSize
)
1315 PCSR_CAPTURE_BUFFER CaptureBuffer
= ApiMessage
->CsrCaptureData
;
1316 // SIZE_T BufferDistance = (ULONG_PTR)Buffer - (ULONG_PTR)ApiMessage;
1320 * Check whether we have a valid buffer pointer, elements
1321 * of non-trivial size and that we don't overflow.
1323 if (!Buffer
|| ElementSize
== 0 ||
1324 (ULONGLONG
)ElementCount
* ElementSize
> (ULONGLONG
)0xFFFFFFFF)
1329 /* Check if didn't get a buffer and there aren't any arguments to check */
1330 // if (!*Buffer && (ElementCount * ElementSize == 0))
1331 if (!*Buffer
&& ElementCount
== 0) // Here ElementSize != 0 therefore only ElementCount can be == 0
1334 /* Check if we have no capture buffer */
1338 * In this case, check only the Process ID
1339 * and if there is a match, we succeed.
1341 if (NtCurrentTeb()->ClientId
.UniqueProcess
==
1342 ApiMessage
->Header
.ClientId
.UniqueProcess
)
1349 /* Make sure that there is still space left in the buffer */
1350 if ((CaptureBuffer
->Size
- (ULONG_PTR
)*Buffer
+ (ULONG_PTR
)CaptureBuffer
) >=
1351 (ElementCount
* ElementSize
))
1353 for (i
= 0 ; i
< CaptureBuffer
->PointerCount
; ++i
)
1356 * If the pointer offset is in fact equal to the
1357 * real address of the buffer then it's OK.
1359 if (CaptureBuffer
->PointerOffsetsArray
[i
] == (ULONG_PTR
)Buffer
/* BufferDistance + (ULONG_PTR)ApiMessage */)
1368 DPRINT1("CSRSRV: Bad message buffer %p\n", ApiMessage
);
1373 /*** This is what we have in consrv/server.c ***
1375 /\* Ensure that a captured buffer is safe to access *\/
1377 Win32CsrValidateBuffer(PCSR_PROCESS ProcessData, PVOID Buffer,
1378 SIZE_T NumElements, SIZE_T ElementSize)
1380 /\* Check that the following conditions are true:
1381 * 1. The start of the buffer is somewhere within the process's
1382 * shared memory section view.
1383 * 2. The remaining space in the view is at least as large as the buffer.
1384 * (NB: Please don't try to "optimize" this by using multiplication
1385 * instead of division; remember that 2147483648 * 2 = 0.)
1386 * 3. The buffer is DWORD-aligned.
1388 ULONG_PTR Offset = (BYTE *)Buffer - (BYTE *)ProcessData->ClientViewBase;
1389 if (Offset >= ProcessData->ClientViewBounds
1390 || NumElements > (ProcessData->ClientViewBounds - Offset) / ElementSize
1391 || (Offset & (sizeof(DWORD) - 1)) != 0)
1393 DPRINT1("Invalid buffer %p(%u*%u); section view is %p(%u)\n",
1394 Buffer, NumElements, ElementSize,
1395 ProcessData->ClientViewBase, ProcessData->ClientViewBounds);
1401 ***********************************************/
1404 * @name CsrValidateMessageString
1405 * @implemented NT5.1
1407 * The CsrValidateMessageString validates a captured Wide-Character String
1408 * present in a CSR API Message.
1411 * Pointer to the CSR API Message containing the CSR Capture Buffer.
1413 * @param MessageString
1414 * Pointer to the buffer containing the string to validate.
1416 * @return TRUE if validation suceeded, FALSE otherwise.
1423 CsrValidateMessageString(IN PCSR_API_MESSAGE ApiMessage
,
1424 IN LPWSTR
*MessageString
)
1428 return CsrValidateMessageBuffer(ApiMessage
,
1429 (PVOID
*)MessageString
,
1430 wcslen(*MessageString
) + 1,