d013e156b7cf918ca4d612b7390015636fd84609
[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 == CsrReplyAlreadyDone)
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*/);
923
924 /* Create the Port Object */
925 Status = NtCreatePort(&CsrApiPort,
926 &ObjectAttributes,
927 LPC_MAX_DATA_LENGTH, // HACK: the real value is: sizeof(CSR_CONNECTION_INFO),
928 LPC_MAX_MESSAGE_LENGTH, // HACK: the real value is: 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 i;
1129
1130 /* Use SEH to make sure this is valid */
1131 _SEH2_TRY
1132 {
1133 /* Get the buffer we got from whoever called NTDLL */
1134 LocalCaptureBuffer = ApiMessage->CsrCaptureData;
1135 Length = LocalCaptureBuffer->Size;
1136
1137 /* Now check if the buffer is inside our mapped section */
1138 if (((ULONG_PTR)LocalCaptureBuffer < CsrThread->Process->ClientViewBase) ||
1139 (((ULONG_PTR)LocalCaptureBuffer + Length) >= CsrThread->Process->ClientViewBounds))
1140 {
1141 /* Return failure */
1142 DPRINT1("*** CSRSS: CaptureBuffer outside of ClientView\n");
1143 ApiMessage->Status = STATUS_INVALID_PARAMETER;
1144 _SEH2_YIELD(return FALSE);
1145 }
1146
1147 /* Check if the Length is valid */
1148 if ((FIELD_OFFSET(CSR_CAPTURE_BUFFER, PointerOffsetsArray) +
1149 (LocalCaptureBuffer->PointerCount * sizeof(PVOID)) > Length) ||
1150 (Length > MAXWORD))
1151 {
1152 /* Return failure */
1153 DPRINT1("*** CSRSS: CaptureBuffer %p has bad length\n", LocalCaptureBuffer);
1154 DbgBreakPoint();
1155 ApiMessage->Status = STATUS_INVALID_PARAMETER;
1156 _SEH2_YIELD(return FALSE);
1157 }
1158 }
1159 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
1160 {
1161 /* Return failure */
1162 ApiMessage->Status = STATUS_INVALID_PARAMETER;
1163 _SEH2_YIELD(return FALSE);
1164 } _SEH2_END;
1165
1166 /* We validated the incoming buffer, now allocate the remote one */
1167 RemoteCaptureBuffer = RtlAllocateHeap(CsrHeap, 0, Length);
1168 if (!RemoteCaptureBuffer)
1169 {
1170 /* We're out of memory */
1171 ApiMessage->Status = STATUS_NO_MEMORY;
1172 return FALSE;
1173 }
1174
1175 /* Copy the client's buffer */
1176 RtlMoveMemory(RemoteCaptureBuffer, LocalCaptureBuffer, Length);
1177
1178 /* Calculate the difference between our buffer and the client's */
1179 BufferDistance = (ULONG_PTR)RemoteCaptureBuffer - (ULONG_PTR)LocalCaptureBuffer;
1180
1181 /*
1182 * All the pointer offsets correspond to pointers which point
1183 * to the remote data buffer instead of the local one.
1184 */
1185 for (i = 0 ; i < RemoteCaptureBuffer->PointerCount ; ++i)
1186 {
1187 if (RemoteCaptureBuffer->PointerOffsetsArray[i] != 0)
1188 {
1189 /* Temporarily transform the offset into a pointer */
1190 RemoteCaptureBuffer->PointerOffsetsArray[i] += (ULONG_PTR)ApiMessage;
1191
1192 /* Validate the bounds of the current pointed pointer */
1193 if ((*(PULONG_PTR)RemoteCaptureBuffer->PointerOffsetsArray[i] >= CsrThread->Process->ClientViewBase) &&
1194 (*(PULONG_PTR)RemoteCaptureBuffer->PointerOffsetsArray[i] < CsrThread->Process->ClientViewBounds))
1195 {
1196 /* Modify the pointed pointer to take into account its new position */
1197 *(PULONG_PTR)RemoteCaptureBuffer->PointerOffsetsArray[i] += BufferDistance;
1198 }
1199 else
1200 {
1201 /* Invalid pointer, fail */
1202 DPRINT1("*** CSRSS: CaptureBuffer MessagePointer outside of ClientView\n");
1203 DbgBreakPoint();
1204 ApiMessage->Status = STATUS_INVALID_PARAMETER;
1205 }
1206
1207 /* Transform back into an offset */
1208 RemoteCaptureBuffer->PointerOffsetsArray[i] -= (ULONG_PTR)ApiMessage;
1209 }
1210 }
1211
1212 /* Check if we got success */
1213 if (ApiMessage->Status != STATUS_SUCCESS)
1214 {
1215 /* Failure. Free the buffer and return */
1216 RtlFreeHeap(CsrHeap, 0, RemoteCaptureBuffer);
1217 return FALSE;
1218 }
1219 else
1220 {
1221 /* Success, save the previous buffer and use the remote capture buffer */
1222 RemoteCaptureBuffer->PreviousCaptureBuffer = LocalCaptureBuffer;
1223 ApiMessage->CsrCaptureData = RemoteCaptureBuffer;
1224 }
1225
1226 /* Success */
1227 return TRUE;
1228 }
1229
1230 /*++
1231 * @name CsrReleaseCapturedArguments
1232 * @implemented NT5.1
1233 *
1234 * The CsrReleaseCapturedArguments routine releases a Capture Buffer
1235 * that was previously captured with CsrCaptureArguments.
1236 *
1237 * @param ApiMessage
1238 * Pointer to the CSR API Message containing the Capture Buffer
1239 * that needs to be released.
1240 *
1241 * @return None.
1242 *
1243 * @remarks None.
1244 *
1245 *--*/
1246 VOID
1247 NTAPI
1248 CsrReleaseCapturedArguments(IN PCSR_API_MESSAGE ApiMessage)
1249 {
1250 PCSR_CAPTURE_BUFFER RemoteCaptureBuffer, LocalCaptureBuffer;
1251 SIZE_T BufferDistance;
1252 ULONG i;
1253
1254 /* Get the remote capture buffer */
1255 RemoteCaptureBuffer = ApiMessage->CsrCaptureData;
1256
1257 /* Do not continue if there is no captured buffer */
1258 if (!RemoteCaptureBuffer) return;
1259
1260 /* If there is one, get the corresponding local capture buffer */
1261 LocalCaptureBuffer = RemoteCaptureBuffer->PreviousCaptureBuffer;
1262
1263 /* Free the previous one and use again the local capture buffer */
1264 RemoteCaptureBuffer->PreviousCaptureBuffer = NULL;
1265 ApiMessage->CsrCaptureData = LocalCaptureBuffer;
1266
1267 /* Calculate the difference between our buffer and the client's */
1268 BufferDistance = (ULONG_PTR)RemoteCaptureBuffer - (ULONG_PTR)LocalCaptureBuffer;
1269
1270 /*
1271 * All the pointer offsets correspond to pointers which point
1272 * to the local data buffer instead of the remote one (revert
1273 * the logic of CsrCaptureArguments).
1274 */
1275 for (i = 0 ; i < RemoteCaptureBuffer->PointerCount ; ++i)
1276 {
1277 if (RemoteCaptureBuffer->PointerOffsetsArray[i] != 0)
1278 {
1279 /* Temporarily transform the offset into a pointer */
1280 RemoteCaptureBuffer->PointerOffsetsArray[i] += (ULONG_PTR)ApiMessage;
1281
1282 /* Modify the pointed pointer to take into account its new position */
1283 *(PULONG_PTR)RemoteCaptureBuffer->PointerOffsetsArray[i] -= BufferDistance;
1284
1285 /* Transform back into an offset */
1286 RemoteCaptureBuffer->PointerOffsetsArray[i] -= (ULONG_PTR)ApiMessage;
1287 }
1288 }
1289
1290 /* Copy the data back */
1291 RtlMoveMemory(LocalCaptureBuffer, RemoteCaptureBuffer, RemoteCaptureBuffer->Size);
1292
1293 /* Free our allocated buffer */
1294 RtlFreeHeap(CsrHeap, 0, RemoteCaptureBuffer);
1295 }
1296
1297
1298 /*++
1299 * @name CsrValidateMessageBuffer
1300 * @implemented NT5.1
1301 *
1302 * The CsrValidateMessageBuffer routine validates a captured message buffer
1303 * present in the CSR Api Message
1304 *
1305 * @param ApiMessage
1306 * Pointer to the CSR API Message containing the CSR Capture Buffer.
1307 *
1308 * @param Buffer
1309 * Pointer to the message buffer to validate.
1310 *
1311 * @param ElementCount
1312 * Number of elements contained in the message buffer.
1313 *
1314 * @param ElementSize
1315 * Size of each element.
1316 *
1317 * @return TRUE if validation suceeded, FALSE otherwise.
1318 *
1319 * @remarks None.
1320 *
1321 *--*/
1322 BOOLEAN
1323 NTAPI
1324 CsrValidateMessageBuffer(IN PCSR_API_MESSAGE ApiMessage,
1325 IN PVOID *Buffer,
1326 IN ULONG ElementCount,
1327 IN ULONG ElementSize)
1328 {
1329 PCSR_CAPTURE_BUFFER CaptureBuffer = ApiMessage->CsrCaptureData;
1330 SIZE_T BufferDistance = (ULONG_PTR)Buffer - (ULONG_PTR)ApiMessage;
1331 ULONG i;
1332
1333 /*
1334 * Check whether we have a valid buffer pointer, elements
1335 * of non-trivial size and that we don't overflow.
1336 */
1337 if (!Buffer || ElementSize == 0 ||
1338 (ULONGLONG)ElementCount * ElementSize > (ULONGLONG)0xFFFFFFFF)
1339 {
1340 return FALSE;
1341 }
1342
1343 /* Check if didn't get a buffer and there aren't any arguments to check */
1344 // if (!*Buffer && (ElementCount * ElementSize == 0))
1345 if (!*Buffer && ElementCount == 0) // Here ElementSize != 0 therefore only ElementCount can be == 0
1346 return TRUE;
1347
1348 /* Check if we have no capture buffer */
1349 if (!CaptureBuffer)
1350 {
1351 /*
1352 * In this case, check only the Process ID
1353 * and if there is a match, we succeed.
1354 */
1355 if (NtCurrentTeb()->ClientId.UniqueProcess ==
1356 ApiMessage->Header.ClientId.UniqueProcess)
1357 {
1358 return TRUE;
1359 }
1360 }
1361 else
1362 {
1363 /* Make sure that there is still space left in the buffer */
1364 if ((CaptureBuffer->Size - (ULONG_PTR)*Buffer + (ULONG_PTR)CaptureBuffer) >=
1365 (ElementCount * ElementSize))
1366 {
1367 for (i = 0 ; i < CaptureBuffer->PointerCount ; ++i)
1368 {
1369 /*
1370 * The pointer offset must be equal to the delta between
1371 * the addresses of the buffer and of the API message.
1372 */
1373 if (CaptureBuffer->PointerOffsetsArray[i] == BufferDistance)
1374 {
1375 return TRUE;
1376 }
1377 }
1378 }
1379 }
1380
1381 /* Failure */
1382 DPRINT1("CSRSRV: Bad message buffer %p\n", ApiMessage);
1383 DbgBreakPoint();
1384 return FALSE;
1385 }
1386
1387 /*** This is what we have in consrv/server.c ***
1388
1389 /\* Ensure that a captured buffer is safe to access *\/
1390 BOOL FASTCALL
1391 Win32CsrValidateBuffer(PCSR_PROCESS ProcessData, PVOID Buffer,
1392 SIZE_T NumElements, SIZE_T ElementSize)
1393 {
1394 /\* Check that the following conditions are true:
1395 * 1. The start of the buffer is somewhere within the process's
1396 * shared memory section view.
1397 * 2. The remaining space in the view is at least as large as the buffer.
1398 * (NB: Please don't try to "optimize" this by using multiplication
1399 * instead of division; remember that 2147483648 * 2 = 0.)
1400 * 3. The buffer is DWORD-aligned.
1401 *\/
1402 ULONG_PTR Offset = (BYTE *)Buffer - (BYTE *)ProcessData->ClientViewBase;
1403 if (Offset >= ProcessData->ClientViewBounds
1404 || NumElements > (ProcessData->ClientViewBounds - Offset) / ElementSize
1405 || (Offset & (sizeof(DWORD) - 1)) != 0)
1406 {
1407 DPRINT1("Invalid buffer %p(%u*%u); section view is %p(%u)\n",
1408 Buffer, NumElements, ElementSize,
1409 ProcessData->ClientViewBase, ProcessData->ClientViewBounds);
1410 return FALSE;
1411 }
1412 return TRUE;
1413 }
1414
1415 ***********************************************/
1416
1417 /*++
1418 * @name CsrValidateMessageString
1419 * @implemented NT5.1
1420 *
1421 * The CsrValidateMessageString validates a captured Wide-Character String
1422 * present in a CSR API Message.
1423 *
1424 * @param ApiMessage
1425 * Pointer to the CSR API Message containing the CSR Capture Buffer.
1426 *
1427 * @param MessageString
1428 * Pointer to the buffer containing the string to validate.
1429 *
1430 * @return TRUE if validation suceeded, FALSE otherwise.
1431 *
1432 * @remarks None.
1433 *
1434 *--*/
1435 BOOLEAN
1436 NTAPI
1437 CsrValidateMessageString(IN PCSR_API_MESSAGE ApiMessage,
1438 IN LPWSTR *MessageString)
1439 {
1440 if (MessageString)
1441 {
1442 return CsrValidateMessageBuffer(ApiMessage,
1443 (PVOID*)MessageString,
1444 wcslen(*MessageString) + 1,
1445 sizeof(WCHAR));
1446 }
1447 else
1448 {
1449 return FALSE;
1450 }
1451 }
1452
1453 /* EOF */