0aa184d4ad26003f5ba7e9261b2674d4f8624ca1
[reactos.git] / subsystems / win32 / csrsrv / api.c
1 /*
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)
8 */
9
10 /* INCLUDES *******************************************************************/
11
12 #include "srv.h"
13
14 //#define NDEBUG
15 #include <debug.h>
16
17 /* GLOBALS ********************************************************************/
18
19 BOOLEAN (*CsrClientThreadSetup)(VOID) = NULL;
20 UNICODE_STRING CsrApiPortName;
21 volatile LONG CsrpStaticThreadCount;
22 volatile LONG CsrpDynamicThreadTotal;
23 extern ULONG CsrMaxApiRequestThreads;
24
25 /* FUNCTIONS ******************************************************************/
26
27 /*++
28 * @name CsrCallServerFromServer
29 * @implemented NT4
30 *
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.
33 *
34 * @param ReceiveMsg
35 * Pointer to the CSR API Message to send to the server.
36 *
37 * @param ReplyMsg
38 * Pointer to the CSR API Message to receive from the server.
39 *
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.
43 *
44 * @remarks None.
45 *
46 *--*/
47 NTSTATUS
48 NTAPI
49 CsrCallServerFromServer(IN PCSR_API_MESSAGE ReceiveMsg,
50 IN OUT PCSR_API_MESSAGE ReplyMsg)
51 {
52 ULONG ServerId;
53 PCSR_SERVER_DLL ServerDll;
54 ULONG ApiId;
55 CSR_REPLY_CODE ReplyCode = CsrReplyImmediately;
56
57 /* Get the Server ID */
58 ServerId = CSR_API_NUMBER_TO_SERVER_ID(ReceiveMsg->ApiNumber);
59
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])))
63 {
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;
68 }
69 else
70 {
71 /* Get the API ID, normalized with our Base ID */
72 ApiId = CSR_API_NUMBER_TO_API_ID(ReceiveMsg->ApiNumber) - ServerDll->ApiBase;
73
74 /* Make sure that the ID is within limits, and the entry exists */
75 if ((ApiId >= ServerDll->HighestApiSupported) ||
76 ((ServerDll->ValidTable) && !(ServerDll->ValidTable[ApiId])))
77 {
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);
84 DbgBreakPoint();
85 ReplyMsg->Status = (ULONG)STATUS_ILLEGAL_FUNCTION;
86 return STATUS_ILLEGAL_FUNCTION;
87 }
88 }
89
90 if (CsrDebug & 2)
91 {
92 DPRINT1("CSRSS: %s Api Request received from server process\n",
93 ServerDll->NameTable[ApiId]);
94 }
95
96 /* Validation complete, start SEH */
97 _SEH2_TRY
98 {
99 /* Call the API, get the reply code and return the result */
100 ReplyMsg->Status = ServerDll->DispatchTable[ApiId](ReceiveMsg, &ReplyCode);
101 }
102 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
103 {
104 /* If we got an exception, return access violation */
105 ReplyMsg->Status = STATUS_ACCESS_VIOLATION;
106 }
107 _SEH2_END;
108
109 /* Return success */
110 return STATUS_SUCCESS;
111 }
112
113 /*++
114 * @name CsrApiHandleConnectionRequest
115 *
116 * The CsrApiHandleConnectionRequest routine handles and accepts a new
117 * connection request to the CSR API LPC Port.
118 *
119 * @param ApiMessage
120 * Pointer to the incoming CSR API Message which contains the
121 * connection request.
122 *
123 * @return STATUS_SUCCESS in case of success, or status code which caused
124 * the routine to error.
125 *
126 * @remarks This routine is responsible for attaching the Shared Section to
127 * new clients connecting to CSR.
128 *
129 *--*/
130 NTSTATUS
131 NTAPI
132 CsrApiHandleConnectionRequest(IN PCSR_API_MESSAGE ApiMessage)
133 {
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;
140 HANDLE ServerPort;
141
142 /* Acquire the Process Lock */
143 CsrAcquireProcessLock();
144
145 /* Lookup the CSR Thread */
146 CsrThread = CsrLocateThreadByClientId(NULL, &ApiMessage->Header.ClientId);
147
148 /* Check if we have a thread */
149 if (CsrThread)
150 {
151 /* Get the Process */
152 CsrProcess = CsrThread->Process;
153
154 /* Make sure we have a Process as well */
155 if (CsrProcess)
156 {
157 /* Reference the Process */
158 CsrLockedReferenceProcess(CsrThread->Process);
159
160 /* Release the lock */
161 CsrReleaseProcessLock();
162
163 /* Duplicate the Object Directory */
164 Status = NtDuplicateObject(NtCurrentProcess(),
165 CsrObjectDirectory,
166 CsrProcess->ProcessHandle,
167 &ConnectInfo->ObjectDirectory,
168 0,
169 0,
170 DUPLICATE_SAME_ACCESS |
171 DUPLICATE_SAME_ATTRIBUTES);
172
173 /* Acquire the lock */
174 CsrAcquireProcessLock();
175
176 /* Check for success */
177 if (NT_SUCCESS(Status))
178 {
179 /* Attach the Shared Section */
180 Status = CsrSrvAttachSharedSection(CsrProcess, ConnectInfo);
181
182 /* Check how this went */
183 if (NT_SUCCESS(Status)) AllowConnection = TRUE;
184 }
185
186 /* Dereference the project */
187 CsrLockedDereferenceProcess(CsrProcess);
188 }
189 }
190
191 /* Release the lock */
192 CsrReleaseProcessLock();
193
194 /* Setup the Port View Structure */
195 RemotePortView.Length = sizeof(REMOTE_PORT_VIEW);
196 RemotePortView.ViewSize = 0;
197 RemotePortView.ViewBase = NULL;
198
199 /* Save the Process ID */
200 ConnectInfo->ProcessId = NtCurrentTeb()->ClientId.UniqueProcess;
201
202 /* Accept the Connection */
203 Status = NtAcceptConnectPort(&ServerPort,
204 AllowConnection ? UlongToPtr(CsrProcess->SequenceNumber) : 0,
205 &ApiMessage->Header,
206 AllowConnection,
207 NULL,
208 &RemotePortView);
209 if (!NT_SUCCESS(Status))
210 {
211 DPRINT1("CSRSS: NtAcceptConnectPort - failed. Status == %X\n", Status);
212 }
213 else if (AllowConnection)
214 {
215 if (CsrDebug & 2)
216 {
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);
222 }
223
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);
229
230 /* Complete the connection */
231 Status = NtCompleteConnectPort(ServerPort);
232 if (!NT_SUCCESS(Status))
233 {
234 DPRINT1("CSRSS: NtCompleteConnectPort - failed. Status == %X\n", Status);
235 }
236 }
237 else
238 {
239 DPRINT1("CSRSS: Rejecting Connection Request from ClientId: %lx.%lx\n",
240 ApiMessage->Header.ClientId.UniqueProcess,
241 ApiMessage->Header.ClientId.UniqueThread);
242 }
243
244 /* Return status to caller */
245 return Status;
246 }
247
248 /*++
249 * @name CsrpCheckRequestThreads
250 *
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
253 * avoid starvation.
254 *
255 * @param None.
256 *
257 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
258 * if a new thread couldn't be created.
259 *
260 * @remarks None.
261 *
262 *--*/
263 NTSTATUS
264 NTAPI
265 CsrpCheckRequestThreads(VOID)
266 {
267 HANDLE hThread;
268 CLIENT_ID ClientId;
269 NTSTATUS Status;
270
271 /* Decrease the count, and see if we're out */
272 if (!(_InterlockedDecrement(&CsrpStaticThreadCount)))
273 {
274 /* Check if we've still got space for a Dynamic Thread */
275 if (CsrpDynamicThreadTotal < CsrMaxApiRequestThreads)
276 {
277 /* Create a new dynamic thread */
278 Status = RtlCreateUserThread(NtCurrentProcess(),
279 NULL,
280 TRUE,
281 0,
282 0,
283 0,
284 (PVOID)CsrApiRequestThread,
285 NULL,
286 &hThread,
287 &ClientId);
288 /* Check success */
289 if (NT_SUCCESS(Status))
290 {
291 /* Increase the thread counts */
292 _InterlockedIncrement(&CsrpStaticThreadCount);
293 _InterlockedIncrement(&CsrpDynamicThreadTotal);
294
295 /* Add a new server thread */
296 if (CsrAddStaticServerThread(hThread,
297 &ClientId,
298 CsrThreadIsServerThread))
299 {
300 /* Activate it */
301 NtResumeThread(hThread, NULL);
302 }
303 else
304 {
305 /* Failed to create a new static thread */
306 _InterlockedDecrement(&CsrpStaticThreadCount);
307 _InterlockedDecrement(&CsrpDynamicThreadTotal);
308
309 /* Terminate it */
310 DPRINT1("Failing\n");
311 NtTerminateThread(hThread, 0);
312 NtClose(hThread);
313
314 /* Return */
315 return STATUS_UNSUCCESSFUL;
316 }
317 }
318 }
319 }
320
321 /* Success */
322 return STATUS_SUCCESS;
323 }
324
325 /*++
326 * @name CsrApiRequestThread
327 *
328 * The CsrApiRequestThread routine handles incoming messages or connection
329 * requests on the CSR API LPC Port.
330 *
331 * @param Parameter
332 * System-default user-defined parameter. Unused.
333 *
334 * @return The thread exit code, if the thread is terminated.
335 *
336 * @remarks Before listening on the port, the routine will first attempt
337 * to connect to the user subsystem.
338 *
339 *--*/
340 NTSTATUS
341 NTAPI
342 CsrApiRequestThread(IN PVOID Parameter)
343 {
344 PTEB Teb = NtCurrentTeb();
345 LARGE_INTEGER TimeOut;
346 PCSR_THREAD CurrentThread, CsrThread;
347 NTSTATUS Status;
348 CSR_REPLY_CODE ReplyCode;
349 PCSR_API_MESSAGE ReplyMsg;
350 CSR_API_MESSAGE ReceiveMsg;
351 PCSR_PROCESS CsrProcess;
352 PHARDERROR_MSG HardErrorMsg;
353 PVOID PortContext;
354 PCSR_SERVER_DLL ServerDll;
355 PCLIENT_DIED_MSG ClientDiedMsg;
356 PDBGKM_MSG DebugMessage;
357 ULONG ServerId, ApiId, MessageType, i;
358 HANDLE ReplyPort;
359
360 /* Setup LPC loop port and message */
361 ReplyMsg = NULL;
362 ReplyPort = CsrApiPort;
363
364 /* Connect to user32 */
365 while (!CsrConnectToUser())
366 {
367 /* Set up the timeout for the connect (30 seconds) */
368 TimeOut.QuadPart = -30 * 1000 * 1000 * 10;
369
370 /* Keep trying until we get a response */
371 Teb->Win32ClientInfo[0] = 0;
372 NtDelayExecution(FALSE, &TimeOut);
373 }
374
375 /* Get our thread */
376 CurrentThread = Teb->CsrClientThread;
377
378 /* If we got an event... */
379 if (Parameter)
380 {
381 /* Set it, to let stuff waiting on us load */
382 Status = NtSetEvent((HANDLE)Parameter, NULL);
383 ASSERT(NT_SUCCESS(Status));
384
385 /* Increase the Thread Counts */
386 _InterlockedIncrement(&CsrpStaticThreadCount);
387 _InterlockedIncrement(&CsrpDynamicThreadTotal);
388 }
389
390 /* Now start the loop */
391 while (TRUE)
392 {
393 /* Make sure the real CID is set */
394 Teb->RealClientId = Teb->ClientId;
395
396 /* Debug check */
397 if (Teb->CountOfOwnedCriticalSections)
398 {
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);
403 DbgBreakPoint();
404 }
405
406 /* Wait for a message to come through */
407 Status = NtReplyWaitReceivePort(ReplyPort,
408 &PortContext,
409 &ReplyMsg->Header,
410 &ReceiveMsg.Header);
411
412 /* Check if we didn't get success */
413 if (Status != STATUS_SUCCESS)
414 {
415 /* Was it a failure or another success code? */
416 if (!NT_SUCCESS(Status))
417 {
418 /* Check for specific status cases */
419 if ((Status != STATUS_INVALID_CID) &&
420 (Status != STATUS_UNSUCCESSFUL) &&
421 ((Status == STATUS_INVALID_HANDLE) || (ReplyPort == CsrApiPort)))
422 {
423 /* Notify the debugger */
424 DPRINT1("CSRSS: ReceivePort failed - Status == %X\n", Status);
425 DPRINT1("CSRSS: ReplyPortHandle %lx CsrApiPort %lx\n", ReplyPort, CsrApiPort);
426 }
427
428 /* We failed big time, so start out fresh */
429 ReplyMsg = NULL;
430 ReplyPort = CsrApiPort;
431 continue;
432 }
433 else
434 {
435 /* A bizare "success" code, just try again */
436 DPRINT1("NtReplyWaitReceivePort returned \"success\" status 0x%x\n", Status);
437 continue;
438 }
439 }
440
441 /* Use whatever Client ID we got */
442 Teb->RealClientId = ReceiveMsg.Header.ClientId;
443
444 /* Get the Message Type */
445 MessageType = ReceiveMsg.Header.u2.s2.Type;
446
447 /* Handle connection requests */
448 if (MessageType == LPC_CONNECTION_REQUEST)
449 {
450 /* Handle the Connection Request */
451 CsrApiHandleConnectionRequest(&ReceiveMsg);
452
453 ReplyMsg = NULL;
454 ReplyPort = CsrApiPort;
455 continue;
456 }
457
458 /* It's some other kind of request. Get the lock for the lookup */
459 CsrAcquireProcessLock();
460
461 /* Now do the lookup to get the CSR_THREAD */
462 CsrThread = CsrLocateThreadByClientId(&CsrProcess,
463 &ReceiveMsg.Header.ClientId);
464
465 /* Did we find a thread? */
466 if (!CsrThread)
467 {
468 /* This wasn't a CSR Thread, release lock */
469 CsrReleaseProcessLock();
470
471 /* If this was an exception, handle it */
472 if (MessageType == LPC_EXCEPTION)
473 {
474 ReplyMsg = &ReceiveMsg;
475 ReplyPort = CsrApiPort;
476 ReplyMsg->Status = DBG_CONTINUE;
477 }
478 else if (MessageType == LPC_PORT_CLOSED ||
479 MessageType == LPC_CLIENT_DIED)
480 {
481 /* The Client or Port are gone, loop again */
482 ReplyMsg = NULL;
483 ReplyPort = CsrApiPort;
484 }
485 else if (MessageType == LPC_ERROR_EVENT)
486 {
487 /* If it's a hard error, handle this too */
488 HardErrorMsg = (PHARDERROR_MSG)&ReceiveMsg;
489
490 /* Default it to unhandled */
491 HardErrorMsg->Response = ResponseNotHandled;
492
493 /* Check if there are free api threads */
494 CsrpCheckRequestThreads();
495 if (CsrpStaticThreadCount)
496 {
497 /* Loop every Server DLL */
498 for (i = 0; i < CSR_SERVER_DLL_MAX; i++)
499 {
500 /* Get the Server DLL */
501 ServerDll = CsrLoadedServerDll[i];
502
503 /* Check if it's valid and if it has a Hard Error Callback */
504 if ((ServerDll) && (ServerDll->HardErrorCallback))
505 {
506 /* Call it */
507 ServerDll->HardErrorCallback(NULL /* == CsrThread */, HardErrorMsg);
508
509 /* If it's handled, get out of here */
510 if (HardErrorMsg->Response != ResponseNotHandled) break;
511 }
512 }
513 }
514
515 /* Increase the thread count */
516 _InterlockedIncrement(&CsrpStaticThreadCount);
517
518 /* If the response was 0xFFFFFFFF, we'll ignore it */
519 if (HardErrorMsg->Response == 0xFFFFFFFF)
520 {
521 ReplyMsg = NULL;
522 ReplyPort = CsrApiPort;
523 }
524 else
525 {
526 ReplyMsg = &ReceiveMsg;
527 ReplyPort = CsrApiPort;
528 }
529 }
530 else if (MessageType == LPC_REQUEST)
531 {
532 /* This is an API Message coming from a non-CSR Thread */
533 ReplyMsg = &ReceiveMsg;
534 ReplyPort = CsrApiPort;
535 ReplyMsg->Status = STATUS_ILLEGAL_FUNCTION;
536 }
537 else if (MessageType == LPC_DATAGRAM)
538 {
539 /* This is an API call, get the Server ID */
540 ServerId = CSR_API_NUMBER_TO_SERVER_ID(ReceiveMsg.ApiNumber);
541
542 /* Make sure that the ID is within limits, and the Server DLL loaded */
543 ServerDll = NULL;
544 if ((ServerId >= CSR_SERVER_DLL_MAX) ||
545 (!(ServerDll = CsrLoadedServerDll[ServerId])))
546 {
547 /* We are beyond the Maximum Server ID */
548 DPRINT1("CSRSS: %lx is invalid ServerDllIndex (%08x)\n",
549 ServerId, ServerDll);
550 DbgBreakPoint();
551
552 ReplyMsg = NULL;
553 ReplyPort = CsrApiPort;
554 continue;
555 }
556
557 /* Get the API ID, normalized with our Base ID */
558 ApiId = CSR_API_NUMBER_TO_API_ID(ReceiveMsg.ApiNumber) - ServerDll->ApiBase;
559
560 /* Make sure that the ID is within limits, and the entry exists */
561 if (ApiId >= ServerDll->HighestApiSupported)
562 {
563 /* We are beyond the Maximum API ID, or it doesn't exist */
564 DPRINT1("CSRSS: %lx is invalid ApiTableIndex for %Z\n",
565 CSR_API_NUMBER_TO_API_ID(ReceiveMsg.ApiNumber),
566 &ServerDll->Name);
567
568 ReplyPort = CsrApiPort;
569 ReplyMsg = NULL;
570 continue;
571 }
572
573 if (CsrDebug & 2)
574 {
575 DPRINT1("[%02x] CSRSS: [%02x,%02x] - %s Api called from %08x\n",
576 Teb->ClientId.UniqueThread,
577 ReceiveMsg.Header.ClientId.UniqueProcess,
578 ReceiveMsg.Header.ClientId.UniqueThread,
579 ServerDll->NameTable[ApiId],
580 NULL);
581 }
582
583 /* Assume success */
584 ReceiveMsg.Status = STATUS_SUCCESS;
585
586 /* Validation complete, start SEH */
587 _SEH2_TRY
588 {
589 /* Make sure we have enough threads */
590 CsrpCheckRequestThreads();
591
592 /* Call the API and get the reply code */
593 ReplyMsg = NULL;
594 ReplyPort = CsrApiPort;
595 ServerDll->DispatchTable[ApiId](&ReceiveMsg, &ReplyCode);
596
597 /* Increase the static thread count */
598 _InterlockedIncrement(&CsrpStaticThreadCount);
599 }
600 _SEH2_EXCEPT(CsrUnhandledExceptionFilter(_SEH2_GetExceptionInformation()))
601 {
602 ReplyMsg = NULL;
603 ReplyPort = CsrApiPort;
604 }
605 _SEH2_END;
606 }
607 else
608 {
609 /* Some other ignored message type */
610 ReplyMsg = NULL;
611 ReplyPort = CsrApiPort;
612 }
613
614 /* Keep going */
615 continue;
616 }
617
618 /* We have a valid thread, was this an LPC Request? */
619 if (MessageType != LPC_REQUEST)
620 {
621 /* It's not an API, check if the client died */
622 if (MessageType == LPC_CLIENT_DIED)
623 {
624 /* Get the information and check if it matches our thread */
625 ClientDiedMsg = (PCLIENT_DIED_MSG)&ReceiveMsg;
626 if (ClientDiedMsg->CreateTime.QuadPart == CsrThread->CreateTime.QuadPart)
627 {
628 /* Reference the thread */
629 CsrLockedReferenceThread(CsrThread);
630
631 /* Destroy the thread in the API Message */
632 CsrDestroyThread(&ReceiveMsg.Header.ClientId);
633
634 /* Check if the thread was actually ourselves */
635 if (CsrProcess->ThreadCount == 1)
636 {
637 /* Kill the process manually here */
638 CsrDestroyProcess(&CsrThread->ClientId, 0);
639 }
640
641 /* Remove our extra reference */
642 CsrLockedDereferenceThread(CsrThread);
643 }
644
645 /* Release the lock and keep looping */
646 CsrReleaseProcessLock();
647
648 ReplyMsg = NULL;
649 ReplyPort = CsrApiPort;
650 continue;
651 }
652
653 /* Reference the thread and release the lock */
654 CsrLockedReferenceThread(CsrThread);
655 CsrReleaseProcessLock();
656
657 /* Check if this was an exception */
658 if (MessageType == LPC_EXCEPTION)
659 {
660 /* Kill the process */
661 NtTerminateProcess(CsrProcess->ProcessHandle, STATUS_ABANDONED);
662
663 /* Destroy it from CSR */
664 CsrDestroyProcess(&ReceiveMsg.Header.ClientId, STATUS_ABANDONED);
665
666 /* Return a Debug Message */
667 DebugMessage = (PDBGKM_MSG)&ReceiveMsg;
668 DebugMessage->ReturnedStatus = DBG_CONTINUE;
669 ReplyMsg = &ReceiveMsg;
670 ReplyPort = CsrApiPort;
671
672 /* Remove our extra reference */
673 CsrDereferenceThread(CsrThread);
674 }
675 else if (MessageType == LPC_ERROR_EVENT)
676 {
677 /* If it's a hard error, handle this too */
678 HardErrorMsg = (PHARDERROR_MSG)&ReceiveMsg;
679
680 /* Default it to unhandled */
681 HardErrorMsg->Response = ResponseNotHandled;
682
683 /* Check if there are free api threads */
684 CsrpCheckRequestThreads();
685 if (CsrpStaticThreadCount)
686 {
687 /* Loop every Server DLL */
688 for (i = 0; i < CSR_SERVER_DLL_MAX; i++)
689 {
690 /* Get the Server DLL */
691 ServerDll = CsrLoadedServerDll[i];
692
693 /* Check if it's valid and if it has a Hard Error Callback */
694 if ((ServerDll) && (ServerDll->HardErrorCallback))
695 {
696 /* Call it */
697 ServerDll->HardErrorCallback(CsrThread, HardErrorMsg);
698
699 /* If it's handled, get out of here */
700 if (HardErrorMsg->Response != ResponseNotHandled) break;
701 }
702 }
703 }
704
705 /* Increase the thread count */
706 _InterlockedIncrement(&CsrpStaticThreadCount);
707
708 /* If the response was 0xFFFFFFFF, we'll ignore it */
709 if (HardErrorMsg->Response == 0xFFFFFFFF)
710 {
711 ReplyMsg = NULL;
712 ReplyPort = CsrApiPort;
713 }
714 else
715 {
716 CsrDereferenceThread(CsrThread);
717 ReplyMsg = &ReceiveMsg;
718 ReplyPort = CsrApiPort;
719 }
720 }
721 else
722 {
723 /* Something else */
724 CsrDereferenceThread(CsrThread);
725 ReplyMsg = NULL;
726 }
727
728 /* Keep looping */
729 continue;
730 }
731
732 /* We got an API Request */
733 CsrLockedReferenceThread(CsrThread);
734 CsrReleaseProcessLock();
735
736 /* This is an API call, get the Server ID */
737 ServerId = CSR_API_NUMBER_TO_SERVER_ID(ReceiveMsg.ApiNumber);
738
739 /* Make sure that the ID is within limits, and the Server DLL loaded */
740 ServerDll = NULL;
741 if ((ServerId >= CSR_SERVER_DLL_MAX) ||
742 (!(ServerDll = CsrLoadedServerDll[ServerId])))
743 {
744 /* We are beyond the Maximum Server ID */
745 DPRINT1("CSRSS: %lx is invalid ServerDllIndex (%08x)\n",
746 ServerId, ServerDll);
747 DbgBreakPoint();
748
749 ReplyPort = CsrApiPort;
750 ReplyMsg = &ReceiveMsg;
751 ReplyMsg->Status = STATUS_ILLEGAL_FUNCTION;
752 CsrDereferenceThread(CsrThread);
753 continue;
754 }
755
756 /* Get the API ID, normalized with our Base ID */
757 ApiId = CSR_API_NUMBER_TO_API_ID(ReceiveMsg.ApiNumber) - ServerDll->ApiBase;
758
759 /* Make sure that the ID is within limits, and the entry exists */
760 if (ApiId >= ServerDll->HighestApiSupported)
761 {
762 /* We are beyond the Maximum API ID, or it doesn't exist */
763 DPRINT1("CSRSS: %lx is invalid ApiTableIndex for %Z\n",
764 CSR_API_NUMBER_TO_API_ID(ReceiveMsg.ApiNumber),
765 &ServerDll->Name);
766
767 ReplyPort = CsrApiPort;
768 ReplyMsg = &ReceiveMsg;
769 ReplyMsg->Status = STATUS_ILLEGAL_FUNCTION;
770 CsrDereferenceThread(CsrThread);
771 continue;
772 }
773
774 if (CsrDebug & 2)
775 {
776 DPRINT1("[%02x] CSRSS: [%02x,%02x] - %s Api called from %08x\n",
777 Teb->ClientId.UniqueThread,
778 ReceiveMsg.Header.ClientId.UniqueProcess,
779 ReceiveMsg.Header.ClientId.UniqueThread,
780 ServerDll->NameTable[ApiId],
781 CsrThread);
782 }
783
784 /* Assume success */
785 ReplyMsg = &ReceiveMsg;
786 ReceiveMsg.Status = STATUS_SUCCESS;
787
788 /* Now we reply to a particular client */
789 ReplyPort = CsrThread->Process->ClientPort;
790
791 /* Check if there's a capture buffer */
792 if (ReceiveMsg.CsrCaptureData)
793 {
794 /* Capture the arguments */
795 if (!CsrCaptureArguments(CsrThread, &ReceiveMsg))
796 {
797 /* Ignore this message if we failed to get the arguments */
798 CsrDereferenceThread(CsrThread);
799 continue;
800 }
801 }
802
803 /* Validation complete, start SEH */
804 _SEH2_TRY
805 {
806 /* Make sure we have enough threads */
807 CsrpCheckRequestThreads();
808
809 Teb->CsrClientThread = CsrThread;
810
811 /* Call the API, get the reply code and return the result */
812 ReplyCode = CsrReplyImmediately;
813 ReplyMsg->Status = ServerDll->DispatchTable[ApiId](&ReceiveMsg, &ReplyCode);
814
815 /* Increase the static thread count */
816 _InterlockedIncrement(&CsrpStaticThreadCount);
817
818 Teb->CsrClientThread = CurrentThread;
819
820 if (ReplyCode == CsrReplyAlreadySent)
821 {
822 if (ReceiveMsg.CsrCaptureData)
823 {
824 CsrReleaseCapturedArguments(&ReceiveMsg);
825 }
826 ReplyMsg = NULL;
827 ReplyPort = CsrApiPort;
828 CsrDereferenceThread(CsrThread);
829 }
830 else if (ReplyCode == CsrReplyDeadClient)
831 {
832 /* Reply to the death message */
833 NtReplyPort(ReplyPort, &ReplyMsg->Header);
834
835 /* Reply back to the API port now */
836 ReplyMsg = NULL;
837 ReplyPort = CsrApiPort;
838
839 CsrDereferenceThread(CsrThread);
840 }
841 else if (ReplyCode == CsrReplyPending)
842 {
843 ReplyMsg = NULL;
844 ReplyPort = CsrApiPort;
845 }
846 else
847 {
848 if (ReceiveMsg.CsrCaptureData)
849 {
850 CsrReleaseCapturedArguments(&ReceiveMsg);
851 }
852 CsrDereferenceThread(CsrThread);
853 }
854 }
855 _SEH2_EXCEPT(CsrUnhandledExceptionFilter(_SEH2_GetExceptionInformation()))
856 {
857 ReplyMsg = NULL;
858 ReplyPort = CsrApiPort;
859 }
860 _SEH2_END;
861 }
862
863 /* We're out of the loop for some reason, terminate! */
864 NtTerminateThread(NtCurrentThread(), Status);
865 return Status;
866 }
867
868 /*++
869 * @name CsrApiPortInitialize
870 *
871 * The CsrApiPortInitialize routine initializes the LPC Port used for
872 * communications with the Client/Server Runtime (CSR) and initializes the
873 * static thread that will handle connection requests and APIs.
874 *
875 * @param None
876 *
877 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
878 * otherwise.
879 *
880 * @remarks None.
881 *
882 *--*/
883 NTSTATUS
884 NTAPI
885 CsrApiPortInitialize(VOID)
886 {
887 ULONG Size;
888 OBJECT_ATTRIBUTES ObjectAttributes;
889 NTSTATUS Status;
890 HANDLE hRequestEvent, hThread;
891 CLIENT_ID ClientId;
892 PLIST_ENTRY ListHead, NextEntry;
893 PCSR_THREAD ServerThread;
894
895 /* Calculate how much space we'll need for the Port Name */
896 Size = CsrDirectoryName.Length + sizeof(CSR_PORT_NAME) + sizeof(WCHAR);
897
898 /* Create the buffer for it */
899 CsrApiPortName.Buffer = RtlAllocateHeap(CsrHeap, 0, Size);
900 if (!CsrApiPortName.Buffer) return STATUS_NO_MEMORY;
901
902 /* Setup the rest of the empty string */
903 CsrApiPortName.Length = 0;
904 CsrApiPortName.MaximumLength = (USHORT)Size;
905 RtlAppendUnicodeStringToString(&CsrApiPortName, &CsrDirectoryName);
906 RtlAppendUnicodeToString(&CsrApiPortName, UNICODE_PATH_SEP);
907 RtlAppendUnicodeToString(&CsrApiPortName, CSR_PORT_NAME);
908 if (CsrDebug & 1)
909 {
910 DPRINT1("CSRSS: Creating %wZ port and associated threads\n", &CsrApiPortName);
911 DPRINT1("CSRSS: sizeof( CONNECTINFO ) == %ld sizeof( API_MSG ) == %ld\n",
912 sizeof(CSR_CONNECTION_INFO), sizeof(CSR_API_MESSAGE));
913 }
914
915 /* FIXME: Create a Security Descriptor */
916
917 /* Initialize the Attributes */
918 InitializeObjectAttributes(&ObjectAttributes,
919 &CsrApiPortName,
920 0,
921 NULL,
922 NULL /* FIXME: Use the Security Descriptor */);
923
924 /* Create the Port Object */
925 Status = NtCreatePort(&CsrApiPort,
926 &ObjectAttributes,
927 sizeof(CSR_CONNECTION_INFO),
928 sizeof(CSR_API_MESSAGE),
929 16 * PAGE_SIZE);
930 if (NT_SUCCESS(Status))
931 {
932 /* Create the event the Port Thread will use */
933 Status = NtCreateEvent(&hRequestEvent,
934 EVENT_ALL_ACCESS,
935 NULL,
936 SynchronizationEvent,
937 FALSE);
938 if (NT_SUCCESS(Status))
939 {
940 /* Create the Request Thread */
941 Status = RtlCreateUserThread(NtCurrentProcess(),
942 NULL,
943 TRUE,
944 0,
945 0,
946 0,
947 (PVOID)CsrApiRequestThread,
948 (PVOID)hRequestEvent,
949 &hThread,
950 &ClientId);
951 if (NT_SUCCESS(Status))
952 {
953 /* Add this as a static thread to CSRSRV */
954 CsrAddStaticServerThread(hThread, &ClientId, CsrThreadIsServerThread);
955
956 /* Get the Thread List Pointers */
957 ListHead = &CsrRootProcess->ThreadList;
958 NextEntry = ListHead->Flink;
959
960 /* Start looping the list */
961 while (NextEntry != ListHead)
962 {
963 /* Get the Thread */
964 ServerThread = CONTAINING_RECORD(NextEntry, CSR_THREAD, Link);
965
966 /* Start it up */
967 Status = NtResumeThread(ServerThread->ThreadHandle, NULL);
968
969 /* Is this a Server Thread? */
970 if (ServerThread->Flags & CsrThreadIsServerThread)
971 {
972 /* If so, then wait for it to initialize */
973 Status = NtWaitForSingleObject(hRequestEvent, FALSE, NULL);
974 ASSERT(NT_SUCCESS(Status));
975 }
976
977 /* Next thread */
978 NextEntry = NextEntry->Flink;
979 }
980
981 /* We don't need this anymore */
982 NtClose(hRequestEvent);
983 }
984 }
985 }
986
987 /* Return */
988 return Status;
989 }
990
991 /*++
992 * @name CsrConnectToUser
993 * @implemented NT4
994 *
995 * The CsrConnectToUser connects to the User subsystem.
996 *
997 * @param None
998 *
999 * @return A pointer to the CSR Thread
1000 *
1001 * @remarks None.
1002 *
1003 *--*/
1004 PCSR_THREAD
1005 NTAPI
1006 CsrConnectToUser(VOID)
1007 {
1008 #if 0 // This code is OK, however it is ClientThreadSetup which sucks.
1009 NTSTATUS Status;
1010 ANSI_STRING DllName;
1011 UNICODE_STRING TempName;
1012 HANDLE hUser32;
1013 STRING StartupName;
1014 PTEB Teb = NtCurrentTeb();
1015 PCSR_THREAD CsrThread;
1016 BOOLEAN Connected;
1017
1018 /* Check if we didn't already find it */
1019 if (!CsrClientThreadSetup)
1020 {
1021 /* Get the DLL Handle for user32.dll */
1022 RtlInitAnsiString(&DllName, "user32");
1023 RtlAnsiStringToUnicodeString(&TempName, &DllName, TRUE);
1024 Status = LdrGetDllHandle(NULL,
1025 NULL,
1026 &TempName,
1027 &hUser32);
1028 RtlFreeUnicodeString(&TempName);
1029
1030 /* If we got the handle, get the Client Thread Startup Entrypoint */
1031 if (NT_SUCCESS(Status))
1032 {
1033 RtlInitAnsiString(&StartupName,"ClientThreadSetup");
1034 Status = LdrGetProcedureAddress(hUser32,
1035 &StartupName,
1036 0,
1037 (PVOID)&CsrClientThreadSetup);
1038 }
1039 }
1040
1041 /* Connect to user32 */
1042 _SEH2_TRY
1043 {
1044 Connected = CsrClientThreadSetup();
1045 }
1046 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
1047 {
1048 Connected = FALSE;
1049 } _SEH2_END;
1050
1051 if (!Connected)
1052 {
1053 DPRINT1("CSRSS: CsrConnectToUser failed\n");
1054 return NULL;
1055 }
1056
1057 /* Save pointer to this thread in TEB */
1058 CsrAcquireProcessLock();
1059 CsrThread = CsrLocateThreadInProcess(NULL, &Teb->ClientId);
1060 CsrReleaseProcessLock();
1061 if (CsrThread) Teb->CsrClientThread = CsrThread;
1062
1063 /* Return it */
1064 return CsrThread;
1065
1066 #else
1067
1068 PTEB Teb = NtCurrentTeb();
1069 PCSR_THREAD CsrThread;
1070
1071 /* Save pointer to this thread in TEB */
1072 CsrThread = CsrLocateThreadInProcess(NULL, &Teb->ClientId);
1073 if (CsrThread) Teb->CsrClientThread = CsrThread;
1074
1075 /* Return it */
1076 return CsrThread;
1077 #endif
1078 }
1079
1080 /*++
1081 * @name CsrQueryApiPort
1082 * @implemented NT4
1083 *
1084 * The CsrQueryApiPort routine returns a handle to the CSR API LPC port.
1085 *
1086 * @param None.
1087 *
1088 * @return A handle to the port.
1089 *
1090 * @remarks None.
1091 *
1092 *--*/
1093 HANDLE
1094 NTAPI
1095 CsrQueryApiPort(VOID)
1096 {
1097 DPRINT("CSRSRV: %s called\n", __FUNCTION__);
1098 return CsrApiPort;
1099 }
1100
1101 /*++
1102 * @name CsrCaptureArguments
1103 * @implemented NT5.1
1104 *
1105 * The CsrCaptureArguments routine validates a CSR Capture Buffer and
1106 * re-captures it into a server CSR Capture Buffer.
1107 *
1108 * @param CsrThread
1109 * Pointer to the CSR Thread performing the validation.
1110 *
1111 * @param ApiMessage
1112 * Pointer to the CSR API Message containing the Capture Buffer
1113 * that needs to be validated.
1114 *
1115 * @return TRUE if validation succeeded, FALSE otherwise.
1116 *
1117 * @remarks None.
1118 *
1119 *--*/
1120 BOOLEAN
1121 NTAPI
1122 CsrCaptureArguments(IN PCSR_THREAD CsrThread,
1123 IN PCSR_API_MESSAGE ApiMessage)
1124 {
1125 PCSR_CAPTURE_BUFFER LocalCaptureBuffer = NULL, RemoteCaptureBuffer = NULL;
1126 SIZE_T BufferDistance;
1127 ULONG Length = 0;
1128 ULONG PointerCount;
1129 PULONG_PTR OffsetPointer;
1130 ULONG_PTR CurrentOffset;
1131
1132 /* Use SEH to make sure this is valid */
1133 _SEH2_TRY
1134 {
1135 /* Get the buffer we got from whoever called NTDLL */
1136 LocalCaptureBuffer = ApiMessage->CsrCaptureData;
1137 Length = LocalCaptureBuffer->Size;
1138
1139 /* Now check if the buffer is inside our mapped section */
1140 if (((ULONG_PTR)LocalCaptureBuffer < CsrThread->Process->ClientViewBase) ||
1141 (((ULONG_PTR)LocalCaptureBuffer + Length) >= CsrThread->Process->ClientViewBounds))
1142 {
1143 /* Return failure */
1144 DPRINT1("*** CSRSS: CaptureBuffer outside of ClientView\n");
1145 ApiMessage->Status = STATUS_INVALID_PARAMETER;
1146 _SEH2_YIELD(return FALSE);
1147 }
1148
1149 /* Check if the Length is valid */
1150 if ((FIELD_OFFSET(CSR_CAPTURE_BUFFER, PointerOffsetsArray) +
1151 (LocalCaptureBuffer->PointerCount * sizeof(PVOID)) > Length) ||
1152 (Length > MAXWORD))
1153 {
1154 /* Return failure */
1155 DPRINT1("*** CSRSS: CaptureBuffer %p has bad length\n", LocalCaptureBuffer);
1156 DbgBreakPoint();
1157 ApiMessage->Status = STATUS_INVALID_PARAMETER;
1158 _SEH2_YIELD(return FALSE);
1159 }
1160 }
1161 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
1162 {
1163 /* Return failure */
1164 ApiMessage->Status = STATUS_INVALID_PARAMETER;
1165 _SEH2_YIELD(return FALSE);
1166 } _SEH2_END;
1167
1168 /* We validated the incoming buffer, now allocate the remote one */
1169 RemoteCaptureBuffer = RtlAllocateHeap(CsrHeap, 0, Length);
1170 if (!RemoteCaptureBuffer)
1171 {
1172 /* We're out of memory */
1173 ApiMessage->Status = STATUS_NO_MEMORY;
1174 return FALSE;
1175 }
1176
1177 /* Copy the client's buffer */
1178 RtlMoveMemory(RemoteCaptureBuffer, LocalCaptureBuffer, Length);
1179
1180 /* Calculate the difference between our buffer and the client's */
1181 BufferDistance = (ULONG_PTR)RemoteCaptureBuffer - (ULONG_PTR)LocalCaptureBuffer;
1182
1183 /*
1184 * All the pointer offsets correspond to pointers which point
1185 * to the remote data buffer instead of the local one.
1186 */
1187 PointerCount = RemoteCaptureBuffer->PointerCount;
1188 OffsetPointer = RemoteCaptureBuffer->PointerOffsetsArray;
1189 while (PointerCount--)
1190 {
1191 CurrentOffset = *OffsetPointer;
1192
1193 if (CurrentOffset != 0)
1194 {
1195 /* Get the pointer corresponding to the offset */
1196 CurrentOffset += (ULONG_PTR)ApiMessage;
1197
1198 /* Validate the bounds of the current pointed pointer */
1199 if ((*(PULONG_PTR)CurrentOffset >= CsrThread->Process->ClientViewBase) &&
1200 (*(PULONG_PTR)CurrentOffset < CsrThread->Process->ClientViewBounds))
1201 {
1202 /* Modify the pointed pointer to take into account its new position */
1203 *(PULONG_PTR)CurrentOffset += BufferDistance;
1204 }
1205 else
1206 {
1207 /* Invalid pointer, fail */
1208 DPRINT1("*** CSRSS: CaptureBuffer MessagePointer outside of ClientView\n");
1209 DbgBreakPoint();
1210 ApiMessage->Status = STATUS_INVALID_PARAMETER;
1211 }
1212 }
1213
1214 ++OffsetPointer;
1215 }
1216
1217 /* Check if we got success */
1218 if (ApiMessage->Status != STATUS_SUCCESS)
1219 {
1220 /* Failure. Free the buffer and return */
1221 RtlFreeHeap(CsrHeap, 0, RemoteCaptureBuffer);
1222 return FALSE;
1223 }
1224 else
1225 {
1226 /* Success, save the previous buffer and use the remote capture buffer */
1227 RemoteCaptureBuffer->PreviousCaptureBuffer = LocalCaptureBuffer;
1228 ApiMessage->CsrCaptureData = RemoteCaptureBuffer;
1229 }
1230
1231 /* Success */
1232 return TRUE;
1233 }
1234
1235 /*++
1236 * @name CsrReleaseCapturedArguments
1237 * @implemented NT5.1
1238 *
1239 * The CsrReleaseCapturedArguments routine releases a Capture Buffer
1240 * that was previously captured with CsrCaptureArguments.
1241 *
1242 * @param ApiMessage
1243 * Pointer to the CSR API Message containing the Capture Buffer
1244 * that needs to be released.
1245 *
1246 * @return None.
1247 *
1248 * @remarks None.
1249 *
1250 *--*/
1251 VOID
1252 NTAPI
1253 CsrReleaseCapturedArguments(IN PCSR_API_MESSAGE ApiMessage)
1254 {
1255 PCSR_CAPTURE_BUFFER RemoteCaptureBuffer, LocalCaptureBuffer;
1256 SIZE_T BufferDistance;
1257 ULONG PointerCount;
1258 PULONG_PTR OffsetPointer;
1259 ULONG_PTR CurrentOffset;
1260
1261 /* Get the remote capture buffer */
1262 RemoteCaptureBuffer = ApiMessage->CsrCaptureData;
1263
1264 /* Do not continue if there is no captured buffer */
1265 if (!RemoteCaptureBuffer) return;
1266
1267 /* If there is one, get the corresponding local capture buffer */
1268 LocalCaptureBuffer = RemoteCaptureBuffer->PreviousCaptureBuffer;
1269
1270 /* Free the previous one and use again the local capture buffer */
1271 RemoteCaptureBuffer->PreviousCaptureBuffer = NULL;
1272 ApiMessage->CsrCaptureData = LocalCaptureBuffer;
1273
1274 /* Calculate the difference between our buffer and the client's */
1275 BufferDistance = (ULONG_PTR)RemoteCaptureBuffer - (ULONG_PTR)LocalCaptureBuffer;
1276
1277 /*
1278 * All the pointer offsets correspond to pointers which point
1279 * to the local data buffer instead of the remote one (revert
1280 * the logic of CsrCaptureArguments).
1281 */
1282 PointerCount = RemoteCaptureBuffer->PointerCount;
1283 OffsetPointer = RemoteCaptureBuffer->PointerOffsetsArray;
1284 while (PointerCount--)
1285 {
1286 CurrentOffset = *OffsetPointer;
1287
1288 if (CurrentOffset != 0)
1289 {
1290 /* Get the pointer corresponding to the offset */
1291 CurrentOffset += (ULONG_PTR)ApiMessage;
1292
1293 /* Modify the pointed pointer to take into account its new position */
1294 *(PULONG_PTR)CurrentOffset -= BufferDistance;
1295 }
1296
1297 ++OffsetPointer;
1298 }
1299
1300 /* Copy the data back */
1301 RtlMoveMemory(LocalCaptureBuffer, RemoteCaptureBuffer, RemoteCaptureBuffer->Size);
1302
1303 /* Free our allocated buffer */
1304 RtlFreeHeap(CsrHeap, 0, RemoteCaptureBuffer);
1305 }
1306
1307
1308 /*++
1309 * @name CsrValidateMessageBuffer
1310 * @implemented NT5.1
1311 *
1312 * The CsrValidateMessageBuffer routine validates a captured message buffer
1313 * present in the CSR Api Message
1314 *
1315 * @param ApiMessage
1316 * Pointer to the CSR API Message containing the CSR Capture Buffer.
1317 *
1318 * @param Buffer
1319 * Pointer to the message buffer to validate.
1320 *
1321 * @param ElementCount
1322 * Number of elements contained in the message buffer.
1323 *
1324 * @param ElementSize
1325 * Size of each element.
1326 *
1327 * @return TRUE if validation suceeded, FALSE otherwise.
1328 *
1329 * @remarks None.
1330 *
1331 *--*/
1332 BOOLEAN
1333 NTAPI
1334 CsrValidateMessageBuffer(IN PCSR_API_MESSAGE ApiMessage,
1335 IN PVOID *Buffer,
1336 IN ULONG ElementCount,
1337 IN ULONG ElementSize)
1338 {
1339 PCSR_CAPTURE_BUFFER CaptureBuffer = ApiMessage->CsrCaptureData;
1340 SIZE_T BufferDistance = (ULONG_PTR)Buffer - (ULONG_PTR)ApiMessage;
1341 ULONG PointerCount;
1342 PULONG_PTR OffsetPointer;
1343
1344 /*
1345 * Check whether we have a valid buffer pointer, elements
1346 * of non-trivial size and that we don't overflow.
1347 */
1348 if (!Buffer || ElementSize == 0 ||
1349 (ULONGLONG)ElementCount * ElementSize > (ULONGLONG)0xFFFFFFFF)
1350 {
1351 return FALSE;
1352 }
1353
1354 /* Check if didn't get a buffer and there aren't any arguments to check */
1355 // if (!*Buffer && (ElementCount * ElementSize == 0))
1356 if (!*Buffer && ElementCount == 0) // Here ElementSize != 0 therefore only ElementCount can be == 0
1357 return TRUE;
1358
1359 /* Check if we have no capture buffer */
1360 if (!CaptureBuffer)
1361 {
1362 /*
1363 * In this case, check only the Process ID
1364 * and if there is a match, we succeed.
1365 */
1366 if (NtCurrentTeb()->ClientId.UniqueProcess ==
1367 ApiMessage->Header.ClientId.UniqueProcess)
1368 {
1369 return TRUE;
1370 }
1371 }
1372 else
1373 {
1374 /* Make sure that there is still space left in the buffer */
1375 if ((CaptureBuffer->Size - (ULONG_PTR)*Buffer + (ULONG_PTR)CaptureBuffer) >=
1376 (ElementCount * ElementSize))
1377 {
1378 /* Perform the validation test */
1379 PointerCount = CaptureBuffer->PointerCount;
1380 OffsetPointer = CaptureBuffer->PointerOffsetsArray;
1381 while (PointerCount--)
1382 {
1383 /*
1384 * The pointer offset must be equal to the delta between
1385 * the addresses of the buffer and of the API message.
1386 */
1387 if (*OffsetPointer == BufferDistance)
1388 {
1389 return TRUE;
1390 }
1391 ++OffsetPointer;
1392 }
1393 }
1394 }
1395
1396 /* Failure */
1397 DPRINT1("CSRSRV: Bad message buffer %p\n", ApiMessage);
1398 DbgBreakPoint();
1399 return FALSE;
1400 }
1401
1402 /*** This is what we have in consrv/server.c ***
1403
1404 /\* Ensure that a captured buffer is safe to access *\/
1405 BOOL FASTCALL
1406 Win32CsrValidateBuffer(PCSR_PROCESS ProcessData, PVOID Buffer,
1407 SIZE_T NumElements, SIZE_T ElementSize)
1408 {
1409 /\* Check that the following conditions are true:
1410 * 1. The start of the buffer is somewhere within the process's
1411 * shared memory section view.
1412 * 2. The remaining space in the view is at least as large as the buffer.
1413 * (NB: Please don't try to "optimize" this by using multiplication
1414 * instead of division; remember that 2147483648 * 2 = 0.)
1415 * 3. The buffer is DWORD-aligned.
1416 *\/
1417 ULONG_PTR Offset = (BYTE *)Buffer - (BYTE *)ProcessData->ClientViewBase;
1418 if (Offset >= ProcessData->ClientViewBounds
1419 || NumElements > (ProcessData->ClientViewBounds - Offset) / ElementSize
1420 || (Offset & (sizeof(DWORD) - 1)) != 0)
1421 {
1422 DPRINT1("Invalid buffer %p(%u*%u); section view is %p(%u)\n",
1423 Buffer, NumElements, ElementSize,
1424 ProcessData->ClientViewBase, ProcessData->ClientViewBounds);
1425 return FALSE;
1426 }
1427 return TRUE;
1428 }
1429
1430 ***********************************************/
1431
1432 /*++
1433 * @name CsrValidateMessageString
1434 * @implemented NT5.1
1435 *
1436 * The CsrValidateMessageString validates a captured Wide-Character String
1437 * present in a CSR API Message.
1438 *
1439 * @param ApiMessage
1440 * Pointer to the CSR API Message containing the CSR Capture Buffer.
1441 *
1442 * @param MessageString
1443 * Pointer to the buffer containing the string to validate.
1444 *
1445 * @return TRUE if validation suceeded, FALSE otherwise.
1446 *
1447 * @remarks None.
1448 *
1449 *--*/
1450 BOOLEAN
1451 NTAPI
1452 CsrValidateMessageString(IN PCSR_API_MESSAGE ApiMessage,
1453 IN LPWSTR *MessageString)
1454 {
1455 if (MessageString)
1456 {
1457 return CsrValidateMessageBuffer(ApiMessage,
1458 (PVOID*)MessageString,
1459 wcslen(*MessageString) + 1,
1460 sizeof(WCHAR));
1461 }
1462 else
1463 {
1464 return FALSE;
1465 }
1466 }
1467
1468 /* EOF */