Remko Weijnen's Blog (Remko's Blog)

About Virtualization, VDI, SBC, Application Compatibility and anything else I feel like

Archive for the ‘Delphi’ Category

Working with bitfields in Delphi

Recently I needed to convert a C header file to Delphi which contained bitfields. Let’s take a look at a sample structure that contains bitfields:

It means that there is a DWORD (Cardinal) dwValue1 followed by a bitfield with the size of a ULONG (32 bits). In this bitfield 4 values are defined (BitValue1..4) which are used as boolean’s because the value can offcourse be 0 or 1. Since Delphi doesn’t know a bitfield type the question is how to translate it. Usually it would mean that we simply treat the whole bitfield value as a ULONG and extract the required properties by applying a bitmask (shl/shr). Starting from BDS2006 we can define a record with propertes and use getters and setters. Using this technique we can present boolean values to the user:

Code completion shows that the record has one DWORD Value and 4 Boolean Values which is just what we want!
CodeCompletion

Offcourse we need to implement the Getters and Setters:

We can even add a constructor to it, this can be used to e.g. initialize the record (in the example below we fill with zeroes). Note that only a constructor with at least one argument can be used:

So why not use a class instead of record? The answer is that a class is just a pointer we can never pass this to a function, procedure or api call that expects a record. But if we want to support older Delphi versions, like Delphi 6 or Delphi 7 and even Delphi 2005, which are still used a lot we need to find another solution. I came up with (ab)using sets to emulate bitfields, we can do this because a set is actually a set of bits (limited to 256 bits). The example structure could look like this if we use sets:

We can use normal set operations to get and set bitvalues:

