Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2050 lines
54 KiB

  1. /*++
  2. Copyright (c) 1999-2000 Microsoft Corporation
  3. Module Name :
  4. session.cpp
  5. Abstract:
  6. Session object is created to handle redirection for this session
  7. Revision History:
  8. --*/
  9. #include "precomp.hxx"
  10. #define TRC_FILE "session"
  11. #include "trc.h"
  12. typedef enum {
  13. scidServerAnnounce,
  14. scidClientConfirm,
  15. scidDeviceReply,
  16. scidIoRequest
  17. } DrSessionCallbackId;
  18. DrSession::DrSession() :
  19. _ChannelDeletionEvent(NotificationEvent, FALSE)
  20. {
  21. BEGIN_FN("DrSession::DrSession");
  22. TRC_NRM((TB, "Session Class=%p", this));
  23. SetClassName("DrSession");
  24. _crefs = 0;
  25. SetSessionState(csExpired);
  26. _ConnectCount = 0;
  27. _ChannelBuffer = NULL;
  28. _ChannelBufferSize = 0;
  29. _PartialPacketData = 0;
  30. _Initialized = FALSE;
  31. _ClientDisplayName[0] = L'\0';
  32. //
  33. // Initialize the server capability set
  34. // This is the capability set that we'll send to client
  35. //
  36. memcpy(&_SrvCapabilitySet, &SERVER_CAPABILITY_SET_DEFAULT,
  37. sizeof(SERVER_CAPABILITY_SET_DEFAULT));
  38. //
  39. // Initialize the client capability set
  40. // Once we receive the client side capability, we'll combine with our local
  41. // capability and stores it.
  42. //
  43. memcpy(&_CliCapabilitySet, &CLIENT_CAPABILITY_SET_DEFAULT,
  44. sizeof(CLIENT_CAPABILITY_SET_DEFAULT));
  45. #if DBG
  46. _BufCount = 1;
  47. _ApcCount = 0;
  48. _ApcChannelRef = 0;
  49. #endif
  50. }
  51. BOOL DrSession::Initialize()
  52. {
  53. BOOL Registered = FALSE;
  54. BOOL ExchangeInitialized = FALSE;
  55. BOOL DeviceManagerInitialized = FALSE;
  56. BEGIN_FN("DrSession::Initialize");
  57. if (!_Initialized) {
  58. Registered = !NT_ERROR(RegisterPacketReceiver(this));
  59. if (Registered) {
  60. TRC_DBG((TB, "Initilazing ExchangeManager"));
  61. ExchangeInitialized = _ExchangeManager.Initialize(this);
  62. }
  63. if (ExchangeInitialized) {
  64. TRC_DBG((TB, "Initilazing DeviceManager"));
  65. DeviceManagerInitialized = _DeviceManager.Initialize(this);
  66. }
  67. if (DeviceManagerInitialized) {
  68. TRC_DBG((TB, "Allocating Channel buffer"));
  69. _ChannelBuffer = new UCHAR[CHANNEL_CHUNK_LENGTH];
  70. }
  71. if (_ChannelBuffer != NULL) {
  72. TRC_DBG((TB, "Allocated default channel buffer=%p", _ChannelBuffer));
  73. _ChannelBufferSize = CHANNEL_CHUNK_LENGTH;
  74. _Initialized = TRUE;
  75. } else {
  76. //
  77. // Error Path, tear down initialization steps
  78. //
  79. if (DeviceManagerInitialized) {
  80. TRC_ERR((TB, "Failed to allocate default channel buffer"));
  81. _DeviceManager.Uninitialize();
  82. }
  83. if (ExchangeInitialized) {
  84. TRC_ALT((TB, "Tearing down ExchangeManager"));
  85. _ExchangeManager.Uninitialize();
  86. }
  87. if (Registered) {
  88. TRC_ALT((TB, "Unregistering for packets"));
  89. RemovePacketReceiver(this);
  90. }
  91. }
  92. }
  93. return _Initialized;
  94. }
  95. DrSession::~DrSession()
  96. {
  97. BEGIN_FN("DrSession::~DrSession");
  98. ASSERT(_crefs == 0);
  99. TRC_NRM((TB, "Session is deleted=%p", this));
  100. if (_ChannelBuffer) {
  101. delete _ChannelBuffer;
  102. _ChannelBuffer = NULL;
  103. }
  104. }
  105. #if DBG
  106. VOID DrSession::DumpUserConfigSettings()
  107. {
  108. BEGIN_FN("DrSession::DumpUserConfigSettings");
  109. TRC_NRM((TB, "Automatically map client drives: %s",
  110. _AutoClientDrives ? "True" : "False"));
  111. TRC_NRM((TB, "Automatically map client printers: %s",
  112. _AutoClientLpts ? "True" : "False"));
  113. TRC_NRM((TB, "Force client printer as default: %s",
  114. _ForceClientLptDef ? "True" : "False"));
  115. TRC_NRM((TB, "Disable client printer mapping: %s",
  116. _DisableCpm ? "True" : "False"));
  117. TRC_NRM((TB, "Disable client drive mapping: %s",
  118. _DisableCdm ? "True" : "False"));
  119. TRC_NRM((TB, "Disable client COM port mapping: %s",
  120. _DisableCcm ? "True" : "False"));
  121. TRC_NRM((TB, "Disable client printer mapping: %s",
  122. _DisableLPT ? "True" : "False"));
  123. TRC_NRM((TB, "Disable clipboard redirection: %s",
  124. _DisableClip ? "True" : "False"));
  125. TRC_NRM((TB, "DisableExe: %s",
  126. _DisableExe ? "True" : "False"));
  127. TRC_NRM((TB, "Disable client audio mapping: %s",
  128. _DisableCam ? "True" : "False"));
  129. }
  130. #endif // DBG
  131. void DrSession::Release(void)
  132. {
  133. BEGIN_FN("DrSession::Release");
  134. ULONG crefs;
  135. ASSERT(_crefs > 0);
  136. ASSERT(Sessions != NULL);
  137. Sessions->LockExclusive();
  138. if ((crefs = InterlockedDecrement(&_crefs)) == 0)
  139. {
  140. TRC_DBG((TB, "Deleting object type %s",
  141. _ClassName));
  142. if (_Initialized) {
  143. Sessions->Remove(this);
  144. }
  145. Sessions->Unlock();
  146. delete this;
  147. } else {
  148. TRC_DBG((TB, "Releasing object type %s to %d",
  149. _ClassName, crefs));
  150. ASSERT(_Initialized);
  151. Sessions->Unlock();
  152. }
  153. }
  154. BOOL DrSession::Connect(PCHANNEL_CONNECT_IN ConnectIn,
  155. PCHANNEL_CONNECT_OUT ConnectOut)
  156. {
  157. ULONG i;
  158. SmartPtr<VirtualChannel> Channel = NULL;
  159. BOOL ExchangeManagerStarted = FALSE;
  160. NTSTATUS Status;
  161. PCHANNEL_CONNECT_DEF Channels;
  162. BEGIN_FN("DrSession::Connect");
  163. _ConnectNotificationLock.AcquireResourceExclusive();
  164. if (InterlockedCompareExchange(&_ConnectCount, 1, 0) != 0) {
  165. TRC_ALT((TB, "RDPDR connect reentry called"));
  166. ASSERT(FALSE);
  167. _ConnectNotificationLock.ReleaseResource();
  168. return FALSE;
  169. }
  170. //ASSERT(_ApcChannelRef == 0);
  171. ASSERT(GetState() == csExpired);
  172. //
  173. // Need granular locking on notifying RDPDYN so we don't deadlock.
  174. //
  175. LockRDPDYNConnectStateChange();
  176. //
  177. // Tell RDPDYN about the new session.
  178. //
  179. RDPDYN_SessionConnected(ConnectIn->hdr.sessionID);
  180. UnlockRDPDYNConnectStateChange();
  181. //
  182. // Clear the channel event
  183. //
  184. _ChannelDeletionEvent.ResetEvent();
  185. //
  186. // Save all the user settings, we may need them later.
  187. // This is conceptually "wasteful" because we don't care
  188. // about some of them. But some may be supported in the
  189. // the future, and the size is padded out to a ULONG anyway
  190. //
  191. _SessionId = ConnectIn->hdr.sessionID;
  192. _AutoClientDrives = ConnectIn->fAutoClientDrives;
  193. _AutoClientLpts = ConnectIn->fAutoClientLpts;
  194. _ForceClientLptDef = ConnectIn->fForceClientLptDef;
  195. _DisableCpm = ConnectIn->fDisableCpm;
  196. _DisableCdm = ConnectIn->fDisableCdm;
  197. _DisableCcm = ConnectIn->fDisableCcm;
  198. _DisableLPT = ConnectIn->fDisableLPT;
  199. _DisableClip = ConnectIn->fDisableClip;
  200. _DisableExe = ConnectIn->fDisableExe;
  201. _DisableCam = ConnectIn->fDisableCam;
  202. _ClientId = 0xFFFFFFFF;
  203. #if DBG
  204. DumpUserConfigSettings();
  205. #endif // DBG
  206. //
  207. // Is our channel name in the list of channels on which the client is
  208. // prepared to communicate?
  209. //
  210. if (!FindChannelFromConnectIn(&i, ConnectIn)) {
  211. TRC_ALT((TB, "Undoctored client"));
  212. Status = STATUS_UNSUCCESSFUL;
  213. }
  214. else {
  215. Status = STATUS_SUCCESS;
  216. }
  217. if (NT_SUCCESS(Status)) {
  218. ExchangeManagerStarted = _ExchangeManager.Start();
  219. }
  220. if (ExchangeManagerStarted) {
  221. Status = STATUS_SUCCESS;
  222. } else {
  223. Status = STATUS_UNSUCCESSFUL;
  224. }
  225. if (NT_SUCCESS(Status)) {
  226. Channel = new(NonPagedPool) VirtualChannel;
  227. if (Channel != NULL) {
  228. Channels = (PCHANNEL_CONNECT_DEF)(ConnectIn + 1);
  229. if (Channel->Create(ConnectIn->hdr.IcaHandle,
  230. ConnectIn->hdr.sessionID, Channels[i].ID,
  231. _ChannelDeletionEvent.GetEvent())) {
  232. TRC_NRM((TB, "Channel opened for session %d",
  233. ConnectIn->hdr.sessionID));
  234. Status = STATUS_SUCCESS;
  235. } else {
  236. TRC_ALT((TB, "Channel not opened for session %d",
  237. ConnectIn->hdr.sessionID));
  238. Status = STATUS_UNSUCCESSFUL;
  239. }
  240. }
  241. }
  242. TRC_NRM((TB, "Channel open result: %lx", Status));
  243. if (NT_SUCCESS(Status)) {
  244. _Channel = Channel;
  245. //
  246. // Send a server announce
  247. //
  248. Status = ServerAnnounceWrite();
  249. if (Status == STATUS_PENDING) {
  250. Status = STATUS_SUCCESS;
  251. }
  252. if (!NT_SUCCESS(Status)) {
  253. TRC_ERR((TB, "DrServerAnnounceWrite returned error: "
  254. "%lx", Status));
  255. }
  256. }
  257. if (NT_SUCCESS(Status)) {
  258. SetSessionState(csPendingClientConfirm);
  259. //
  260. // Start Reading.
  261. //
  262. ReadPacket();
  263. }
  264. if (NT_SUCCESS(Status)) {
  265. //
  266. // Release the Notification resource
  267. //
  268. _ConnectNotificationLock.ReleaseResource();
  269. } else {
  270. TRC_ALT((TB, "Cleaning up DrOnSession create work due "
  271. "to error condition: %lx.", Status));
  272. //
  273. // Since we just Closed the channel, NULL out the handle
  274. // to it before deleting the client entry
  275. //
  276. if (Channel != NULL) {
  277. Channel = NULL;
  278. DeleteChannel(TRUE);
  279. }
  280. if (ExchangeManagerStarted) {
  281. _ExchangeManager.Stop();
  282. }
  283. //
  284. // Need granular locking on notifying RDPDYN so we don't deadlock.
  285. //
  286. LockRDPDYNConnectStateChange();
  287. SetSessionState(csExpired);
  288. // Notify RDPDYN about the session terminating.
  289. // We won't do this later because we're not making this a
  290. // doctored session after all, so we need this to
  291. // properly frame this from an RDPDYN perspective
  292. RDPDYN_SessionDisconnected(ConnectIn->hdr.sessionID);
  293. UnlockRDPDYNConnectStateChange();
  294. LONG Count = InterlockedCompareExchange(&_ConnectCount, 0, 1);
  295. ASSERT(Count == 1);
  296. //
  297. // Release the resource and dereference the client entry.
  298. //
  299. _ConnectNotificationLock.ReleaseResource();
  300. }
  301. return NT_SUCCESS(Status);
  302. }
  303. VOID DrSession::Disconnect(PCHANNEL_DISCONNECT_IN DisconnectIn,
  304. PCHANNEL_DISCONNECT_OUT DisconnectOut)
  305. {
  306. BEGIN_FN("DrSession::Disconnect");
  307. //
  308. // Ensure synchronization of notification
  309. //
  310. _ConnectNotificationLock.AcquireResourceExclusive();
  311. //
  312. // Delete our reference to the channel handle and close it
  313. //
  314. DeleteChannel(TRUE);
  315. //
  316. // Enumerate the atlas entries and cancel the I/O
  317. //
  318. _ExchangeManager.Stop();
  319. //
  320. // Enumerate the devices and mark them disconnected
  321. //
  322. _DeviceManager.Disconnect();
  323. //
  324. // Need granular locking on notifying RDPDYN so we don't deadlock.
  325. //
  326. LockRDPDYNConnectStateChange();
  327. //
  328. // Notify RDPDYN about the session terminating.
  329. // This function is called when an existing session is disconnected.
  330. ASSERT(_SessionId == DisconnectIn->hdr.sessionID);
  331. RDPDYN_SessionDisconnected(DisconnectIn->hdr.sessionID);
  332. //
  333. // Avoid creating additional references which would only lead to
  334. // disappointing results. DrOnSessionDisconnect sets this to
  335. // csDisconnected, so we have to be after that
  336. //
  337. SetSessionState(csExpired);
  338. UnlockRDPDYNConnectStateChange();
  339. TRC_NRM((TB, "Session: %d is disconnected", _SessionId));
  340. LONG Count = InterlockedCompareExchange(&_ConnectCount, 0, 1);
  341. ASSERT(Count == 1);
  342. //
  343. // Release the resource before we dereference (and potentially
  344. // delete) the ClientEntry
  345. //
  346. _ConnectNotificationLock.ReleaseResource();
  347. }
  348. BOOL DrSession::FindChannelFromConnectIn(PULONG ChannelId,
  349. PCHANNEL_CONNECT_IN ConnectIn)
  350. /*++
  351. Routine Description:
  352. Finds the appropriate channel id given a ConnectIn structure
  353. Arguments:
  354. ChannelId - Where to put the channel if it is found
  355. Return Value:
  356. Whether the channel was found
  357. --*/
  358. {
  359. ANSI_STRING DrChannelName;
  360. ANSI_STRING ChannelSearch;
  361. PCHANNEL_CONNECT_DEF Channels = (PCHANNEL_CONNECT_DEF)(ConnectIn + 1);
  362. BEGIN_FN("DrSession::FindChannelFromConnectIn");
  363. TRC_NRM((TB, "%ld Channels", ConnectIn->channelCount));
  364. RtlInitString(&DrChannelName, DR_CHANNEL_NAME);
  365. for (*ChannelId = 0; *ChannelId < ConnectIn->channelCount; *ChannelId++) {
  366. Channels[*ChannelId].name[CHANNEL_NAME_LEN] = 0;
  367. RtlInitString(&ChannelSearch, Channels[*ChannelId].name);
  368. TRC_DBG((TB, "Found channel %wZ", &ChannelSearch));
  369. if (RtlEqualString(&DrChannelName, &ChannelSearch, TRUE))
  370. break;
  371. }
  372. return (*ChannelId != ConnectIn->channelCount);
  373. }
  374. VOID DrSession::DeleteChannel(BOOL bWait)
  375. /*++
  376. Routine Description:
  377. Safely removes the Channel from the session and ditches the reference
  378. Arguments:
  379. ClientEntry - The relevant client entry
  380. Return Value:
  381. None
  382. Notes:
  383. --*/
  384. {
  385. SmartPtr<VirtualChannel> Channel;
  386. BEGIN_FN("DrSession::DeleteChannel");
  387. DrAcquireSpinLock();
  388. Channel = _Channel;
  389. _Channel = NULL;
  390. DrReleaseSpinLock();
  391. if (Channel != NULL) {
  392. //
  393. // Do the ZwClose on it so all I/O will be cancelled
  394. //
  395. Channel->SubmitClose();
  396. //
  397. // Remove our reference to it so it can go to zero
  398. //
  399. Channel = NULL;
  400. }
  401. if (bWait) {
  402. //
  403. // Wait for all of our Irps to finish.
  404. //
  405. #if DBG
  406. LARGE_INTEGER Timeout;
  407. NTSTATUS Status;
  408. KeQuerySystemTime(&Timeout);
  409. Timeout.QuadPart += 6000000000; // 10 min in hundreds of nano-seconds
  410. while ((Status = _ChannelDeletionEvent.Wait(UserRequest, KernelMode,
  411. TRUE, &Timeout)) != STATUS_SUCCESS) {
  412. //TRC_ASSERT(Status != STATUS_TIMEOUT,
  413. // (TB, "Timed out waiting for channel 0x%p", Channel));
  414. if (Status == STATUS_TIMEOUT) {
  415. TRC_DBG((TB, "Timed out waiting for channel 0x%p", Channel));
  416. //
  417. // If we just hit go in the debugger, we want to give it
  418. // just another 2 min
  419. //
  420. KeQuerySystemTime(&Timeout);
  421. Timeout.QuadPart += 1200000000; // 2 min in hundreds of nano-seconds
  422. }
  423. // Do nothing, just hit an alerted state
  424. }
  425. #else // !DBG
  426. while (_ChannelDeletionEvent.Wait(UserRequest, KernelMode,
  427. TRUE) != STATUS_SUCCESS) {
  428. // Do nothing, just hit an alerted state
  429. }
  430. #endif // DBG
  431. //ASSERT(_ApcChannelRef == 0);
  432. _ChannelDeletionEvent.ResetEvent();
  433. } // if (bWait)
  434. }
  435. BOOL
  436. DrSession::GetChannel(
  437. SmartPtr<VirtualChannel> &Channel
  438. )
  439. /*++
  440. Routine Description:
  441. Safely gets the Channel from the session and adds a reference
  442. Arguments:
  443. ClientEntry - The relevant client entry
  444. Return Value:
  445. The freshly referenced channel or NULL
  446. Notes:
  447. --*/
  448. {
  449. BEGIN_FN("DrSession::GetChannel");
  450. _ChannelLock.AcquireResourceShared();
  451. Channel = _Channel;
  452. _ChannelLock.ReleaseResource();
  453. return Channel != NULL;
  454. }
  455. VOID
  456. DrSession::SetChannel(
  457. SmartPtr<VirtualChannel> &Channel
  458. )
  459. /*++
  460. Routine Description:
  461. Safely sets the Channel for the session
  462. Arguments:
  463. ClientEntry - The relevant client entry
  464. Return Value:
  465. None
  466. Notes:
  467. --*/
  468. {
  469. BEGIN_FN("DrSession::SetChannel");
  470. _ChannelLock.AcquireResourceExclusive();
  471. _Channel = Channel;
  472. _ChannelLock.ReleaseResource();
  473. }
  474. NTSTATUS DrSession::SendToClient(PVOID Buffer, ULONG Length,
  475. ISessionPacketSender *PacketSender, BOOL bWorkerItem,
  476. BOOL LowPrioSend, PVOID AdditionalContext)
  477. {
  478. BEGIN_FN("DrSession::SendToClient A");
  479. return PrivateSendToClient(
  480. Buffer, Length, PacketSender, NULL, bWorkerItem,
  481. LowPrioSend, AdditionalContext
  482. );
  483. }
  484. NTSTATUS DrSession::SendToClient(PVOID Buffer, ULONG Length,
  485. DrWriteCallback WriteCallback, BOOL bWorkerItem,
  486. BOOL LowPrioSend, PVOID AdditionalContext)
  487. {
  488. BEGIN_FN("DrSession::SendToClient B");
  489. return PrivateSendToClient(
  490. Buffer, Length, NULL, WriteCallback, bWorkerItem,
  491. LowPrioSend, AdditionalContext
  492. );
  493. }
  494. NTSTATUS DrSession::PrivateSendToClient(PVOID Buffer, ULONG Length,
  495. ISessionPacketSender *PacketSender, DrWriteCallback WriteCallback,
  496. BOOL bWorkerItem, BOOL LowPrioSend, PVOID AdditionalContext)
  497. /*++
  498. Routine Description:
  499. Sends data to the client. Handles details of allocating contextual memory
  500. and verifying the virtual channel is available, etc.
  501. Arguments:
  502. Buffer - The data to be sent
  503. Length - the length of Buffer in bytes
  504. CallbackId - An identifier for the completion work
  505. AdditionalContext - Context specific to CallbackId, NULL by default
  506. Return Value:
  507. NTSTATUS code indicating communication status
  508. --*/
  509. {
  510. NTSTATUS Status;
  511. RDPDR_SERVER_ANNOUNCE_PACKET ServerAnnouncePacket;
  512. SmartPtr<VirtualChannel> Channel;
  513. DrWriteContext *WriteContext = NULL;
  514. BEGIN_FN("DrSession::SendToClient C");
  515. ASSERT(Buffer != NULL);
  516. ASSERT(Length > 0);
  517. if (GetChannel(Channel)) {
  518. TRC_DBG((TB, "Got session channel"));
  519. WriteContext = new DrWriteContext;
  520. if (WriteContext != NULL) {
  521. TRC_DBG((TB, "WriteContext allocated, sending"));
  522. WriteContext->Session = this;
  523. if (bWorkerItem) {
  524. WriteContext->BufferToFree = Buffer;
  525. }
  526. else {
  527. WriteContext->BufferToFree = NULL;
  528. }
  529. WriteContext->PacketSender = PacketSender;
  530. WriteContext->WriteCallback = WriteCallback;
  531. WriteContext->AdditionalContext = AdditionalContext;
  532. Status = Channel->Write(SendCompletionRoutine,
  533. WriteContext, Buffer, Length, bWorkerItem, LowPrioSend);
  534. } else {
  535. TRC_ERR((TB, "DrServerAnnounceWrite unable to allocate "
  536. "WriteContext"));
  537. Status = STATUS_INSUFFICIENT_RESOURCES;
  538. }
  539. } else {
  540. TRC_NRM((TB, "Channel not available"));
  541. Status = STATUS_DEVICE_NOT_CONNECTED;
  542. }
  543. return Status;
  544. }
  545. NTSTATUS DrSession::SendCompletionRoutine(
  546. IN PDEVICE_OBJECT DeviceObject,
  547. IN PIRP Irp,
  548. IN PVOID Context
  549. )
  550. /*++
  551. Routine Description:
  552. IoCompletion routine once a Server Announce packet has been sent to
  553. the client
  554. Arguments:
  555. Context - Contains a pointer to the ClientEntry information
  556. IoStatusBlock - Status information about the operation. The Information
  557. indicates the actual number of bytes written
  558. Reserved - Reserved
  559. Return Value:
  560. None
  561. --*/
  562. {
  563. DrWriteContext *WriteContext = (DrWriteContext *)Context;
  564. BEGIN_FN_STATIC("DrSession::SendCompletionRoutine");
  565. ASSERT(Context != NULL);
  566. if (Irp) {
  567. TRC_NRM((TB, "status: 0x%x", Irp->IoStatus.Status));
  568. WriteContext->Session->SendCompletion(WriteContext, &(Irp->IoStatus));
  569. IoFreeIrp(Irp);
  570. }
  571. else {
  572. TRC_NRM((TB, "status: 0x%x", WriteContext->IoStatusBlock.Status));
  573. WriteContext->Session->SendCompletion(WriteContext, &(WriteContext->IoStatusBlock));
  574. }
  575. if (WriteContext->BufferToFree) {
  576. delete (WriteContext->BufferToFree);
  577. }
  578. delete WriteContext;
  579. return STATUS_MORE_PROCESSING_REQUIRED;
  580. }
  581. VOID DrSession::SendCompletion(DrWriteContext *WriteContext,
  582. PIO_STATUS_BLOCK IoStatusBlock)
  583. {
  584. NTSTATUS Status = STATUS_SUCCESS;
  585. BEGIN_FN("DrSession::SendCompletion");
  586. //
  587. // One of these should be null
  588. //
  589. ASSERT(WriteContext->PacketSender == NULL ||
  590. WriteContext->WriteCallback == NULL);
  591. if (WriteContext->PacketSender != NULL) {
  592. Status = WriteContext->PacketSender->SendCompleted(
  593. WriteContext->AdditionalContext, IoStatusBlock);
  594. } else if (WriteContext->WriteCallback != NULL) {
  595. Status = WriteContext->WriteCallback(
  596. WriteContext->AdditionalContext, IoStatusBlock);
  597. }
  598. if (!NT_ERROR(Status)) {
  599. TRC_NRM((TB, "SendCompletion succeded"));
  600. } else {
  601. TRC_NRM((TB, "SendCompletion failed"));
  602. ChannelIoFailed();
  603. }
  604. }
  605. NTSTATUS DrSession::ServerAnnounceWrite()
  606. {
  607. NTSTATUS Status;
  608. RDPDR_SERVER_ANNOUNCE_PACKET ServerAnnouncePacket;
  609. BEGIN_FN("DrSession::ServerAnnounceWrite");
  610. //
  611. // Construct the packet
  612. //
  613. ServerAnnouncePacket.Header.Component = RDPDR_CTYP_CORE;
  614. ServerAnnouncePacket.Header.PacketId = DR_CORE_SERVER_ANNOUNCE;
  615. ServerAnnouncePacket.VersionInfo.Major = RDPDR_MAJOR_VERSION;
  616. ServerAnnouncePacket.VersionInfo.Minor = RDPDR_MINOR_VERSION;
  617. ServerAnnouncePacket.ServerAnnounce.ClientId = _ClientId;
  618. //
  619. // This is synchronous write
  620. //
  621. Status = SendToClient(&ServerAnnouncePacket, sizeof(RDPDR_SERVER_ANNOUNCE_PACKET), this, FALSE);
  622. return Status;
  623. }
  624. VOID DrSession::ReadPacket()
  625. {
  626. NTSTATUS Status;
  627. SmartPtr<VirtualChannel> Channel;
  628. BEGIN_FN("DrSession::ReadPacket");
  629. ASSERT(_ChannelBuffer != NULL);
  630. ASSERT(_ChannelBufferSize > 0);
  631. if (GetChannel(Channel)) {
  632. TRC_DBG((TB, "Got session channel"));
  633. //
  634. // It'd be ineficient to allocate a SmartPtr just to do an
  635. // AddRef when instead we'd neet to remember to call delete on
  636. // the allocated memory. Thus the explicit AddRef.
  637. //
  638. AddRef();
  639. _PartialPacketData = 0;
  640. DEBUG_DEREF_BUF();
  641. Status = Channel->Read(ReadCompletionRoutine, this,
  642. _ChannelBuffer, _ChannelBufferSize, FALSE);
  643. if (!NT_SUCCESS(Status)) {
  644. //
  645. // Frame the AddRef above for error case
  646. //
  647. Release();
  648. ChannelIoFailed();
  649. }
  650. } else {
  651. TRC_NRM((TB, "Channel not available"));
  652. Status = STATUS_DEVICE_NOT_CONNECTED;
  653. }
  654. }
  655. BOOL DrSession::ReadMore(ULONG cbSaveData, ULONG cbWantData)
  656. /*++
  657. Routine Description:
  658. Initiates a read operation on the channel to retrieve more
  659. data and place it in the channel buffer after the
  660. current data. Sets an appropriate completion handler.
  661. Arguments:
  662. cbSaveData - Data to be saved from the previous read
  663. cbWantData - Expected total size (including saved data) needed
  664. Return Value:
  665. BOOL - True if reading worked, False otherwise
  666. --*/
  667. {
  668. ULONG cbNewBufferSize = _ChannelBufferSize;
  669. NTSTATUS Status = STATUS_SUCCESS;
  670. SmartPtr<VirtualChannel> Channel;
  671. BEGIN_FN("DrSession::ReadMore");
  672. if ((cbWantData != 0) && (cbNewBufferSize < cbWantData)) {
  673. cbNewBufferSize = ((cbWantData / CHANNEL_CHUNK_LENGTH) + 1)
  674. * CHANNEL_CHUNK_LENGTH;
  675. }
  676. if (cbNewBufferSize - cbSaveData < CHANNEL_CHUNK_LENGTH) {
  677. cbNewBufferSize += CHANNEL_CHUNK_LENGTH;
  678. }
  679. if (cbNewBufferSize > _ChannelBufferSize ) {
  680. //
  681. // Need to expand the buffer size
  682. //
  683. TRC_NRM((TB, "Buffer full, expanding"));
  684. Status = ReallocateChannelBuffer(cbNewBufferSize, cbSaveData);
  685. if (!NT_SUCCESS(Status)) {
  686. // We didn't get a bigger buffer, so we really can't
  687. // read any more.
  688. TRC_ERR((TB, "Failed to expand channel buffer, %lx", Status));
  689. ChannelIoFailed();
  690. }
  691. }
  692. if (NT_SUCCESS(Status)) {
  693. //
  694. // Go ahead and read the additional data
  695. //
  696. if (GetChannel(Channel)) {
  697. TRC_DBG((TB, "Got session channel"));
  698. //
  699. // It'd be inefiecent to allocate a SmartPtr just to do an
  700. // AddRef when instead we'd neet to remember to call delete on
  701. // the allocated memory. Thus the explicit AddRef.
  702. //
  703. AddRef();
  704. _PartialPacketData = cbSaveData;
  705. // Deref channel buffer
  706. DEBUG_DEREF_BUF();
  707. Status = Channel->Read(ReadCompletionRoutine, this,
  708. _ChannelBuffer + cbSaveData, _ChannelBufferSize - cbSaveData, FALSE);
  709. if (!NT_SUCCESS(Status)) {
  710. //
  711. // Frame the AddRef above for error case
  712. //
  713. TRC_ERR((TB, "Failed (0x%x) to Read channel in ReadMore", Status));
  714. Release();
  715. ChannelIoFailed();
  716. }
  717. } else {
  718. TRC_NRM((TB, "Channel not available"));
  719. Status = STATUS_DEVICE_NOT_CONNECTED;
  720. }
  721. }
  722. return NT_SUCCESS(Status);
  723. }
  724. NTSTATUS DrSession::ReadCompletionRoutine(
  725. IN PDEVICE_OBJECT DeviceObject,
  726. IN PIRP Irp,
  727. IN PVOID Context)
  728. /*++
  729. Routine Description:
  730. IoCompletion routine once a Server Announce packet has been sent to
  731. the client
  732. Arguments:
  733. Context - Contains a pointer to the ClientEntry information
  734. IoStatusBlock - Status information about the operation. The Information
  735. indicates the actual number of bytes written
  736. Reserved - Reserved
  737. Return Value:
  738. None
  739. --*/
  740. {
  741. DrSession *Session = (DrSession *)Context;
  742. BEGIN_FN_STATIC("DrSession::ReadCompletionRoutine");
  743. ASSERT(Context != NULL);
  744. #if DBG
  745. InterlockedDecrement(&(Session->_ApcChannelRef));
  746. #endif
  747. if (NT_SUCCESS(Irp->IoStatus.Status) && Irp->AssociatedIrp.SystemBuffer != NULL) {
  748. ASSERT(Irp->Flags & (IRP_BUFFERED_IO | IRP_DEALLOCATE_BUFFER | IRP_INPUT_OPERATION));
  749. RtlCopyMemory(Irp->UserBuffer, Irp->AssociatedIrp.SystemBuffer, Irp->IoStatus.Information);
  750. }
  751. //
  752. // Call the real completion routine
  753. //
  754. Session->ReadCompletion(&(Irp->IoStatus));
  755. //
  756. // Free the AddRef in ReadPacket()
  757. //
  758. Session->Release();
  759. // Free the system buffer
  760. if (NT_SUCCESS(Irp->IoStatus.Status) && Irp->AssociatedIrp.SystemBuffer != NULL) {
  761. ExFreePool(Irp->AssociatedIrp.SystemBuffer);
  762. Irp->AssociatedIrp.SystemBuffer = NULL;
  763. }
  764. //
  765. // Free the irp
  766. //
  767. IoFreeIrp(Irp);
  768. return STATUS_MORE_PROCESSING_REQUIRED;
  769. }
  770. VOID DrSession::ReadCompletion(PIO_STATUS_BLOCK IoStatusBlock)
  771. /*++
  772. Routine Description:
  773. Completion routine once a packet header has been read from
  774. the client. Dispatches the request to the appropriate handler
  775. Arguments:
  776. None.
  777. Return Value:
  778. None.
  779. --*/
  780. {
  781. NTSTATUS Status;
  782. BOOL fDoDefaultRead = TRUE;
  783. ISessionPacketReceiver *PacketReceiver;
  784. ListEntry *ListEnum;
  785. BOOL bFound = FALSE;
  786. #if DBG
  787. ULONG cFound = 0;
  788. #endif // DBG
  789. BEGIN_FN("DrSession::ReadCompletion");
  790. DEBUG_REF_BUF();
  791. ASSERT(InterlockedDecrement(&_ApcCount) == 0);
  792. PRDPDR_HEADER RdpdrHeader = (PRDPDR_HEADER)_ChannelBuffer;
  793. _ReadStatus = *IoStatusBlock;
  794. TRC_NRM((TB, "IoStatus %lx, Bytes %lx, Component %c%c, PacketId %c%c",
  795. _ReadStatus.Status, _ReadStatus.Information,
  796. HIBYTE(RdpdrHeader->Component), LOBYTE(RdpdrHeader->Component),
  797. HIBYTE(RdpdrHeader->PacketId), LOBYTE(RdpdrHeader->PacketId)));
  798. if (NT_SUCCESS(_ReadStatus.Status)) {
  799. TRC_NRM((TB, "Successful channel read"));
  800. Status = STATUS_SUCCESS;
  801. //
  802. // Update the information field to reflect any data saved from a
  803. // previous read
  804. //
  805. _ReadStatus.Information += _PartialPacketData;
  806. TRC_ASSERT(_ChannelBufferSize >= _ReadStatus.Information,
  807. (TB, "ReadCompleted with too much data"));
  808. TRC_DBG((TB, "In ReadCompletion, _ChannelBuffer=%p", _ChannelBuffer));
  809. _PacketReceivers.LockShared();
  810. #if DBG
  811. //
  812. // We should only have one handler, in debug, assert this,
  813. //
  814. ListEnum = _PacketReceivers.First();
  815. while (ListEnum != NULL) {
  816. PacketReceiver = (ISessionPacketReceiver *)ListEnum->Node();
  817. TRC_DBG((TB, "PacketReceiver=%p", PacketReceiver));
  818. if (PacketReceiver->RecognizePacket(RdpdrHeader)) {
  819. cFound++;
  820. // "assert this"
  821. ASSERT(cFound == 1);
  822. }
  823. ListEnum = _PacketReceivers.Next(ListEnum);
  824. }
  825. #endif // DBG
  826. if (_ReadStatus.Information < sizeof(RDPDR_HEADER)) {
  827. TRC_ERR((TB, "Bad RDPDR packet size"));
  828. Status = STATUS_DEVICE_PROTOCOL_ERROR;
  829. _PacketReceivers.Unlock();
  830. goto CleanUp;
  831. }
  832. ListEnum = _PacketReceivers.First();
  833. while (ListEnum != NULL) {
  834. PacketReceiver = (ISessionPacketReceiver *)ListEnum->Node();
  835. TRC_DBG((TB, "PacketReceiver=%p", PacketReceiver));
  836. if (PacketReceiver->RecognizePacket(RdpdrHeader)) {
  837. //
  838. // Set the _DoDefaultRead here, if we get called back to do
  839. // a read from the packet handler we'll clear in back out
  840. //
  841. bFound = TRUE;
  842. Status = PacketReceiver->HandlePacket(RdpdrHeader, (ULONG)(_ReadStatus.Information),
  843. &fDoDefaultRead);
  844. // Once we found the one handler we're done
  845. break;
  846. }
  847. ListEnum = _PacketReceivers.Next(ListEnum);
  848. }
  849. _PacketReceivers.Unlock();
  850. if (!bFound) {
  851. TRC_ERR((TB, "Unrecognized RDPDR Header %d", RdpdrHeader->Component));
  852. Status = STATUS_DEVICE_PROTOCOL_ERROR;
  853. //ASSERT(bFound);
  854. }
  855. } else {
  856. Status = _ReadStatus.Status;
  857. TRC_ALT((TB, "Channel read failed 0x%X", Status));
  858. }
  859. CleanUp:
  860. if (NT_SUCCESS(Status)) {
  861. if (fDoDefaultRead) {
  862. //
  863. // Start the next read before releasing our reference to the ClientEntry
  864. //
  865. TRC_DBG((TB, "Starting default read"));
  866. ReadPacket();
  867. } else {
  868. TRC_DBG((TB, "Skipping default read"));
  869. }
  870. } else {
  871. TRC_ERR((TB, "Error detected in ReadCompletion %lx",
  872. Status));
  873. ChannelIoFailed();
  874. }
  875. }
  876. BOOL DrSession::RecognizePacket(PRDPDR_HEADER RdpdrHeader)
  877. /*++
  878. Routine Description:
  879. Determines if the packet will be handled by this object
  880. Arguments:
  881. RdpdrHeader - Header of the packet.
  882. Return Value:
  883. TRUE if this object should handle this packet
  884. FALSE if this object should not handle this packet
  885. --*/
  886. {
  887. BEGIN_FN("DrSession::RecognizePacket");
  888. //
  889. // If you add a packet here, update the ASSERTS in HandlePacket
  890. //
  891. switch (RdpdrHeader->Component) {
  892. case RDPDR_CTYP_CORE:
  893. switch (RdpdrHeader->PacketId) {
  894. case DR_CORE_CLIENTID_CONFIRM:
  895. TRC_NRM((TB, "Recognized CLIENTID_CONFIRM packet"));
  896. return TRUE;
  897. case DR_CORE_CLIENT_NAME:
  898. TRC_NRM((TB, "Recognized CLIENT_NAME packet"));
  899. return TRUE;
  900. case DR_CORE_CLIENT_CAPABILITY:
  901. TRC_NRM((TB, "Recognized CLIENT_CAPABILITY packet"));
  902. return TRUE;
  903. case DR_CORE_CLIENT_DISPLAY_NAME:
  904. TRC_NRM((TB, "Recognized CLIENT_DISPLAY_NAME packet"));
  905. return TRUE;
  906. }
  907. }
  908. return FALSE;
  909. }
  910. NTSTATUS DrSession::HandlePacket(PRDPDR_HEADER RdpdrHeader, ULONG Length,
  911. BOOL *DoDefaultRead)
  912. /*++
  913. Routine Description:
  914. Handles this packet
  915. Arguments:
  916. RdpdrHeader - Header of the packet.
  917. Length - Total length of the packet
  918. Return Value:
  919. NTSTATUS - An error code indicates the client is Bad and should be
  920. disconnected, otherwise SUCCESS.
  921. --*/
  922. {
  923. NTSTATUS Status = STATUS_DEVICE_PROTOCOL_ERROR;
  924. BEGIN_FN("DrSession::HandlePacket");
  925. //
  926. // RdpdrHeader read, dispatch based on the header
  927. //
  928. ASSERT(RdpdrHeader->Component == RDPDR_CTYP_CORE);
  929. switch (RdpdrHeader->Component) {
  930. case RDPDR_CTYP_CORE:
  931. ASSERT(RdpdrHeader->PacketId == DR_CORE_CLIENTID_CONFIRM ||
  932. RdpdrHeader->PacketId == DR_CORE_CLIENT_NAME ||
  933. RdpdrHeader->PacketId == DR_CORE_CLIENT_CAPABILITY ||
  934. RdpdrHeader->PacketId == DR_CORE_CLIENT_DISPLAY_NAME);
  935. switch (RdpdrHeader->PacketId) {
  936. case DR_CORE_CLIENTID_CONFIRM:
  937. Status = OnClientIdConfirm(RdpdrHeader, Length, DoDefaultRead);
  938. break;
  939. case DR_CORE_CLIENT_NAME:
  940. Status = OnClientName(RdpdrHeader, Length, DoDefaultRead);
  941. break;
  942. case DR_CORE_CLIENT_CAPABILITY:
  943. Status = OnClientCapability(RdpdrHeader, Length, DoDefaultRead);
  944. break;
  945. case DR_CORE_CLIENT_DISPLAY_NAME:
  946. Status = OnClientDisplayName(RdpdrHeader, Length, DoDefaultRead);
  947. break;
  948. }
  949. }
  950. return Status;
  951. }
  952. #if DBG
  953. BOOL DrSession::PacketReceiverExists(ISessionPacketReceiver *PacketReceiver)
  954. {
  955. PVOID NodeEnum;
  956. PVOID NodeFound = NULL;
  957. ListEntry *ListEnum;
  958. BEGIN_FN("DrSession::PacketReceiverExists");
  959. _PacketReceivers.LockShared();
  960. ListEnum = _PacketReceivers.First();
  961. while (ListEnum != NULL) {
  962. NodeEnum = ListEnum->Node();
  963. if (NodeEnum == (PVOID) PacketReceiver) {
  964. NodeFound = NodeEnum;
  965. NodeEnum = NULL;
  966. ListEnum = NULL;
  967. break;
  968. }
  969. ListEnum = _PacketReceivers.Next(ListEnum);
  970. }
  971. _PacketReceivers.Unlock();
  972. return NodeFound != NULL;
  973. }
  974. #endif // DBG
  975. NTSTATUS DrSession::RegisterPacketReceiver(ISessionPacketReceiver *PacketReceiver)
  976. /*++
  977. Routine Description:
  978. Adds an object to the queue of Packet handlers.
  979. Arguments:
  980. PacketReceiver - An interface to the object that wants to handle
  981. some packets
  982. Return Value:
  983. Boolean indication of whether to do a default read (TRUE) or not (FALSE),
  984. where FALSE might be specified if another read has been requested
  985. explicitly to get a full packet
  986. --*/
  987. {
  988. BEGIN_FN("DrSession::RegisterPacketReceiver");
  989. ASSERT(!PacketReceiverExists(PacketReceiver));
  990. ASSERT(PacketReceiver != NULL);
  991. if (_PacketReceivers.CreateEntry(PacketReceiver)) {
  992. return STATUS_SUCCESS;
  993. } else {
  994. return STATUS_INSUFFICIENT_RESOURCES;
  995. }
  996. }
  997. VOID DrSession::RemovePacketReceiver(ISessionPacketReceiver *PacketReceiver)
  998. {
  999. PVOID NodeEnum;
  1000. ListEntry *ListEnum;
  1001. BEGIN_FN("DrSession::RemovePacketReceiver");
  1002. _PacketReceivers.LockExclusive();
  1003. ListEnum = _PacketReceivers.First();
  1004. while (ListEnum != NULL) {
  1005. NodeEnum = ListEnum->Node();
  1006. if (NodeEnum == (PVOID) PacketReceiver) {
  1007. break;
  1008. }
  1009. ListEnum = _PacketReceivers.Next(ListEnum);
  1010. }
  1011. ASSERT(ListEnum != NULL);
  1012. _PacketReceivers.RemoveEntry(ListEnum);
  1013. _PacketReceivers.Unlock();
  1014. }
  1015. NTSTATUS DrSession::OnClientIdConfirm(PRDPDR_HEADER RdpdrHeader, ULONG cbPacket,
  1016. BOOL *DoDefaultRead)
  1017. /*++
  1018. Routine Description:
  1019. Called in response to recognizing a ClientIdConfirm packet has been
  1020. received.
  1021. Arguments:
  1022. RdpdrHeader - The packet
  1023. cbPacket - Bytes in the packet
  1024. DoDefaultRead - Set this to false if you do an explicit read
  1025. Return Value:
  1026. --*/
  1027. {
  1028. NTSTATUS Status;
  1029. PRDPDR_CLIENT_CONFIRM_PACKET ClientConfirmPacket =
  1030. (PRDPDR_CLIENT_CONFIRM_PACKET)RdpdrHeader;
  1031. BEGIN_FN("DrSession::OnClientIdConfirm");
  1032. TRC_ASSERT(ClientConfirmPacket->Header.Component == RDPDR_CTYP_CORE,
  1033. (TB, "Expected Core packet type!"));
  1034. TRC_ASSERT(ClientConfirmPacket->Header.PacketId == DR_CORE_CLIENTID_CONFIRM,
  1035. (TB, "Expected ClientConfirmPacket!"));
  1036. *DoDefaultRead = TRUE;
  1037. //
  1038. // Check the version. The original protocol didn't have a version field,
  1039. // so we first check to make sure the packet is big enough to indicate
  1040. // one is present.
  1041. //
  1042. if (cbPacket < sizeof(RDPDR_CLIENT_CONFIRM_PACKET)) {
  1043. //
  1044. // Client version too old to have version info. Just close
  1045. // the channel and be done with him.
  1046. //
  1047. TRC_ERR((TB, "ClientConfirmPacket size incorrect, may be old "
  1048. "client. Size: %ld",
  1049. cbPacket));
  1050. return STATUS_DEVICE_PROTOCOL_ERROR;
  1051. }
  1052. //
  1053. // We have a version field
  1054. //
  1055. TRC_NRM((TB, "Client version Major: %d Minor: %d",
  1056. ClientConfirmPacket->VersionInfo.Major,
  1057. ClientConfirmPacket->VersionInfo.Minor));
  1058. // Keep the version info
  1059. _ClientVersion.Major = ClientConfirmPacket->VersionInfo.Major;
  1060. _ClientVersion.Minor = ClientConfirmPacket->VersionInfo.Minor;
  1061. // Send server capability to client
  1062. if (COMPARE_VERSION(_ClientVersion.Minor, _ClientVersion.Major,
  1063. 5, 1) >= 0) {
  1064. SendClientCapability();
  1065. }
  1066. // Look for ClientID to have changed
  1067. if (ClientConfirmPacket->ClientConfirm.ClientId != _ClientId) {
  1068. TRC_NRM((TB, "Client %lx replied with alternate "
  1069. "ClientId %lx", _ClientId,
  1070. ClientConfirmPacket->ClientConfirm.ClientId));
  1071. SetSessionState(csConnected);
  1072. // TODO:
  1073. // Kill off the old devices
  1074. //
  1075. _ClientId = ClientConfirmPacket->ClientConfirm.ClientId;
  1076. //
  1077. // Accept the clientid
  1078. //
  1079. SendClientConfirm();
  1080. }
  1081. return STATUS_SUCCESS;
  1082. }
  1083. NTSTATUS DrSession::OnClientCapability(PRDPDR_HEADER RdpdrHeader, ULONG cbPacket,
  1084. BOOL *DoDefaultRead)
  1085. /*++
  1086. Routine Description:
  1087. Called in response to recognizing a client capability packet has been
  1088. received.
  1089. Arguments:
  1090. RdpdrHeader - The packet
  1091. cbPacket - Bytes in the packet
  1092. DoDefaultRead - Set this to false if you do an explicit read
  1093. Return Value:
  1094. --*/
  1095. {
  1096. NTSTATUS Status;
  1097. PRDPDR_CAPABILITY_SET_HEADER pCapSetHeader = (PRDPDR_CAPABILITY_SET_HEADER)RdpdrHeader;
  1098. PRDPDR_CAPABILITY_HEADER pCapHdr = (PRDPDR_CAPABILITY_HEADER)(pCapSetHeader + 1);
  1099. PBYTE pPacketEnd;
  1100. ULONG PacketLen;
  1101. BOOL CapSupported;
  1102. BEGIN_FN("DrSession::OnClientCapability");
  1103. TRC_ASSERT(pCapSetHeader->Header.Component == RDPDR_CTYP_CORE,
  1104. (TB, "Expected Core packet type!"));
  1105. TRC_ASSERT(pCapSetHeader->Header.PacketId == DR_CORE_CLIENT_CAPABILITY,
  1106. (TB, "Expected ClientCapabilityPacket!"));
  1107. *DoDefaultRead = TRUE;
  1108. //
  1109. // Check to make sure the server send us at least the header size
  1110. //
  1111. if (cbPacket < sizeof(RDPDR_CAPABILITY_SET_HEADER)) {
  1112. TRC_ERR((TB, "ClientCapabilityPacket size incorrect. Size: %ld",
  1113. cbPacket));
  1114. return STATUS_DEVICE_PROTOCOL_ERROR;
  1115. }
  1116. pPacketEnd = (PBYTE)RdpdrHeader + cbPacket;
  1117. //
  1118. // Grab the supported capability info from client's capability PDU
  1119. //
  1120. // TODO: Should check for large capability set?
  1121. //
  1122. for (unsigned i = 0; i < pCapSetHeader->numberCapabilities; i++) {
  1123. if (((PBYTE)(pCapHdr) + sizeof(RDPDR_CAPABILITY_HEADER) <= pPacketEnd) &&
  1124. (pCapHdr->capabilityLength <= (pPacketEnd - (PBYTE)pCapHdr))) {
  1125. PacketLen = (ULONG)(pPacketEnd - (PBYTE)pCapHdr);
  1126. Status = InitClientCapability(pCapHdr, &PacketLen, &CapSupported);
  1127. if (!NT_SUCCESS(Status)) {
  1128. TRC_ASSERT(FALSE,(TB, "Bad client capability packet"));
  1129. return Status;
  1130. }
  1131. pCapHdr = (PRDPDR_CAPABILITY_HEADER)(((PBYTE)pCapHdr) + pCapHdr->capabilityLength);
  1132. }
  1133. else {
  1134. TRC_ERR((TB, "ClientCapabilityPacket incorrect packet."));
  1135. return STATUS_DEVICE_PROTOCOL_ERROR;
  1136. }
  1137. }
  1138. return STATUS_SUCCESS;
  1139. }
  1140. VOID DrSession::SendClientConfirm()
  1141. /*++
  1142. Routine Description:
  1143. Sends a ClientIdConfirm packet to the client
  1144. Arguments:
  1145. None.
  1146. Return Value:
  1147. None.
  1148. --*/
  1149. {
  1150. PRDPDR_CLIENT_CONFIRM_PACKET pClientConfirmPacket;
  1151. BEGIN_FN("DrSession::SendClientConfirm");
  1152. //
  1153. // Construct the packet
  1154. //
  1155. pClientConfirmPacket = new RDPDR_CLIENT_CONFIRM_PACKET;
  1156. if (pClientConfirmPacket != NULL) {
  1157. pClientConfirmPacket->Header.Component = RDPDR_CTYP_CORE;
  1158. pClientConfirmPacket->Header.PacketId = DR_CORE_CLIENTID_CONFIRM;
  1159. pClientConfirmPacket->VersionInfo.Major = RDPDR_MAJOR_VERSION;
  1160. pClientConfirmPacket->VersionInfo.Minor = RDPDR_MINOR_VERSION;
  1161. pClientConfirmPacket->ClientConfirm.ClientId = _ClientId;
  1162. //
  1163. // Send it - asynchronous write, cleanup not here
  1164. //
  1165. SendToClient(pClientConfirmPacket, sizeof(RDPDR_CLIENT_CONFIRM_PACKET), this, TRUE);
  1166. }
  1167. }
  1168. VOID DrSession::SendClientCapability()
  1169. /*++
  1170. Routine Description:
  1171. Sends server capability packet to the client
  1172. Arguments:
  1173. None.
  1174. Return Value:
  1175. None.
  1176. --*/
  1177. {
  1178. PRDPDR_SERVER_COMBINED_CAPABILITYSET pSrvCapabilitySet;
  1179. BEGIN_FN("DrSession::SendClientCapability");
  1180. //
  1181. // Send it
  1182. //
  1183. pSrvCapabilitySet = new RDPDR_SERVER_COMBINED_CAPABILITYSET;
  1184. if (pSrvCapabilitySet != NULL) {
  1185. memcpy(pSrvCapabilitySet, &_SrvCapabilitySet, sizeof(RDPDR_SERVER_COMBINED_CAPABILITYSET));
  1186. //
  1187. // Send it - asynchronous write, cleanup not here
  1188. //
  1189. SendToClient(pSrvCapabilitySet, sizeof(RDPDR_SERVER_COMBINED_CAPABILITYSET), this, TRUE);
  1190. }
  1191. }
  1192. NTSTATUS DrSession::InitClientCapability(PRDPDR_CAPABILITY_HEADER pCapHdr, ULONG *pPacketLen, BOOL *pCapSupported)
  1193. /*++
  1194. Routine Description:
  1195. Initialize the client capability
  1196. Arguments:
  1197. pCapHdr - client capability
  1198. pPacketLen - In: Length of the total packet
  1199. Out: Length used in this function
  1200. CapSupported - TRUE - if we found the same capability supported on the server side
  1201. FALSE - if this is not a supported capability
  1202. Return Value:
  1203. TRUE - if we found the same capability supported on the server side
  1204. FALSE - if this is not a supported capability
  1205. --*/
  1206. {
  1207. *pCapSupported = FALSE;
  1208. switch(pCapHdr->capabilityType) {
  1209. case RDPDR_GENERAL_CAPABILITY_TYPE:
  1210. {
  1211. PRDPDR_GENERAL_CAPABILITY pGeneralCap = (PRDPDR_GENERAL_CAPABILITY)pCapHdr;
  1212. if (*pPacketLen < sizeof(RDPDR_GENERAL_CAPABILITY)) {
  1213. return STATUS_DEVICE_PROTOCOL_ERROR;
  1214. }
  1215. *pPacketLen = sizeof(RDPDR_GENERAL_CAPABILITY);
  1216. _CliCapabilitySet.GeneralCap.version = pGeneralCap->version;
  1217. _CliCapabilitySet.GeneralCap.osType = pGeneralCap->osType;
  1218. _CliCapabilitySet.GeneralCap.osVersion = pGeneralCap->osVersion;
  1219. _CliCapabilitySet.GeneralCap.ioCode1 = pGeneralCap->ioCode1;
  1220. _CliCapabilitySet.GeneralCap.extendedPDU = pGeneralCap->extendedPDU;
  1221. _CliCapabilitySet.GeneralCap.protocolMajorVersion = pGeneralCap->protocolMajorVersion;
  1222. _CliCapabilitySet.GeneralCap.protocolMinorVersion = pGeneralCap->protocolMinorVersion;
  1223. *pCapSupported = TRUE;
  1224. }
  1225. break;
  1226. case RDPDR_PRINT_CAPABILITY_TYPE:
  1227. {
  1228. PRDPDR_PRINT_CAPABILITY pPrintCap = (PRDPDR_PRINT_CAPABILITY)pCapHdr;
  1229. if (*pPacketLen < sizeof(RDPDR_PRINT_CAPABILITY)) {
  1230. return STATUS_DEVICE_PROTOCOL_ERROR;
  1231. }
  1232. *pPacketLen = sizeof(RDPDR_PRINT_CAPABILITY);
  1233. _CliCapabilitySet.PrintCap.version = pPrintCap->version;
  1234. *pCapSupported = TRUE;
  1235. }
  1236. break;
  1237. case RDPDR_PORT_CAPABILITY_TYPE:
  1238. {
  1239. PRDPDR_PORT_CAPABILITY pPortCap = (PRDPDR_PORT_CAPABILITY)pCapHdr;
  1240. if (*pPacketLen < sizeof(RDPDR_PORT_CAPABILITY)) {
  1241. return STATUS_DEVICE_PROTOCOL_ERROR;
  1242. }
  1243. *pPacketLen = sizeof(RDPDR_PORT_CAPABILITY);
  1244. _CliCapabilitySet.PortCap.version = pPortCap->version;
  1245. *pCapSupported = TRUE;
  1246. }
  1247. break;
  1248. case RDPDR_FS_CAPABILITY_TYPE:
  1249. {
  1250. PRDPDR_FS_CAPABILITY pFsCap = (PRDPDR_FS_CAPABILITY)pCapHdr;
  1251. if (*pPacketLen < sizeof(RDPDR_FS_CAPABILITY)) {
  1252. return STATUS_DEVICE_PROTOCOL_ERROR;
  1253. }
  1254. *pPacketLen = sizeof(RDPDR_FS_CAPABILITY);
  1255. _CliCapabilitySet.FileSysCap.version = pFsCap->version;
  1256. *pCapSupported = TRUE;
  1257. }
  1258. break;
  1259. case RDPDR_SMARTCARD_CAPABILITY_TYPE:
  1260. {
  1261. PRDPDR_SMARTCARD_CAPABILITY pSmartCardCap = (PRDPDR_SMARTCARD_CAPABILITY)pCapHdr;
  1262. if (*pPacketLen < sizeof(RDPDR_SMARTCARD_CAPABILITY)) {
  1263. return STATUS_DEVICE_PROTOCOL_ERROR;
  1264. }
  1265. *pPacketLen = sizeof(RDPDR_SMARTCARD_CAPABILITY);
  1266. _CliCapabilitySet.SmartCardCap.version = pSmartCardCap->version;
  1267. *pCapSupported = TRUE;
  1268. }
  1269. break;
  1270. default:
  1271. {
  1272. if (*pPacketLen < pCapHdr->capabilityLength) {
  1273. return STATUS_DEVICE_PROTOCOL_ERROR;
  1274. }
  1275. *pPacketLen = pCapHdr->capabilityLength;
  1276. }
  1277. break;
  1278. }
  1279. return STATUS_SUCCESS;
  1280. }
  1281. VOID DrSession::SendDeviceReply(ULONG DeviceId, NTSTATUS Result)
  1282. /*++
  1283. Routine Description:
  1284. Sends a DeviceReply packet to the client
  1285. Arguments:
  1286. DeviceId - Id that the client proposed
  1287. Result - Indication of whether the device was accepted
  1288. Return Value:
  1289. NTSTATUS - Success/failure indication of the operation
  1290. --*/
  1291. {
  1292. PRDPDR_DEVICE_REPLY_PACKET pDeviceReplyPacket;
  1293. BEGIN_FN("DrSession::SendDeviceReply");
  1294. //
  1295. // Construct the packet
  1296. //
  1297. pDeviceReplyPacket = new RDPDR_DEVICE_REPLY_PACKET;
  1298. if (pDeviceReplyPacket != NULL) {
  1299. pDeviceReplyPacket->Header.Component = RDPDR_CTYP_CORE;
  1300. pDeviceReplyPacket->Header.PacketId = DR_CORE_DEVICE_REPLY;
  1301. pDeviceReplyPacket->DeviceReply.DeviceId = DeviceId;
  1302. pDeviceReplyPacket->DeviceReply.ResultCode = Result;
  1303. //
  1304. // Send it - asynchronous write, cleanup not here
  1305. //
  1306. SendToClient(pDeviceReplyPacket, sizeof(RDPDR_DEVICE_REPLY_PACKET), this, TRUE);
  1307. }
  1308. }
  1309. VOID DrSession::ChannelIoFailed()
  1310. /*++
  1311. Routine Description:
  1312. Handles Virtual channel IO failure. Marks the client as disabled and cancels
  1313. all the outstanding Io operations
  1314. Arguments:
  1315. ClientEntry - The client which has been disconnected
  1316. Return Value:
  1317. None
  1318. --*/
  1319. {
  1320. BEGIN_FN("DrSession::ChannelIoFailed");
  1321. //
  1322. // Mark as disconnected
  1323. //
  1324. SetSessionState(csDisconnected);
  1325. //
  1326. // Close down the channel, but don't need to wait for all IO to
  1327. // finish
  1328. //
  1329. DeleteChannel(FALSE);
  1330. //
  1331. // Fail outstanding IO
  1332. // Should be done via Delete devices?
  1333. //
  1334. _ExchangeManager.Stop();
  1335. }
  1336. NTSTATUS DrSession::OnClientName(PRDPDR_HEADER RdpdrHeader, ULONG cbPacket,
  1337. BOOL *DoDefaultRead)
  1338. /*++
  1339. Routine Description:
  1340. Called in response to recognizing a ClientName packet has been
  1341. received.
  1342. Arguments:
  1343. RdpdrHeader - The packet
  1344. cbPacket - Bytes in the packet
  1345. Return Value:
  1346. Boolean indication of whether to do a default read (TRUE) or not (FALSE),
  1347. where FALSE might be specified if another read has been requested
  1348. explicitly to get a full packet
  1349. --*/
  1350. {
  1351. NTSTATUS Status;
  1352. PRDPDR_CLIENT_NAME_PACKET ClientNamePacket =
  1353. (PRDPDR_CLIENT_NAME_PACKET)RdpdrHeader;
  1354. ULONG cb;
  1355. BEGIN_FN("DrSession::OnClientName");
  1356. *DoDefaultRead = TRUE;
  1357. if (cbPacket < sizeof(RDPDR_CLIENT_NAME_PACKET)) {
  1358. //
  1359. // Sent an undersized packet
  1360. //
  1361. return STATUS_DEVICE_PROTOCOL_ERROR;
  1362. }
  1363. // Copy and possibly convert the computer name
  1364. if (ClientNamePacket->Name.Unicode) {
  1365. TRC_NRM((TB, "Copying Unicode client name"));
  1366. // Restrict size to max size
  1367. cb = ClientNamePacket->Name.ComputerNameLen;
  1368. if ((cbPacket - sizeof(RDPDR_CLIENT_DISPLAY_NAME_PACKET)) < cb) {
  1369. //
  1370. // Sent an undersized packet
  1371. //
  1372. return STATUS_DEVICE_PROTOCOL_ERROR;
  1373. }
  1374. if (cb > (RDPDR_MAX_COMPUTER_NAME_LENGTH * sizeof(WCHAR))) {
  1375. cb = RDPDR_MAX_COMPUTER_NAME_LENGTH * sizeof(WCHAR);
  1376. }
  1377. // Copy the text
  1378. RtlCopyMemory(_ClientName, (ClientNamePacket + 1), cb);
  1379. // Ensure buffer termination
  1380. _ClientName[RDPDR_MAX_COMPUTER_NAME_LENGTH - 1] = 0;
  1381. TRC_NRM((TB, "Copied client computer name: %S",
  1382. _ClientName));
  1383. } else {
  1384. cb = ClientNamePacket->Name.ComputerNameLen;
  1385. if (cbPacket - sizeof(RDPDR_CLIENT_NAME_PACKET) < cb) {
  1386. //
  1387. // Sent an undersized packet
  1388. //
  1389. return STATUS_DEVICE_PROTOCOL_ERROR;
  1390. }
  1391. if (cb > (RDPDR_MAX_COMPUTER_NAME_LENGTH)) {
  1392. cb = RDPDR_MAX_COMPUTER_NAME_LENGTH;
  1393. }
  1394. // CopyConvert the buffer
  1395. cb = ConvertToAndFromWideChar(ClientNamePacket->Name.CodePage,
  1396. _ClientName, sizeof(_ClientName),
  1397. (LPSTR)(ClientNamePacket + 1),
  1398. cb, TRUE);
  1399. if (cb != -1) {
  1400. // Successful conversion
  1401. _ClientName[RDPDR_MAX_COMPUTER_NAME_LENGTH - 1] = 0;
  1402. TRC_NRM((TB, "Converted client computer name: %S",
  1403. _ClientName));
  1404. } else {
  1405. // Doh
  1406. TRC_ERR((TB, "Failed to convert ComputerName to "
  1407. "Unicode."));
  1408. _ClientName[0] = 0;
  1409. }
  1410. }
  1411. return TRUE;
  1412. }
  1413. NTSTATUS DrSession::OnClientDisplayName(PRDPDR_HEADER RdpdrHeader, ULONG cbPacket,
  1414. BOOL *DoDefaultRead)
  1415. /*++
  1416. Routine Description:
  1417. Called in response to recognizing a ClientDisplayName packet has been
  1418. received.
  1419. Arguments:
  1420. RdpdrHeader - The packet
  1421. cbPacket - Bytes in the packet
  1422. Return Value:
  1423. Boolean indication of whether to do a default read (TRUE) or not (FALSE),
  1424. where FALSE might be specified if another read has been requested
  1425. explicitly to get a full packet
  1426. --*/
  1427. {
  1428. NTSTATUS Status;
  1429. PRDPDR_CLIENT_DISPLAY_NAME_PACKET ClientDisplayNamePacket =
  1430. (PRDPDR_CLIENT_DISPLAY_NAME_PACKET)RdpdrHeader;
  1431. ULONG cb;
  1432. BEGIN_FN("DrSession::OnClientDisplayName");
  1433. *DoDefaultRead = TRUE;
  1434. if (cbPacket < sizeof(RDPDR_CLIENT_DISPLAY_NAME_PACKET)) {
  1435. //
  1436. // Sent an undersized packet
  1437. //
  1438. return STATUS_DEVICE_PROTOCOL_ERROR;
  1439. }
  1440. // Copy the computer display name
  1441. TRC_NRM((TB, "Copying Unicode client display name"));
  1442. // Restrict size to max size
  1443. cb = ClientDisplayNamePacket->Name.ComputerDisplayNameLen;
  1444. if ((cbPacket - sizeof(RDPDR_CLIENT_DISPLAY_NAME_PACKET)) < cb) {
  1445. //
  1446. // Sent an undersized packet
  1447. //
  1448. return STATUS_DEVICE_PROTOCOL_ERROR;
  1449. }
  1450. if (cb > (RDPDR_MAX_CLIENT_DISPLAY_NAME * sizeof(WCHAR))) {
  1451. cb = RDPDR_MAX_CLIENT_DISPLAY_NAME * sizeof(WCHAR);
  1452. }
  1453. // Copy the text
  1454. RtlCopyMemory(_ClientDisplayName, (ClientDisplayNamePacket + 1), cb);
  1455. // Ensure buffer termination
  1456. _ClientDisplayName[RDPDR_MAX_CLIENT_DISPLAY_NAME - 1] = L'\0';
  1457. TRC_NRM((TB, "Copied client computer display name: %S",
  1458. _ClientName));
  1459. return TRUE;
  1460. }
  1461. NTSTATUS DrSession::ReallocateChannelBuffer(ULONG ulNewBufferSize,
  1462. ULONG ulSaveBytes)
  1463. /*++
  1464. Routine Description:
  1465. Attempts to make the channel buffer at least the given size, preserving
  1466. as many bytes as desired
  1467. Arguments:
  1468. ulNewBufferSize - The desired size
  1469. ulSaveBytes - The number of bytes in the existing buffer that should be
  1470. preserved
  1471. Return Value:
  1472. STATUS_SUCCESS - The channel buffer is now at least the desired size
  1473. STATUS_INSUFFICIENT_RESOURCES - The new buffer could not be allocated,
  1474. but the old buffer was preserved.
  1475. --*/
  1476. {
  1477. PUCHAR pNewBuffer;
  1478. NTSTATUS Status;
  1479. BEGIN_FN("DrSession::ReallocateChannelBuffer");
  1480. TRC_NRM((TB, "Old size: %ld, "
  1481. "desired size: %ld save bytes: %ld",
  1482. _ChannelBufferSize,
  1483. ulNewBufferSize,
  1484. ulSaveBytes));
  1485. if (ulNewBufferSize <= _ChannelBufferSize) {
  1486. return STATUS_SUCCESS;
  1487. }
  1488. pNewBuffer = new UCHAR[ulNewBufferSize];
  1489. if (pNewBuffer != NULL) {
  1490. TRC_NRM((TB, "saving the old bytes."));
  1491. // Save the current data
  1492. RtlCopyMemory(pNewBuffer, _ChannelBuffer, ulSaveBytes);
  1493. ASSERT(_ApcCount == 0);
  1494. delete _ChannelBuffer;
  1495. _ChannelBuffer = pNewBuffer;
  1496. TRC_DBG((TB, "New ChannelBuffer=%p", _ChannelBuffer));
  1497. _ChannelBufferSize = ulNewBufferSize;
  1498. Status = STATUS_SUCCESS;
  1499. } else {
  1500. Status = STATUS_INSUFFICIENT_RESOURCES;
  1501. }
  1502. return Status;
  1503. }
  1504. NTSTATUS DrSession::SendCompleted(PVOID Context, PIO_STATUS_BLOCK IoStatusBlock)
  1505. {
  1506. BEGIN_FN("DrSession::SendCompleted");
  1507. //
  1508. // return the status, if it is an error the connection will be dropped
  1509. // automatically
  1510. //
  1511. return IoStatusBlock->Status;
  1512. }