Settings like minimal enum size and record alignment are important because we need to asssure that te record size matches the C structure’s size (especially when using structures with a lot of bitfields. I choose to do this with a litte trick, first I declare some constants:

We use these constants to force the correct size, in the example the bitfield was a ULONG which is 32 bits. We add the al32Bit constant to the bitfield:

So I thought I had it figured out… until I came to this line in the C header file:

So we have a bitfield consisting off multiple bits! This gave me some headaches but I finally came up with the following approach

We need a helper function to retreive the numeric value of ColorDepth:

The helper function is used like this:

Some limitations remain, although I don’t think you are likely to encouter these:

  • A Delphi Set can contain at most 256 values.
  • The ValueFromBitSet function returns an Int64, so values that do not fit in an Int64 cannot be returned.
  • Values in a Set need a unique name.

Vista SP1 changes to Terminal Server API

In a previous article I wrote about changes in utildll in vista that breaked compatibality for Terminal Server. Even though release notes for Service Pack 1 don’t indicate changes or fixes in this area my testing shows that Microsoft has taken over the Windows 2008 implementation of utildll to Vista.

This is a good thing, because applications depending on utildll work again. I have updated JwaWinsta for SP1, all Vista versions of the utildll functions are renamed to VistaRTM and all Safe functions were updated to check for SP1. This means that the Safe functions can be used on all OS versions and Service packs! You are strongly advised to use only the Safe functions.

Some observations with SP1: 

  • I quickly tested TSAdmin as well and it seems to work again, only noticable flaw is that the console sessions returns an idle time of 17642 days (Reported Last Input Time is 01-01-1601 but utildll’s ElapsedTimeString function doesn’t account for dates this long in the past).
  • WTSApi32.dll contains some new functions like WTSStartRemoteControlSession and WTSStopRemoteControlSession (which are wrappers to WinStationShadow).
  • The WTSWaitSystemEvent bug I wrote about earlier is still present. I advise to check for winsta.dll version >= 6.0.6000.20664 in code when using this API and advise user to install the Hotfix.

Update: I just tried to install hotfix KB941561 but this fail with the error: The update does not apply to your system. If you do want to get this bug fixed you need to manually replace winsta.dll (take ownership and set permissions to full control). winsta.dll from hotfix KB941561 (X86) (4362 downloads )

For my Terminal Server unit in the Jedi Security library I use 2 TObjectList descendants to hold a list of Terminal Server Sessions and Processes. Consider the sample below which connects to a server and enumerates all sessions:

In the sample I loop through the sessions with a for loop. Even though Delphi supports the for in loop since Delphi 2005 it’s not possible to use this in TObjectList descendants, so we cannot use this:

To make this possible we need to implement GetEnumerator and an Enumerator class:

Now we add a function with the name GetEnumerator in the SessionList class:

And that’s really all!

TSAdminEx Progress

I just wanted to show some of the progress that I made in development of TSAdminEx. I thought the best way would be to show some screenshots. Which reminds me I installed a nice Javascript to enlarge the thumbnails, click to see it…

Edit: A beta is ready!

This screenshot shows TSAdminEx after startup. In the Left Treeview you can see the This Computer, Favorites and All Listed Servers icon. On Startup all available domains are enumerated.
Here you see the Users tab. If you move the mouse over some columns you can get extra info in the hint. In this hint you get the actual shadow permissions of the highlighted session.
This is the Sessions tab where extra details of a session are shown. By default you can see sessions statistics such as Incomingbytes and Outgoingbytes, this makes it easy to identify sessions that have much traffic.Interesting detail is that the Remote Address column lists the real ip address that is connected to Terminal Server! Hovering the mouse also shows the port number.
Now the Process tab is my favorite! It lists far more details than TSAdmin and also some usefull columns that cannot be show with TSAdmin or any documented Terminal Server API!The Process Age columns shows how long the process is running. You can compare this with the CPU Time column to see how much CPU Time the process has allocated since startup.The Mem Usage shows the amount of physical RAM a process uses while the VM Size column shows the amount of Private Bytes (Virtual Memory) a process uses.
If you click on a domain in the Left Treeview, TSAdminEx will enumerate all Terminal Servers for that domain. You can continue using and even enumerate multiple domains, because enumeration is done from seperate threads!
If you select (highlight) a particular session the appropriate toolbar buttons are enabled or disabled automically indicating the actions that can be performed on the selected session.
And offcourse, an about dialog…

Hope you like it! Comments are open…

Using WTSWaitSystemEvent

If you develop an application for Terminal Server you might want to react on session events. This means that your application is notified when a user logs on, logs off or becomes idle. This can be done with the WTSWaitSystemEvent function. Implementing it is rather simple and could look something like this:

Notice that you would probably do this from a seperate thread otherwise you will block the main thread. To stop waiting for Events you send a special event:

Please note that there are at least 2 issues with this API, one with Windows 2000 and one with Windows Vista. On Windows 2000 events are reported twice for each actual event. Microsoft’s resolution?

The application should expect the event twice, and filter out the second occurrence.

Now how do we solve this? I would suggest introducing a small delay after an event trigger, this way you will probably not receive the duplicate event.

On Windows Vista there’s another issue: After you set the value of the EventMask parameter to WTS_EVENT_FLUSH in the WTSWaitSystemEvent function, no pending calls to the function return on a Windows Vista-based computer. Now what does this mean? It means that after sending WTS_EVENT_FLUSH the thread never responds! So there’s actually no nice way to end the thread, the only escape is a call to TerminateThread.

Microsoft does offer a hotfix, so my suggestion is a check on startup that will notify the user that he/she needs to install the hotfix. A version check can be done on winsta.dll, the version before the fix is 6.0.6000.16386. Hotfix version is 6.0.6000.20664. According to this article the fix will be included in Vista SP1.

References:

Undocumented API’s from Utildll

Several of Microsoft’s Terminal Server tools use undocumented API’s from Utildll.dll. For instance Terminal Server Admin uses it to get a localised connect state string and to format time strings like idle time, logon time etc.

Functions below seems to be the most usefull ones, I will add those to the JwaWinsta unit:

  • function StrConnectState (returns localised string of the given ConnectState)
  • DateTimeString (returns formatted date timestring according to user’s timesettings)
  • function CurrentDateTimeString (like the name says)
  • function ElapsedTimeString (returns formatted string with elapsed time as in TSAdmin)
  • function CalculateElapsedTime (returns elapsed time in seconds)
  • function CalculateDiffTime (returns time difference in seconds)
  • function GetUnknownString (returns localised “unknown” string)

Citrix has it’s own version of this DLL called CUtildll.dll which is similar but uses (Citrix) MUI for localising strings.

Delphi and Terminal Server Aware

When an application is not Terminal Server aware (also known as a legacy application), Terminal Server makes certain modifications to the legacy application to make it work properly in a multiuser environment. For example, Terminal Server will create a virtual Windows folder, such that each user gets a Windows folder instead of getting the system’s Windows directory. This gives users access to their own INI files. In addition, Terminal Server makes some adjustments to the registry for a legacy application. These modifications slow the loading of the legacy application on Terminal Server and require up to 8 MegaBytes extra memory. This behaviour can be avoided if the TSAware flag is present in the PE header of an executable as can be read here at MSDN.

But how do we set this property in Delphi?

In Windows.pas we can see that the constant is defined:

But how to use this in your application?
Add the line

somewhere below the uses clause and we’re done!

Offcourse you are now responsible for making your application Terminal Server compliant which according to Microsoft means: If an application is Terminal Server aware, it must neither rely on INI files nor write to the HKEY_CURRENT_USER registry during setup.

It has been a little silent on the JEDI Apilib project lately, but this will change!

We had some change in the team members: Marcel van Brakel, founder and large contributor of the project has signed off because he no longer actively uses Delphi. Christian Wimmer has joined the team and he is a very promising member.

Christian has been working on a new include model (optional) of the Jedi Apilib which has the advantage that you only need to use one unit (JwaWindows) for the whole library.

Chris has also published the JEDI Windows Security Code Library (Jwscl). This is library that tremendously simplifies using Win32 API calls from Delphi. At this point the library contains:

  • Windows Version
  • Token
  • Impersonation
  • Login
  • SID
  • Access Control List
  • Security Descriptor
  • Owner, Group, DACL, SACL
  • WindowStation
  • Desktop
  • LSA
  • Rights mapping
  • Secured Objects Files, Registry (+Inheritance), etc.
  • Credentials (Login Dialog)
  • Encryption (MS Crypto API)
  • Well Known SIDs
  • Privileges
  • Security Dialogs (The “ACL Editor” you see on the security yab when you rightclick object in Explorer)
  • Terminal Sessions
  • Unicode + Ansicode
  • Vista Elevation
  • Vista Integrity Level

Although Jwscl is in beta stage it is already very well useable.

(more…)

How to get Client IP Address?

When a client is connected to a Terminal Server Session you can use the Terminal Server API to retrieve the client’s local IP address.

Start by enumerating all sessions with WtsEnumerateSessions and then for each session get the ClientAddress with a call to WTSQuerySessionInformation with the WTSClientAddress parameter. Sound simple, no?

WTSQuerySessionInformation returns a pointer to a WTS_CLIENT_ADDRESS structure. You need to know that the IP address is located at on offset of 2 bytes in the Address member of WTS_CLIENT_ADDRESS.

So here’s a sample:

(more…)

TSAdminEx

You will probably know Microsofts Tool to Manage Terminal Server, it’s called Terminal Services Manager (you will probably know it as TSAdmin). It can be used to view information about terminal servers including all sessions, users, and processes for each terminal server.

TSAdmin Screenshot

I’m currently working on a TSAdmin replacement (codename TSAdminEx). Purpose is to show how to use the Terminal Server API’s and as a little bonus we will add some extra functionality to TSAdminEx.

(more…)

Blogroll


Categories


Archives