Overview - TWAPI Version 4.0 Overview

Overview

Tcl Windows API V4.0 overview

DESCRIPTION

The Tcl Windows API (TWAPI) extension provides access to functions in the Windows API from within the Tcl scripting language.

The extension provides access to the Windows API at two levels:

  • a raw interface to the supported Windows API is provided where the Tcl commands directly map to Windows functions. Programmers who are familiar with the Win32 API and prefer to do things the hard way may prefer to use this interface.
  • a more convenient and powerful higher level interface that makes the API much more accessible. This is the interface documented in the remaining sections.

COPYRIGHT

Copyright © 2003-2013 Ashok P. Nadkarni


Packages and Loading - TWAPI packages

Packages and Loading

Tcl Windows API package description

DESCRIPTION

The entire TWAPI functionality is available through a single package: twapi. Alternatively, if you need only a small subset of the TWAPI commands, you can package require only that package.

For example,

package require twapi

will make commands from all modules available. On the other hand,

package require twapi_com

will only load the commands in the twapi_com package and the twapi_base package (which is always loaded).

In conjunction with the modular version of the TWAPI distribution, selectively loading modules allows you to only distribute the specific modules used by the application.

Commands

All commands installed by this extension fall under the twapi:: namespace. The commands are not exported from the namespace by default. To import the commands, they must first be exported by calling ::twapi::export_public_commands. Alternatively, you can call ::twapi::import_commands to import all TWAPI commands.

COPYRIGHT

Copyright © 2011-2012 Ashok P. Nadkarni


Installation and Usage - TWAPI Installation

Installation and Usage

Installation requirements and usage instructions

DESCRIPTION

System Requirements

The 32-bit builds of the TWAPI extension require

  • Windows XP or later,
  • Tcl version 8.5 or later.

The 64-bit builds of TWAPI require

  • Windows 2003 Server or later,
  • Tcl version 8.5 or later.
For Windows 2000, use TWAPI 3.0 or earlier. For Windows NT 4.0 (SP3 or later), use TWAPI 1.1.5 or earlier releases.

Distribution formats

The software is distributed in multiple forms (PLATFORM may be x86 or x64 for the 32- and 64-bit builds respectively):

  • A ZIP archive, "twapi-VERSION.zip", that includes the Tcl scripts in source form and is platform independent, containing both 32- and 64-bit DLLs. This is best suited for developers who might want access to the Tcl scripts during development.
  • A ZIP archive, "twapi-bin-VERSION.zip", in which the Tcl scripts are embedded within the DLL. This is also platform independent and simultaneously supports both 32- and 64-bit Tcl.
  • A ZIP archive, "twapi-modular-VERSION.zip", containing separate DLL's for each TWAPI module. This distribution is also platform independent and simultaneously supports both 32- and 64-bit Tcl.

Some factors to consider in choosing the distribution:

  • The "twapi-VERSION.zip" distribution includes the Tcl scripts as separate files. Depending on target audience, this may or may not be a good thing. It is also the smallest distribution as the Tcl scripts are shared between the 32- and 64-bit DLLs.
  • The "twapi-bin-VERSION.zip" distribution contains 32- and 64-bit DLL's with the scripts embedded. It is intended for deployment into standard Tcl installations where the script source is not required or desired. If shipping TWAPI as part of a tclkit/starkit/starpack, this distribution must be used. The other distributions will not work.
  • In the "twapi-modular-VERSION.zip" distribution, each TWAPI module is built as a separate component with the associated scripts embedded. It is not intended to be used as-is. Rather applications that need only a small subset of TWAPI commands can ship only those modules.

Installing TWAPI

To install any ZIP distribution, unzip it into a directory that is included in your Tcl auto_path variable. The ZIP distributions can be used by both 32-bit and 64-bit Tcl from the same location.

COPYRIGHT

Copyright © 2003-2013 Ashok P. Nadkarni


Win32 raw API - Windows API

Win32 raw API

Direct access to the Win32 API

DESCRIPTION

The Windows API may be directly accessed by Tcl commands that map to Windows functions. This interface is not documented in the TWAPI documentation. Refer to the Microsoft Windows SDK for a description of the functions and parameters.

It is recommended that the higher level documented TWAPI Tcl functions be used instead. These provide an easier and more flexible interface in addition to hiding platform-specific differences.

COPYRIGHT

Copyright © 2003-2010 Ashok P. Nadkarni


Base module - Base

Base module

Base module used by all TWAPI components

SYNOPSIS

package require twapi_base

cancel_wait_on_handle HANDLE
close_handle HANDLE
conceal PLAINTEXT
create_file PATH ?options?
credentials_dialog ?options?
debuglog ?MESSAGE?
debuglog_clear
debuglog_disable
debuglog_enable
debuglog_get
duplicate_handle HANDLE ?options?
expand_environment_strings STRING
export_public_commands
format_message ?options?
free_library HMODULE
get_build_config ?CONFIGKEY?
get_tcl_channel_handle CHANNEL DIRECTION
get_version ?-patchlevel?
hex32 INT32VAL
hex64 INT64VAL
import_commands
is_valid_sid_syntax sid
lambda ARGLIST BODY ?NAMESPACE?
large_system_time_to_secs_since_1970 SYSTEMTIMEVALUE ?BOOLEAN?
large_system_time_to_timelist SYSTEMTIMEVALUE
load_library FILEPATH ?options?
lookup_account_name name ?options?
lookup_account_sid sid ?options?
map_account_to_name ACCOUNT ?-system SYSTEMNAME?
map_account_to_sid ACCOUNT ?-system SYSTEMNAME?
map_windows_error ERRORCODE
new_uuid ?-localok?
nil_uuid
parseargs ARGLISTVAR OPTLIST ?-ignoreunknown? ?-nulldefault? ?-hyphenated? ?-maxleftover MAXLEFTOVER? ?-setvars?
random_bytes NUMBER
read_credentials ?options?
recordarray cell RECORDARRAY INDEX FIELD
recordarray column RECORDARRAY FIELD ?-filter FILTERLIST?
recordarray concat ?RECORDARRAY RECORDARRAY...?
recordarray fields RECORDARRAY
recordarray get RECORDARRAY ?options?
recordarray getdict RECORDARRAY ?options?
recordarray getlist RECORDARRAY ?options?
recordarray index RECORDARRAY INDEX ?options?
recordarray iterate ARRAYVAR RECORDARRAY ?options? BODY
recordarray range RECORDARRAY LOW HIGH
recordarray rename RECORDARRAY FIELDRENAMEMAP
recordarray size RECORDARRAY
rethrow
reveal ENCRYPTED
safearray TYPE LISTVALUE
secs_since_1970_to_large_system_time SECONDS
timelist_to_large_system_time TIMELIST
tclcast TYPE VALUE
tcltype VALUE
trap SCRIPT ?onerror ERRORPATTERN ERRORSCRIPT?... ?finally FINALSCRIPT?
wait_on_handle HANDLE ?options?
win32_error WINERROR ?MESSAGE?

DESCRIPTION

This module implements core commands required by all other TWAPI components and some functionality commonly required in all Windows application.

Package information

get_version returns TWAPI version information. export_public_commands and import_commands enable export and import of commands defined in the TWAPI namespace.

Handles

Several Win32 and TWAPI commands return operating system handles to various types of resources. The following commands allow manipulation and retrieval of information regarding handles.

The command create_file returns a handle to a file or device.

The operating system associated with a Tcl channel can be retrieved using the get_tcl_channel_handle command.

The command duplicate_handle can be used to duplicate a handle, for example to pass down to a child process with different access rights.

The command close_handle closes a operating system handle and frees resources associated with it.

An application can wait on a handle to be signalled using the wait_on_handle command. The wait can be cancelled by calling cancel_wait_on_handle command.

User Accounts

The twapi_base package includes some commonly used commands related to user accounts. The command lookup_account_name, map_account_to_name, lookup_account_sid and map_account_to_sid translate between user and group account names and their SID's. The command is_valid_sid_syntax validates the syntax of an SID.

A more complete set of commands related to accounts, credentials and security are in the twapi_account and twapi_security packages.

Password protection

Commands read_credentials, credentials_dialog and confirm_credentials allow interfacing to the Windows credentials manager and getting user credentials such as passwords from the user.

Passwords are sensitive data and need to be protected in memory. For example, in case of error exceptions being logged to file, plaintext passwords should not be exposed. The above commands return passwords in an encrypted form. TWAPI commands that deal with passwords expect them to be passed in this encrypted form. The conceal and reveal commands can also be used for this purpose. Note however using conceal is not as secure as the argument passed to it is still in clear text.

Writing to the Windows event log

Commands for writing to the Windows event log are included in the twapi_base package. Documentation for these is however part of the twapi_eventlog package.

Error generation and handling

The twapi_base module also provides various facilities for generating and handing errors and Tcl exceptions.

TWAPI generates Tcl exceptions when errors are encountered. Information pertaining to the error is stored in Tcl global variables as with any standard Tcl errors. The global variable errorInfo contains a traceback of the Tcl stack when the error occured. The global errorCode contains a list with additional information about the error. The first element is the error class and determines the format of the rest of the list. This may take one of the following values:

TWAPI_WIN32 | This error class corresponds to Windows error codes. The second element of the list is the integer Windows error code. The map_windows_error can be used to retrieve the correesponding text description. The third element is the corresponding localized text string describing the error. The fourth element is optional and its format is dependent on the specific error code. The command win32_error can be used to generate an error in this format.
TWAPI | This error class is used for non-Windows related errors, for example invalid options to commands. The format is similar to that of TWAPI_WIN32 except that the error code is an internal TWAPI error code and the text is not localized.

For handling errors, the command trap provides exception handling with finalization features.

For troubleshooting and debug purposes, TWAPI provides the debuglog command which writes to an internal log. This command is normally a no-op and must be enabled with debuglog_enable for logging to have effect. It can be disabled again with debuglog_disable. The current contents of the debug log can be retrieved with debuglog_get.

Record arrays

Some TWAPI commands return data in a form that is similar to a table with named columns. For example, the event tracing module returns a list of event trace records. The form of the returned data is called a record array and is intended to be opaque and manipulated through the recordarray command. The command takes various forms shown in the table below and is flexible enough to retrieve data as dictionaries or lists as well as support operations like filtering and column slicing.

recordarray cell | Returns the value in a specified field in a specific record.
recordarray column | Returns values for a specified field for all records.
recordarray concat | Returns a record array containing records from one or more record arrays.
recordarray fields | Returns field names for the records in the record array.
recordarray get | Returns another record array containing a subset of the records and fields.
recordarray getdict | Returns a dictionary containing a subset of the records and fields.
recordarray getlist | Returns a list containing a subset of the records and fields.
recordarray index | Returns the record at a specified position in list or dictionary format.
recordarray iterate | Iterates over the records in the record array.
recordarray range | Returns a new record array containing records in the specified range.
recordarray rename | Renames one or more fields in the record array.
recordarray size | Returns the number of records in the record array.
Many record array commands accept some of the following common options:

-filter FILTERLIST Specifies a list of matching filters. Only the records matching all the filter expressions in FILTERLIST are returned. FILTERLIST is a list of filter expressions. Each filter expression is a 3 or 4 element list consisting of a record field name, a matching operator, the value to match and optionally a fourth element -nocase which may be used with any of the string or pattern matching operators to indicate that character case should be ignored. The matching operator must be one of the following:

eq | String equality
ne | Strings inequality
~ | Pattern matched (as in string match)
!~ | Pattern not matched (as in string match)
== | Integer equality
!= | Integer inequality
< | Integer less than
<= | Integer less than or equal
> | Integer greater than
> | Integer greater than or equal

-format FORMAT Specifies the format of each record element returned. FORMAT may be one of the following values:

list | each record is returned as a list (default).
dict | each record is returned as a dictionary whose keys are the fields names of the record array.
flat | Field values of returned as a flat list. Only valid for the recordarray getlist command.

-slice FIELDLIST Specifies that the return value should only include the fields specified in FIELDLIST and in that order.
Here is an example that returns a plain list of PID of processes that have a privileged port (any port under 1024) open. get_tcp_connections returns a record array.

recordarray getlist [get_tcp_connections] -filter {{-localport < 1024}} -slice -pid -format flat

Another example, which shows all services that are marked as interacting with the desktop, returned as a dictionary keyed by the service name.

recordarray getdict [get_multiple_service_status] -filter {{interactive == 1}} -key name

Utility commands

parseargs parses an argument list based on specified options. The command expand_environment_strings replaces environment variables in a string with their values. format_message formats a operating system or application message.

Commands large_system_time_to_secs_since_1970, large_system_time_to_timelist, secs_since_1970_to_large_system_time and timelist_to_large_system_time convert between various time formats.

A Universally Unique Identifier (UUID) can be generated by the command new_uuid. A nil UUID can be generated by nil_uuid.

The commands load_library and free_library can be used to load and free DLL's.

The commands tclcast and tcltype are useful for manipulating internal Tcl value types. This is sometimes useful and required when dealing with external APIs and data formats like COM. hex32 and hex64 format numbers as fixed length hexadecimal strings. lambda returns an anonymous proc definition based on the Tcl apply command.

Commands

cancel_wait_on_handle HANDLE
Cancels any previously registered asynchronous wait on a handle that was registered using wait_on_handle.
close_handle HANDLE
Closes the operating system handle HANDLE. If the handle has been registered for asynchronous notifications via wait_on_handle, the notifications are canceled (via cancel_wait_on_handle).
conceal PLAINTEXT
Returns an encrypted binary string corresponding to PLAINTEXT. reveal can be used to decrypt the result.
create_file PATH ?options?
This is a thin wrapper around the Win32 CreateFile function that returns a handle to a file or device. The wrapper primarily provides mnemonics and defaults for the CreateFile parameters. PATH specifies the file or device path. Additional options and default values are shown below.

-access ACCESSRIGHTS | Specifies the desired access rights and may be specified as a list of integer access rights flags or symbols as described in Access Rights. Defaults to generic_read.
-createdisposition DISPOSITION | DISPOSITION must be one of create_always, create_new, open_always, open_existing or truncate_existing. Refer to the Windows SDK for the meaning. Defaults to open_always.
-flags FLAGS | An integer bit mask corresponding to the dwFlagsAndAttributes parameter to CreateFile function. See the Windows SDK for detail. Defaults to 0.
-inherit BOOL | If true, the returned handle is inheritable by child processes. Defaults to false.
-secd SECURITY_DESCRIPTOR | Specifies a security descriptor to be attached to the file or device if it has to be created. Defaults to a null security descriptor which results in the process' default security descriptor being applied.
-share | Specifies the sharing mode of the object. This is list containing zero or more of the constants read, write and delete that control what kind of shared access should be allowed while the file or device is open. Defaults to {read write delete}.
-templatefile | A handle to a template file with the GENERIC_READ access right from which file attributes and extended attributes are to be copied for the file that is being created. Defaults to NULL.
Refer to the Windows SDK for additional details.

credentials_dialog ?options?
Shows a dialog prompting the user for credentials. Returns a list of three elements, the user name, the password, and a boolean indicating whether the user selected for the credentials to be saved or not.

The following options may be specified:

-bitmap HANDLE | Specifies a hande to a bitmap to be displayed in the dialog.
-caption CAPTION | Specifies a caption to be displayed.
-expectconfirmation BOOLEAN | See read_credentials.
-forceui BOOLEAN | See read_credentials.
-message MESSAGE | Specifies a message to be displayed to the user.
-parent HWIN | Specifies the handle of a windows to be used as the parent for the dialog.
-password PASSWORD | See read_credentials.
-persist BOOLEAN | See read_credentials.
-showsaveoption BOOLEAN | See read_credentials.
-target TARGETNAME | See read_credentials.
-type TARGETTYPE | See read_credentials.
-username USERNAME | See read_credentials.
The command read_credentials provides a console version of this command.

debuglog ?MESSAGE?
Writes each specified argument as a message to an internal log. There is an internal limit on the number of messages stored. Older messages are discarded once the log reaches this limit. The command must be enabled with debuglog_enable for logging to have effect.
debuglog_clear
Clears the internal debug log.
debuglog_disable
Disables the debuglog command.
debuglog_enable
Enables the debuglog command.
debuglog_get
Returns the current content of the internal debug log.
duplicate_handle HANDLE ?options?
Duplicates an operating system handle. HANDLE may be either in the form returned by commands such as get_tcl_channel_handle or get_process_handle or may be an actual address (integer) literal corresponding to the handle. The following options specify the context of the handle and control attributes of the duplicated handle:

-access ACCESSRIGHTS | Specifies the access rights desired for the new handle. If unspecified, the new handle is created with the same access rights as the original one. ACCESSRIGHTS is a list of symbolic constants and bit masks as specified in Access Rights.
-closesource | If specified, HANDLE is closed after it is duplicated.
-inherit | If specified, the new handle marked as inheritable. By default, the duplicated handle cannot be inherited by child processes.
-sourcepid SOURCEPID | Specifies the PID of the process in whose context HANDLE is a valid handle. Defaults to the current process.
-targetpid TARGETPID | Specifies the PID of the process in whose context the new handle is to be created. Specifying this also impacts the format of the returned handle value.
If option -targetpid is not specified, the command returns the duplicated handle in symbolic form that can be passed to functions such as close_handle. If -targetpid is specified, the command returns the literal value of the handle. This is true even if the target PID is that of the current process.

expand_environment_strings STRING
Returns the string formed by replacing all environment variable references in STRING with their values. Environment variable references are in the form %ENVIRONMENTVAR%. References to undefined environment variables are not replaced.
export_public_commands
Export public commands in the twapi:: namespace. The commands in the twapi:: namespace are not exported by default.
format_message ?options?
Formats and returns a message string based on a format string. The format string may be directly supplied, obtained from a loaded library or module, or the system message tables. The format string may contain format insert specifiers of the form %N where N is a number between 1 and 99. The format specifier is replaced by the corresponding positional parameter. The format specifier %0 is treated specially as indicating that a newline character is not to be appended to the result. See FormatMessage in the Windows SDK for more details regarding this command including format specifiers. The command takes the following options:

-module MODULE | Specifies that the format string is to be loaded from the module identified by MODULE. MODULE may either be a handle returned from a command such as load_library or the path to a DLL. If this option is specified, options -messageid and -langid must also be specified. This option cannot be used with the -fmtstring option.
-fmtstring FORMATSTRING | Specifies that FORMATSTRING should be used as the format string for the message. Cannot be used with the -module option.
-messageid MESSAGEID | Specifies the message identifier of the format string. This option cannot be used with the -fmtstring option.
-langid LANGID | Specifies the language identifier to be used in constructing the message. This option cannot be used with the -fmtstring option.
-includesystem | Specifies that the system message tables should also be searched in addition to the message tables in the module specified by -module. This option cannot be used with the -fmtstring option.
-params PARAMLIST | Specifies a list of positional parameters that are to be used to replace the %N format insert sequences in the format string. If the number of parameters does not match the number of escape sequences, a Tcl exception may be generated.
-ignoreinserts | If specified, the %N format insert sequences are not replaced in the returned string.
-width MAXLINEWIDTH | If MAXLINEWIDTH is 0 (default), the returned string contains the same line breaks as in the original format string. The -width option may be used to control the maximum line width in the created message. If MAXLINEWIDTH is between 1 and 254, the command will insert line end characters at appropriate points in the message. In this case, line end characters in the original message are ignored. However, hard coded line end characters, specified as %n in the format string are kept. A MAXLINEWIDTH value of -1 also ignores line end characters while keeping the hard coded %n line end specifiers, but does not insert any line end characters to limit the line length and to terminate the message.
Warning: This command requires all insert placeholders to be strings. Decimal format specifiers such as %|u! will not result in the correct decimal value being inserted.

free_library HMODULE
Frees a loaded module. HMODULE must be a handle previously returned through load_library, get_module_handle or get_module_handle_from_address.
get_build_config ?CONFIGKEY?
If no arguments are specified, returns an dictionary that contains the TWAPI build configuration. If CONFIGKEY is specified, only returns the value for that configuration key. The build configuration keys are:

comobj_ootype | The underlying object system on which the TWAPI COM support is built.
compiler | The compiler used for the build (e.g. vc++)
compiler_version | The version of the build compiler.
opts | List of additional options used in the build.
platform | One of x86 or x64.
sdk_version | Version of the Windows SDK used for the build.
tcl_header_version | Version of the Tcl headers used for the build.
tea | Boolean indicating whether the build used Tcl Extension Architecture or native builds.

get_tcl_channel_handle CHANNEL DIRECTION
Returns the operating system handle corresponding to a Tcl channel identifier (for example, returned by the Tcl open command). If DIRECTION is write, the write-side handle is returned, otherwise the read-side handle is returned. (For many channel types, the two are identical.)
get_version ?-patchlevel?
Without any arguments, the command returns the major/minor TWAPI version number in the form MAJOR.MINOR. If the option -patchlevel is specified, the returned string includes patchlevel and release information similar to the Tcl info patchlevel command, for example, 1.0.2 for final release of version 1.0 patch 2, 1.0b3 for the third beta release of version 1.0 and 1.0a3 for the third alpha release of version 1.0.
hex32 INT32VAL
Returns INT32VAL as a fixed width hexadecimal string.
hex64 INT64VAL
Returns INT64VAL as a fixed width hexadecimal string.
import_commands
Imports all public commands in the twapi:: namespace into the caller's namespace.
is_valid_sid_syntax sid
Returns true or false depending on whether sid is a valid SID or not. Note this only checks the syntax of the SID, not whether it corresponds to a real account.
lambda ARGLIST BODY ?NAMESPACE?
Simple wrapper that returns an anonymous proc definition based on the Tcl apply command.
large_system_time_to_secs_since_1970 SYSTEMTIMEVALUE ?BOOLEAN?
Some Windows functions return time as the number of 100 nanosecond units since Jan 1, 1601. The command converts such time values to seconds since the epoch Jan 1, 1970. If BOOLEAN is false (default), an integral number of seconds is returned. Otherwise, the fractional part is also returned.
large_system_time_to_timelist SYSTEMTIMEVALUE
Some Windows functions return time as the number of 100 nanosecond units since Jan 1, 1601. The command converts such time values to a list of 8 elements representing the year, month, day, hour, minutes, seconds, milliseconds and day of week.
load_library FILEPATH ?options?
Loads a DLL and returns a handle to it. The handle must later be released by calling free_library, not close_handle. The following options may be specified:

-dontresolverefs | Normally, if the module being loaded is a DLL, the system will load any other modules referenced by it and also call its DllMain function to initialize it. If this option is specified, neither of these actions will be done.
-datafile | If specified, the module is loaded as a data file as opposed to an executable module. This is useful when the file is being loaded only to extract resources or format messages.
-alteredpath | Uses an alternative search strategy to find modules referenced by this module. See the Windows SDK for more details.

See LoadLibraryEx in the Windows SDK for more details regarding this command.

lookup_account_name name ?options?
name specifies the name of the account and may be fully qualified in the form domain\name.

If no options are specified, this command returns the SID for the account. If one or more options are specified, returns a flat list of the form "option1 value1 ...". The following options may be specified:

-all | Returns all values.
-sid | Returns the SID for the account.
-domain | Returns the domain in which the account was found.
-system | Specifies the name of the system on which the account is to be looked up. If unspecified, the local system is used.
-type | Returns the account type. This may be one of user, group (domain group), domain, alias (system local group), logonid, wellknowngroup, deletedaccount, invalid, unknown, computer or label. The logonid type is returned for SID's that identify a logon session.

lookup_account_sid sid ?options?
Argument sid specifies the SID of the account. If no options are specified, this command returns the name for the account. If one or more options are specified, the command returns a flat list of the form "option1 value1 ...". The following options may be specified:

-all | Returns all values.
-name | Returns the name for the account.
-domain | Returns the domain in which the account was found.
-system | Specifies the name of the system on which the account is to be looked up. If unspecified, the local system is used.
-type | Returns the account type. This may be one of user, group (domain group), domain, alias (system local group), wellknowngroup, deletedaccount, invalid, unknown, or computer.

map_account_to_name ACCOUNT ?-system SYSTEMNAME?
Returns the name for an account. If ACCOUNT is a valid account name, it is returned as is. Otherwise, it is assumed to be a SID and the corresponding account name is returned. An exception is raised if neither of these is true. The option -system may be used to specify a system as described in Standard Options.
map_account_to_sid ACCOUNT ?-system SYSTEMNAME?
Returns the SID corresponding to an account. If ACCOUNT is a SID, it is returned as is. Otherwise, it is assumed to be an account name and the corresponding SID is returned. An exception is raised if neither of these is true. The option -system may be used to specify a system as described in Standard Options.
map_windows_error ERRORCODE
Returns the text string corresponding to a Windows error code.
new_uuid ?-localok?
Returns a UUID. If the system does not contain a network card, the operating system may return an error as it cannot guarantee uniqueness across systems. Specifying the -localok option causes this to be ignored and a identifier value to be returned anyways.
nil_uuid
Returns a nil UUID.
parseargs ARGLISTVAR OPTLIST ?-ignoreunknown? ?-nulldefault? ?-hyphenated? ?-maxleftover MAXLEFTOVER? ?-setvars?
Parses the options specified in a list of arguments. ARGLISTVAR is the name of a variable in the caller's scope that contains a list of arguments. Option names are case-sensitive and begin with a - character. Option processing is terminated when an argument does not begin with a leading - or is one of the special - or --.

OPTLIST specifies the valid options allowed and is list of option specifiers. Each option specifier is a list of up to 3 elements and takes the following form:

OPTNAME?.OPTTYPE? ?DEFAULTVALUE ?VALUEOPTS??

OPTNAME is the name of the option (without a leading -) and is required. OPTTYPE should be separated from the name with a . and specifies the type of the option. It must have one of the following values: arg, bool, int, or switch. In the first three cases, the argument following the option is taken as the value of the option and must be of an appropriate type: an arbitrary string, a boolean value (0, 1, off, on, false, true) or an integer respectively. If the option type is switch, or is not specified at all, then the option is not associated with any value and is treated as a binary switch.

DEFAULTVALUE, specifies a default value to be assumed for the option if it is not present in ARGLISTVAR. This is ignored for options of type switch.

If VALUEOPTS is specified for option types arg or int, it is treated as a list of allowed values for the option. If an option's value is not in the list, the command will return an error. If the option type is bool or switch, VALUEOPTS is the treated as the value to return when the value of the option is boolean true (by default 1 is returned). This is commonly used in TWAPI to return a integer bit mask for the true value of an option.

If the option -setvars is not specified, the command returns a list of the form OPTION VALUE OPTION VALUE.... If the -hyphenated option is not specified, the OPTION fields in the returned value contain the option name without a leading - character. If the -hyphenated option is specified, OPTION includes the leading - character. This is useful when options are passed through to other commands after partial processing.

If the option -setvars is specified, the command sets variables with the names of the specified options to the corresponding values. The command returns an empty string in this case.

If the -nulldefault option is not present, only options that are present in ARGLISTVAR, or have a default value specified, or are of type switch are included in the returned result. If the -nulldefault option is present, then the returned list also includes values for options that are not present - 0 for options of type int and bool, and an empty string for arguments of type arg.

As a side effect, the variable ARGLISTVAR is modified to remove the parsed options and associated values. If the -maxleftover option is specified, the command will raise a Tcl error if the number of arguments left over after parsing the options is more than MAXLEFTOVER.

The command will normally generate a Tcl error if the arguments include an unknown option (an argument that begins with a - character and is not in OPTLIST). If the -ignoreunknown option is specified to the command, unknown options in ARGLISTVAR are ignored instead of an error being generated and are not removed from ARGLISTVAR.
random_bytes NUMBER
Returns the specified number of random bytes. This is a call into the RtlGenRandom Win32 API.
read_credentials ?options?
Prompts the user for credentials via the console. Returns a list of three elements, the user name, the password, and a boolean indicating whether the user selected for the credentials to be saved or not.

The following options may be specified:

-expectconfirmation | option lets the manager know the application will call confirm_credentials after verifying credentials. If false, the credentials manager will not hold on to the credentials and confirm_credentials need not be called. Generally, if -persist is specified as true, this option should also be specified as true and confirm_credentials called after verifying the credentials.
-forceui BOOLEAN | If specified as true, the user is prompted even if the credentials manager already has the requested credentials. Default is false.
-password PASSWORD | The password to be used as default. PASSWORD must be in the form accepted by reveal which is also the form returned by this command. Plain text passwords are not supported by this command.
-persist BOOLEAN | If true, credentials are to be persisted by the credentials manager if so desired by the user. Default is false.
-showsaveoption BOOLEAN | Specifies whether the user should be given the option to save the credentials. Defaults to true (meaning user is given the choice). If specified as false, credentials are persisted depending on the -persist option.
-target TARGETNAME | Name of the target for the credentials, for example the server name. This is used as the key when retrieving credentials.
-type TARGETTYPE | Specifies the type of credentials. TARGETTYPE must be generic (default) or domain.
-username USERNAME | The user name to display as the default. Defaults to the empty string.
-expectconfirmation BOOLEAN | The credentials manager can persist credentials that are valid so they can be returned later without prompting the user. The application needs to inform it whether the returned credentials are valid or not by calling confirm_credentials. When true,
The command credentials_dialog provides a GUI version of this command.

recordarray cell RECORDARRAY INDEX FIELD
Returns the value of the field FIELD of the record at index INDEX in the specified record array.
recordarray column RECORDARRAY FIELD ?-filter FILTERLIST?
Returns a list of values of the field FIELD in all records. If option -filter is specified only the values from the matching records are included in the returned list. See Record arrays for the format of FILTERLIST.
recordarray concat ?RECORDARRAY RECORDARRAY...?
Returns a record array containing records from one or more record arrays. The fields in each record array must be the same.
recordarray fields RECORDARRAY
Returns field names for the records in the record array.
recordarray get RECORDARRAY ?options?
Returns a record array containing a subset of the records and fields from RECORDARRAY. options may be include -filter and -slice from amongst the standard options described in Record arrays. Other options are silently ignored.
recordarray getdict RECORDARRAY ?options?
Returns a dictionary containing a subset of the records and fields from RECORDARRAY. The keys of the dictionary are specified through option -key the value for which must be the name of a field in the dictionary. If the option is not specified, the first field in the record definition for the record array is used as the key. options may include any of the standard options described in Record arrays.
recordarray getlist RECORDARRAY ?options?
Returns a list containing a subset of the records and fields from RECORDARRAY. The form and content of the elements of the returned list depend on the options as described in Record arrays.
recordarray index RECORDARRAY INDEX ?options?
Returns the record at a specified position in the record array. The options -format and -slice as described in Record arrays control the fields returned and their format.
recordarray iterate ARRAYVAR RECORDARRAY ?options? BODY
Iterates over all records in a recordarray. For each record, sets the array variable ARRAYVAR to the current record and evaluates BODY in the caller's context. The keys of ARRAYVAR are the field names of the record array.

options may include the -slice and -filter options as described in Record arrays.
recordarray range RECORDARRAY LOW HIGH
Returns a new record array containing the records in the specified index range.
recordarray rename RECORDARRAY FIELDRENAMEMAP
Returns a new record array with the same records as RECORDARRY but with the fields renamed as per the contents of the dictionary FIELDRENAMEMAP which should map the old field name to a new one. Names of any fields not in FIELDRENAMEMAP are preserved.
recordarray size RECORDARRAY
Returns the number of records in the record array.
rethrow
Raises a Tcl error where the error options, including values of errorCode and errorStack, are the same as when an exception was raised inside a trap command. This command can only be used inside a onerror clause of a trap and is useful to regenerate the original error when the error handler cannot handle the exception.
reveal ENCRYPTED
Decrypts a binary string that was encrypted by conceal.
safearray TYPE LISTVALUE
Returns LISTVALUE in a form that is interpreted by COM related commands as a single-dimensioned safearray of type TYPE. TYPE must be one of the COM types bool, int or i4, double or r8, bstr, or variant.
secs_since_1970_to_large_system_time SECONDS
This command converts SECONDS which is the number of seconds since the epoch Jan 1, 1970 to the number of 100 nanoseconds since Jan 1, 1601.
timelist_to_large_system_time TIMELIST
Converts TIMELIST to the number of 100 nanoseconds since Jan 1, 1601. If TIMELIST is an empty list, it defaults to the current date and time. Otherwise it is a list of 3-7 elements that specify the year, month, day, hours, minutes, seconds and milliseconds. The last four are optional and default to 0. TIMELIST must be a list of 7 elements representing the year, month, day, hour, minutes, seconds and milliseconds.
tclcast TYPE VALUE
Returns VALUE whose internal Tcl type is set to TYPE. See Controlling Parameter Types for a use case. TYPE must be one of empty, null (corresponding to COM VARIANT types VT_EMPTY and VT_NULL), or one of the Tcl internal types int, boolean, double, string, list, or dict.
tcltype VALUE
Returns the internal Tcl type for a value.
trap SCRIPT ?onerror ERRORPATTERN ERRORSCRIPT?... ?finally FINALSCRIPT?
The command executes SCRIPT in the caller's context. If the script completes without generating any Tcl exceptions, the command executes the script FINALSCRIPT if specified. The result of the command is the result of SCRIPT.

If SCRIPT generates any errors, the command matches the Tcl global ::errorCode variable against each specified ERRORPATTERN in turn. When the first match is found, the corresponding ERRORSCRIPT is executed. Then FINALSCRIPT is executed if specified. The return value from the command is the result of the executed ERRORSCRIPT script.

If the none of the ERRORPATTERN arguments match when an error occurs in SCRIPT, the command executes FINALSCRIPT if specified, and then regenerates the original error.

Each ERRORPATTERN should be a list and is matched against the first (facility) and second (code) elements of ::errorCode. If ERRORPATTERN is empty, it matches any value of ::errorCode. If ERRORPATTERN contains only one element, it is matched against the first element of ::errorCode with the second field of ::errorCode not used for matching. When matching against the second element of ::errorCode, first a exact string match is tried and if that fails, an integer match is tried if both operands being compared are valid integers.

Within an onerror clause, the command rethrow may be used to raise the error that was caught by the clause. This is useful when an error handler finds it cannot handle the case and wants to raise the original error. Similarly, the trapresult and trapoptions commands can be used in a onerror clause to retrieve the error message and error options dictionary captured by the onerror clause.
wait_on_handle HANDLE ?options?
The command waits on the specified HANDLE until it is either signalled or a timeout expires. The command can also be used for non-blocking asynchronous notification. HANDLE may be any operating system handle for which Windows supports the WaitForSingleObject API.

The command may return one of the following values if the -async option is not specified: signalled, timeout, abandoned. If -async is specified, the command returns an empty string and the result is passed to the callback script instead.

The following options may be specified:

-wait MILLISECS | Specifies the number of number of milliseconds to wait for the handle to be signalled. The default is -1 which indicates no timeout.
-async SCRIPT If specified, the command returns immediately. SCRIPT is then invoked when the handle is signalled or the timeout specified through -wait has elapsed. Note that if a timeout is specified with the -wait option, the timeout does not cancel the wait and the script is invoked repeatedly every MILLISECONDS if the handle is not signalled.

Two additional arguments are appended to SCRIPT - HANDLE and the return value (signalled etc.). Once a handle is registered for asynchronous notification, it must not be used for synchronous notification unless the asynchronous notification is first canceled through the cancel_wait_on_handle command. If the handle was already registered for asynchronous notification, the previously registered script is replaced with SCRIPT.
-executeonce BOOLEAN | If this option is specified as true, the SCRIPT is executed only once, even if the object HANDLE stays in a signalled state. Default is false. This option is ignored if -async is not specified.

win32_error WINERROR ?MESSAGE?
Generates a Tcl exception corresponding to the Windows error code WINERROR. MESSAGE may be specified as the error message in which case the system error message for WINERROR is appended to it.

COPYRIGHT

Copyright © 2004-2012 Ashok P. Nadkarni


Window management - Window management

Window management

Commands related to management of windows

SYNOPSIS

package require twapi_ui

arrange_icons ?HWIN?
close_window HWIN ?-wait MILLISECONDS?
configure_window_titlebar HWIN ?options?
disable_window_input HWIN
enable_window_input HWIN
find_windows ?options?
flash_window HWIN ?options?
flash_window_caption HWIN ?-toggle?
get_active_window_for_current_thread TID
get_active_window_for_thread TID
get_caret_blink_time
get_caret_location
get_child_windows HWIN
get_color_depth ?HWIN?
get_descendent_windows HWIN
get_desktop_window
get_desktop_wallpaper
get_desktop_workarea
get_display_devices
get_display_monitor_from_point X Y ?-default DEFAULTMONITOR?
get_display_monitor_from_rect RECT ?-default DEFAULTMONITOR?
get_display_monitor_from_window HWIN ?-default DEFAULTMONITOR?
get_display_monitors ?-device DEVICENAME? ?-activeonly?
get_display_monitor_info HMONITOR
get_display_size
get_first_child HWIN
get_first_sibling_window HWIN
get_focus_window_for_thread TID
get_foreground_window
get_last_sibling_window HWIN
get_multiple_display_monitor_info
get_next_sibling_window HWIN
get_owner_window HWIN
get_parent_window HWIN
get_prev_sibling_window HWIN
get_shell_window
get_toplevel_windows ?-pids PIDLIST?
get_window_application HWIN
get_window_at_location X Y
get_window_class HWIN
get_window_client_area_size HWIN
get_window_coordinates HWIN
get_window_id HWIN
get_window_long HWIN INDEX
get_window_process HWIN
get_window_real_class HWIN
get_window_style HWIN
get_window_text HWIN
get_window_thread HWIN
get_window_userdata HWIN
hide_caret
hide_owned_popups HWIN
hide_window HWIN ?-sync?
invalidate_screen_region ?options?
maximize_window HWIN ?-sync?
minimize_window HWIN ?options?
move_window HWIN X Y ?-sync?
redraw_window HWIN ?-force?
redraw_window_frame HWIN
resize_window HWIN W H ?-sync?
restore_window HWIN ?options?
set_active_window_for_thread HWIN
set_caret_blink_time MILLISECONDS
set_caret_location POINT
set_desktop_wallpaper PATH ?-persist?
set_focus HWIN
set_foreground_window HWIN
set_window_long HWIN INDEX VALUE
set_window_style HWIN style exstyle
set_window_text HWIN TEXT
set_window_userdata HWIN INTEGER
set_window_zorder HWIN POS
show_caret
show_owned_popups HWIN
show_window HWIN ?options?
tkpath_to_hwnd TKPATH
window_exists HWIN
window_input_enabled HWIN
window_is_child PARENTHWIN CHILDHWIN
window_maximized HWIN
window_minimized HWIN
window_visible HWIN
window_unicode_enabled HWIN

DESCRIPTION

This package provides procedures related to window management on Windows platforms.

Window Management

Windows are identified using window handles. A window handle consisting of an empty string represents an invalid or non-existent window when returned from a command. The command tkpath_to_hwnd returns the window handle corresponding to a Tk window.

The commands get_toplevel_windows, get_descendent_windows and get_child_windows enumerate the windows on the system. get_desktop_window and get_shell_window return handles to the desktop window and the shell window respectively. find_windows returns a list of windows that satisfy matching multiple matching criteria. The command window_exists can be used to check if a specific window exists.

The commands get_parent_window, get_owner_window, get_first_child, get_next_sibling_window, get_prev_sibling_window, get_first_sibling_window, get_last_sibling_window retrieve handles to windows with the appropriate relationship to the specified window. The command window_is_child can be used to check parent-child relationships between windows.

The commands get_window_process and get_window_thread retrieve the process and thread respectively that own the specified window. get_window_application returns the application instance for the specified window.

The commands get_foreground_window, set_foreground_window and set_window_zorder deal with the position of windows in the display Z-order.

The commands show_window, hide_window, restore_window, minimize_window, maximize_window, show_owned_popups, and hide_owned_popups control the visibility of windows. The commands window_minimized, window_maximized, window_visible check the visibility state of a window. close_window closes the specified window.

The commands get_window_style, set_window_style, get_window_class, get_window_real_class, get_window_long, set_window_long get_window_userdata and set_window_userdata retrieve and modify various attributes associated with windows.

The visibility and buttons displayed on the title bar of a window can be controlled through the command configure_window_titlebar.

The command get_window_id returns the window id of the specified window.

redraw_window and redraw_window_frame cause the window and the frame of a window to be redrawn respectively.

The commands move_window, resize_window and arrange_icons can be used to position and resize windows. The commands get_window_client_area_size and get_window_coordinates can be used to get window location and size. The command get_window_at_location returns the window at a given screen location.

The commands set_active_window_for_thread, get_active_window_for_thread, get_focus_window_for_thread, get_active_window_for_current_thread deal with the active window state and focus for a particular thread.

The commands enable_window_input, disable_window_input and set_focus deal with controlling input to windows. The command window_input_enabled can be used to check if input to a window is enabled or not. window_unicode_enabled checks if a window is Unicode-enabled or not.

The command flash_window can be used to grab the user's attention by flashing a window or taskbar icon.

The commands get_window_text and set_window_text retrieve and modify the title bar of a window or the text associated with a control. In the latter case, only controls in the same application are supported.

The commands get_caret_blink_time, set_caret_blink_time, hide_caret, show_caret, get_caret_location and set_caret_location allow manipulation of the caret and its position.

The command get_desktop_workarea returns the actual usable desktop area (not used by the taskbar etc.). get_color_depth returns the color depth of the display.

The commands get_desktop_wallpaper and set_desktop_wallpaper can be used to manipulate the wallpaper setting for the desktop.

Displays

Command get_display_devices returns a list of display devices in the system. Command get_display_monitors returns a list of monitors in the system. The command get_display_size returns the size of the display.

The monitor corresponing to a window, virtual screen coordinates or virtual screen rectangle be obtained from get_display_monitor_from_window, get_display_monitor_from_point, get_display_monitor_from_rect respectively.

The command get_display_monitor_info returns location and attributes of a specific display monitor. get_multiple_display_monitor_info returns the same information for all display monitors in the system.

Commands

arrange_icons ?HWIN?
Arranges all the minimized (iconized) child windows of the specified window. If HWIN is not specified, it defaults to the desktop window. The command returns the height of one row of icons.
close_window HWIN ?-wait MILLISECONDS?
Closes the window specified by HWIN. The option -wait can be specified to indicate the command should wait for MILLISECONDS ms for the window to actually close. By default, the command will wait for 10ms. Specify MILLISECONDS as 0 to return immediately without waiting. The command returns 1 if the window is closed and 0 otherwise. Note the latter is not an error as the window might have processed the close message yet.
configure_window_titlebar HWIN ?options?
Configures the title bar of the specified window to show or hide specific buttons. The following options control what buttons are displayed. If a particular option is not specified, the corresponding button is unaffected. Note however that the minimize, maximize and context help buttons are shown only if the system menu is also visible. Also, the minimize and maximize buttons are hidden and displayed as a single group. If one is configured to be hidden and the other is not, both buttons are shown but the hidden one is disabled.

visible BOOLEAN | Controls whether the title bar is displayed.
sysmenu BOOLEAN | Controls whether the system menu button is displayed.
minimizebox BOOLEAN | Controls whether the minimize button is displayed.
maximizebox BOOLEAN | Controls whether the maximize button is displayed.
contexthelp BOOLEAN | Controls whether the context help button is displayed.

disable_window_input HWIN
Disables mouse and keyboard input to the specified window. Returns 1 if the window was previously disabled, else 0.
enable_window_input HWIN
Enables mouse and keyboard input to the specified window. Returns 1 if the window was previously disabled, else 0.
find_windows ?options?
Returns a list of handles corresponding to all windows that match the specified criteria. If the -single option is specified, the return value is a window handle, not a list containing the window handle.

The options below control the matching criteria. Note that the boolean options work in tri-state fashion. If the option is not specified, then the corresponding window attribute is not used in the matching at all. If the option value is specified as true, then only windows having that attribute are selected. If the option value is false, only windows without that attribute are selected.

-ancestor HWIN | The window with handle HWIN must be an ancestor of the window.
-caption BOOLEAN | The window must or must not have a caption/title bar depending on whether BOOLEAN is true or false.
-child BOOLEAN | The window must or must not be an child window depending on whether BOOLEAN is true or false.
-class CLASS | The window must belong to the specified class.
-match MATCHTYPE | Specifies the method used for matching PATTERN in the -text option. This may be one of string for an straight character match, glob for matching as in the string match command or regexp for regular expression based matching. In all cases, the comparisons are case-insensitive.
-maximize BOOLEAN | The window must or must not be maximized depending on whether BOOLEAN is true or false.
-maximizebox BOOLEAN | The window must or must not have a maximize box on the title bar depending on whether BOOLEAN is true or false.
-messageonlywindow BOOLEAN | The window must or must not be a message-only window depending on whether BOOLEAN is true or false.
-minimize BOOLEAN | The window must or must not be minimized depending on whether BOOLEAN is true or false.
-minimizebox BOOLEAN | The window must or must not have a minimize box on the title bar depending on whether BOOLEAN is true or false.
-overlapped BOOLEAN | The window must or must not be an overlapped window depending on whether BOOLEAN is true or false.
-pids PIDLIST | The window must be owned by a process whose id is in PIDLIST.
-popup BOOLEAN | The window must or must not be an popup window depending on whether BOOLEAN is true or false.
-single | Returns the first window found without looking for additional windows. The return value from the command is the window itself, not a list containing the window.
-style STYLE | The window must have the specified style. STYLE must be specified as a list of two integer values corresponding to the style and extended style for the window. See get_window_style.
-text PATTERN | The text associated with the window (generally the window title) must match PATTERN. The matching is done based on the -match option.
-toplevel BOOLEAN | The window must or must not be a toplevel window depending on whether BOOLEAN is true or false.
-visible BOOLEAN | The window must be visible if BOOLEAN is true and hidden if it is false.

flash_window HWIN ?options?
Flashes the window's caption bar or taskbar icon. The following options control the type and nature of the flash.

-count COUNT | Indicates the number of times the window or icon is to be flashed (default is 1).
-nocaption | If specified, the window caption is not flashed.
-notaskbar | If specified, the taskbar icon is not flashed.
-period MILLISECONDS | The period of the flash in milliseconds. Defaults to the system cursor blink rate.
-start | Indicates the window should be continously flashed until stopped by another call to this command with the -stop option.
-stop | Stops any ongoing flashing of the window. Specifying this option will cause all other options to be ignored.
-untilforeground | Indicates the window should be continuously flashed until brought to the foreground. NOTE: Some Windows versions have a bug that results in the window being flashed just once.

flash_window_caption HWIN ?-toggle?
This command is obsolete. Use flash_window instead.
get_active_window_for_current_thread TID
Returns the current active window for the current thread. If the thread does not have a active window, returns $twapi::null_hwin.
get_active_window_for_thread TID
Returns the current active window for the thread with id TID. If the thread does not have a active window, returns $twapi::null_hwin.
get_caret_blink_time
Returns the blink time of the caret in milliseconds.
get_caret_location
Returns a list of two integers specifying the caret's coordinates. These are always with respect to the client area of the window that owns the caret.
get_child_windows HWIN
Returns a list of handles to all windows that are immediate child windows of the specified window.
get_color_depth ?HWIN?
Returns the number of bits per pixel in the device context of the window identified by HWIN. If HWIN is not specified, the color depth of the entire screen is returned.
get_descendent_windows HWIN
Returns a list of handles to all descendent windows of the specified window.
get_desktop_window
Returns a handle to the desktop window.
get_desktop_wallpaper
Returns the path to the file containing the current wallpaper for the desktop or an empty string if no wallpaper is in use.
get_desktop_workarea
Returns the screen coordinates of the usable area of the desktop as a list of four integers corresponding to the left, top, right and bottom coordinates on the display. The usable area is that area that is not covered by the taskbar and any application desktop toolbars.
get_display_devices
Returns a list of display devices in the system. Each element in the list is a keyed list of key value pairs with the following fields:

-description | A string describing the device.
-desktop | If the value is true, the device is attached to the desktop.
-disconnect
-flags | An integer value containing the device flags. These are also returned as the boolean fields described here.
-id | The value is the device id for the device.
-key | The registry key for the device.
-mirroring | If true, the device is a mirroring pseudo driver such as that used for NetMeeting.
-modespruned | If true, not all the device modes are supported by its output.
-multidriver
-name | The device name.
-primary | If true, the primary desktop is displayed on this device.
-remote
-removable | If true, the device is removable.
-vgacompatible | If true, the device is VGA compatible.

get_display_monitor_from_point X Y ?-default DEFAULTMONITOR?
Returns a handle to the monitor corresponding the virtual screen coordinates (X,Y). If the coordinates lie outside the extents of any monitor, the command will generate an error unless the -default option is specified. If -default is specified with a value of primary, then a handle to the primary display monitor is returned. If the value is nearest, the handle of the monitor whose extent is closest to the screen coordinates is returned.

Note that the returned monitor handle is not a Win32 handle and should not be closed.
get_display_monitor_from_rect RECT ?-default DEFAULTMONITOR?
Returns a handle to the monitor that has the largest area of intersection with the rectangle specified by RECT. RECT indicates a virtual screen region and should be specified as a list of four integers indicating the coordinates of the left, top, right, bottom edges. If the rectangle does not intersect any monitor, the command will generate an error unless the -default option is specified. If -default is specified with a value of primary, then a handle to the primary display monitor is returned. If the value is nearest, the handle of the monitor whose extent is closest to the rectangle is returned.

Note that the returned monitor handle is not a Win32 handle and should not be closed.
get_display_monitor_from_window HWIN ?-default DEFAULTMONITOR?
Returns a handle to the monitor on which the window identified by HWIN is displayed. If the window is not displayed on any monitor, because it is iconified or is placed outside of any monitor extents for example, the command will generate an error unless the -default option is specified. If -default is specified with a value of primary, then a handle to the primary display monitor is returned if the window is not currently displayed. If the value is nearest, the handle of the monitor whose extent is closest to the window is returned.

Note that the returned monitor handle is not a Win32 handle and should not be closed.
get_display_monitors ?-device DEVICENAME? ?-activeonly?
Returns a list of display monitors in the system. If -device is specified, only monitors attached to the device with name DEVICENAME are returned. If -activeonly is specified, only monitors marked as active are returned.

Each element in the returned list is a keyed list of key value pairs with the following fields:

-active | The monitor is active.
-attached
-description | A string describing the device.
-flags | An integer value containing the display monitor flags. These are also returned as the boolean fields described here.
-id | The value is the device id for the device.
-key | The registry key for the device.
-name | The monitor name.

get_display_monitor_info HMONITOR
Returns information about the display monitor identified by HMONITOR which is a monitor handle. The following fields are returned in a keyed list:

-extent | A list of four integers indicating the monitor extent corresponding to the left, top, right and bottom edges of the monitor's display area in virtual screen coordinates.
-name | The name identifying the display monitor.
-primary | A boolean indicating whether the monitor is the primary display monitor.
-workarea | A list of four integers indicating the usable monitor extent corresponding to the left, top, right and bottom edges of the monitor's display area in virtual screen coordinates excluding any space taken up by desktop toolbars and the taskbar.

get_display_size
Returns a list of two integers specifying the width and height of the display.
get_first_child HWIN
Returns a handle to the child window of the specified window that is the first (highest) in the display Z-order.
get_first_sibling_window HWIN
Returns a handle to a sibling window (ie. having the same parent) of the specified window that is the highest in the display Z-order.
get_focus_window_for_thread TID
Returns the window which has the focus the thread with id TID. If the thread does not have a active window, returns $twapi::null_hwin.
get_foreground_window
Returns the current foreground window on the desktop.
get_last_sibling_window HWIN
Returns a handle to a sibling window (ie. having the same parent) of the specified window that is the lowest (least visible) in the display Z-order.
get_multiple_display_monitor_info
Returns a list containing information for every monitor in the system. The information is in the same format as that returned by get_display_monitor_info.
get_next_sibling_window HWIN
Returns a handle to a sibling window (ie. having the same parent) of the specified window that is next in the display Z-order.
get_owner_window HWIN
Returns a handle to the owner window of the specified window or null handle if the window does not have a owner.
get_parent_window HWIN
Returns a handle to the parent window of the specified window.
get_prev_sibling_window HWIN
Returns a handle to a sibling window (ie. having the same parent) of the specified window that is previous (immediately higher) in the display Z-order.
get_shell_window
Returns a handle to the Windows shell process' window.
get_toplevel_windows ?-pids PIDLIST?
Returns a list of handles to toplevel windows in the system. If no options are specified, this includes all toplevel windows. If the -pids option is specified, then only toplevel windows owned by the process with one of the PID's in PIDLIST are returned.
get_window_application HWIN
Returns the application instance associated with the specified window.
get_window_at_location X Y
Returns the highest window in the X-order that contains the screen coordinates (X,Y). Windows that are disabled or hidden are not ignored.
get_window_class HWIN
Returns the class of a window. This is simple wrapper around the GetClassName Windows function.
get_window_client_area_size HWIN
Returns a list of two integers containing the width and height in pixels of the client area of the window.
get_window_coordinates HWIN
Returns the screen coordinates of the window as a list of four integers corresponding to the left, top, right and bottom sides of the window.
get_window_id HWIN
Returns the window id of the specified window. Note that this is different than the window handles.
get_window_long HWIN INDEX
This is a direct call to the GetWindowsLong function. Refer to Windows SDK documentation for details. Several other TWAPI functions act as wrappers provide more straightforward access to the values retrieved by this function.
get_window_process HWIN
Returns the id of the process that owns the specified window.
get_window_real_class HWIN
Returns the real class of a window for classes that are wrapped by applications into their own set of classes. This is simple wrapper around the RealGetWindowClass Windows function. Windows function.
get_window_style HWIN
Returns a list containing the style and the extended style bits respectively followed by symbolic window style attributes corresponding to the style bits. The window styles attributes that may be returned are shown below. Refer to the Windows SDK documentation for the meaning of these styles.

overlapped | The window is an overlapped window - this is a toplevel window without a parent. This attribute is mutually exclusive with popup and child.
popup | The window is popup window like a dialog box. This attribute is mutually exclusive with overlapped and child.
child | The window is the child of some other window. This attribute is mutually exclusive with popup and overlapped.
caption | The window has a caption or title bar and a border.
border | The window has a normal border and no title bar.
dlgframe | The window has a double border as used for dialogs and no title bar.
dlgmodalframe | The window has a double border as used for a dialog and may have a caption as well.
minimize | The window is minimized. Windows with neither minimize or maximize attributes are normal windows.
minimizebutton | The window has a minimize button on the title bar.
maximize | The window is maximized. Windows with neither minimize or maximize attributes are normal windows.
maximizebutton | The window has a maximize button on the title bar.
visible | The window is visible. If this attribute is not present, the window is hidden.
disabled | The window is disabled and does not accept input.
clipsiblings | Indicates that the screen area occupied by sibling windows that overlap will not be overwritten when the window is drawn.
clipchildren | Indicates that the screen area occupied by child windows will not be overwritten when the window is drawn.
vscroll | The window displays a vertical scrollbar.
hscroll | The window displays a horizontal scrollbar.
sysmenu | The window displays a system menu.
thickframe | The window has a thick border that allows for resizing.
noparentnotify | The window is a child window that does not send WM_PARENTNOTIFY messages to its parent.
topmost | The window is a topmost window that is displayed above all non-topmost windows even when it is not active.
acceptfiles | The window accepts files that are dragged and dropped into it.
transparent | The window is transparent and does not obscure windows below it.
mdichild | The window is an MDI child window.
toolwindow | The window is a floating toolbar. The title bar and caption are shrunk. The window does not appear in the task bar and will not show up with the ALT-TAB hotkey.
windowedge | The window has a border with a raised edge.
clientedge | The window has a border with a sunken edge.
contexthelp | The window has a context help button in the caption bar.
controlparent | The window allows navigation between child windows using the TAB key.
staticedge | The window has a 3-D border.
appwindow | The window is forced on the task bar when visible. Note that this does not mean that windows without this attribute will not show up on the task bar. It does mean that windows with this attribute will definitely show up on the task bar.

get_window_text HWIN
Gets the title of a window or the text associated with a control. In the latter case, the control must belong to the same application.
get_window_thread HWIN
Returns the id of the thread that owns the specified window.
get_window_userdata HWIN
Returns the longword associated as user data with the specified window. This maps to the Windows GetWindowLong call with an argument of GWL_USERDATA.
hide_caret
Hides the caret. Note that calls to hide_caret or twapi::HideCaret must be matched by an equivalent number of calls to show_caret or twapi::ShowCaret.
hide_owned_popups HWIN
Hides all popup windows that are owned by the specified window.
hide_window HWIN ?-sync?
Hides the specified window so it does not appear on the display or as an icon. If option -sync is specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.

Returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.
invalidate_screen_region ?options?
Marks a region of the screen as invalid. If no options are specified, all windows are marked invalid, forcing them to be redrawn. The following options may be used with the command:

-hwin HWIN | Indicates the specific window whose client region is to be invalidated.
-rect RECT | If specified, this should be a list of four integers indicating the coordinates of the left, top, right, bottom sides of the region in the window's client area that is to be invalidated. If unspecified or an empty list, the entire client region is marked invalid.
-bgerase | If specified, the background within the invalidated region is erased. Otherwise, it remains unchanged.

maximize_window HWIN ?-sync?
Maximizes the specified window. If option -sync is specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.

The command returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.
minimize_window HWIN ?options?
Minimizes the specified window.

-sync | If specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.
-activate | If specified, in addition to being shown, the window is also activated.
-shownext | If specified, the next window in the Z-order is activated.
The command returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.

move_window HWIN X Y ?-sync?
Moves the specified window such that it's left side is at position X and its top side is at position Y. The window is moved asynchronously unless the -sync option is specified. Note that in this case, the command will never return if the target window is hung.
redraw_window HWIN ?-force?
This command causes the invalidate regions of the specified window to be redrawn. If -force is specified, the entire window is redrawn.
redraw_window_frame HWIN
This command causes the frame of the specified window to be redrawn.
resize_window HWIN W H ?-sync?
Resizes the specified window to be W pixels in width and H pixels in height. The resizing is done asynchronously unless the -sync option is specified. Note that in this case, the command will never return if the target window is hung.
restore_window HWIN ?options?
Restores a window to its original size and position if it is maximized or minimized. The command returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.

-sync | If specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.
-activate | In addition to being shown, the window is also activated.

set_active_window_for_thread HWIN
Sets the specified window to be the active window for its owning thread. The window is brought to the foreground if the owning thread belongs to the foreground application. Returns the handle of the window that was previously active.
set_caret_blink_time MILLISECONDS
Sets the blink time of the caret to MILLISECONDS milliseconds.
set_caret_location POINT
Sets the caret's location to POINT which must be a list of two integers specifying the caret's coordinates.
set_desktop_wallpaper PATH ?-persist?
Sets the desktop wallpaper to that specified by the file PATH. On Vista and later systems, the file may be in BMP or JPG format. Older Windows systems only support BMP format.

If PATH is specified as an empty string or none, no wallpaper is displayed on the desktop. If PATH is default, the default wallpaper is restored to the desktop. If the option -persist is specified, the new setting is written to the user's profile. Note that if the system is not currently configured to display a wallpaper, the desktop is not updated immediately unless the -persist flag is also specified.
set_focus HWIN
Sets the focus to the specified window. The window, or its parent, is also activated. The command returns the window that previously had the focus.
set_foreground_window HWIN
Sets the specified window to be the foreground window. Returns 1 if successful, and 0 otherwise.
set_window_long HWIN INDEX VALUE
This is a direct call to the SetWindowsLong function. Refer to Windows SDK documentation for details. Several other TWAPI functions act as wrappers and provide more straightforward access to the values set by this function.
set_window_style HWIN style exstyle
Sets the style and extended style bits for the specified window. style and exstyle are bitmasks. Refer to the Windows SDK documentation for details.
set_window_text HWIN TEXT
Sets the title of a window or the text associated with a control. In the latter case, the control must belong to the same application.
set_window_userdata HWIN INTEGER
Sets the longword associated as user data with the specified window. This maps to the Windows SetWindowLong call with an argument of GWL_USERDATA.
set_window_zorder HWIN POS
Sets the position of the specified window in the Z-order. POS may be either a window handle or a keyword. In the former case, the window is placed right after the window specified by POS. Otherwise, POS must be one of the following keywords:

top | Places the window at the top of the Z-order.
bottom | Places the window at the bottom of the Z-order.
toplayer | Refer to explanation of HWND_TOPMOST in the documentation of the function SetWindowsPos in the Windows SDK.
bottomlayer | Refer to explanation of HWND_NOTOPMOST in the documentation of the function SetWindowsPos in the Windows SDK.

show_caret
Shows the caret. Note that calls to hide_caret or twapi::HideCaret must be matched by an equivalent number of calls to show_caret or twapi::ShowCaret to make the caret visible.
show_owned_popups HWIN
Shows all popup windows owned by the specified window that were hidden by a previous call to hide_owned_popups. Note that popups that were hidden using other functions such as hide_window will not be shown by this call.
show_window HWIN ?options?
Makes the specified window visible. Note that a visible window may still be obscured by other windows or clipped. The command returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.

-sync | If specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.
-activate | In addition to being shown, the window is also activated.
-normal | If a window is minimized or maximized, restores it to its original position.
-startup | Shows the window based on the contents of the STARTUPINFO structure when the process was created.

If both -normal and -startup are specified, -startup takes precedence. If neither is specified, the window is shown in its current form, which may be minimized, maximized or normal.

tkpath_to_hwnd TKPATH
Returns the window handle corresponding to a Tk window in a form that can be passed to other TWAPI commands.
window_exists HWIN
Returns 1 if the specified window exists, else 0.
window_input_enabled HWIN
Returns 1 if the specified window has mouse and keyboard input enabled, else 0.
window_is_child PARENTHWIN CHILDHWIN
Returns 1 if the window CHILDHWIN is a child of the window PARENTHWIN, else 0.
window_maximized HWIN
Returns 1 if the specified window is maximized, else 0.
window_minimized HWIN
Returns 1 if the specified window has been minimized, else 0.
window_visible HWIN
Returns 1 if the specified window is visible, else 0. Note that visible does not imply user can actually see the window (it may be obscured or clipped).
window_unicode_enabled HWIN
Returns 1 if the specified window is a native Unicode window, else 0.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


COM - COM client support

COM

Commands for accessing COM servers

SYNOPSIS

package require twapi_com

clsid_to_progid CLSID
comobj PROGID_OR_CLSID ?options?
COMOBJ NAME ?parameter ...?
COMOBJ -bind SCRIPT
COMOBJ -call METHOD ?parameter ...?
COMOBJ -callnamedargs METHOD ?parametername parameter...?
COMOBJ -default
COMOBJ -destroy
COMOBJ -dispid NAME
COMOBJ -get PROPERTY ?parameter ...?
COMOBJ -interface ADDREF
COMOBJ -isnull
COMOBJ -iterate VARNAME SCRIPT
COMOBJ -print
COMOBJ -set PROPERTY VALUE ?VALUE ...?
COMOBJ -unbind BINDID
COMOBJ -with METHODLIST ?parameters ...?
comobj? COMOBJ
comobj_idispatch IDISPATCHINTERFACE
comobj_instances
comobj_object DISPLAYNAME ?-interface IDispatch|IDispatchEx?
define_dispatch_prototypes IID PROTOTYPES
generate_code_from_typelib PATH ?options?
get_typelib_path_from_guid GUID MAJOR MINOR ?-lcid LCID?
iid_to_name IID
ITypeLibProxy_from_path PATH ?-registration REGOPT?
ITypeLibProxy_from_guid GUID MAJOR MINOR ?-lcid LCID?
name_to_iid INTERFACENAME
progid_to_clsid PROGID
timelist_to_variant_time TIMELIST
unregister_typelib GUID MAJOR MINOR ?-lcid LCID?
variant_time_to_timelist DOUBLE

DESCRIPTION

This module provides commands for supporting COM clients. TWAPI's COM support is limited to client side calls only and does not provide facilities for writing COM components. Like other scripting languages like VBScript and Javascript, TWAPI's COM support is focused on Automation objects through their IDispatch and IDispatchEx interfaces. This provides the ability to script Windows applications such as Microsoft Office and Internet Explorer as well as admistrative interfaces such as Active Directory and Windows Management Instrumentation.

This documentation assumes some familiarity with COM programming concepts such as COM interfaces, COM automation, PROGID and CLSID identifier types etc.

COM API layers

TWAPI's COM support is implemented in layers:

  • At the lowest layer, TWAPI supports the raw Windows API calls such as IUnknown_QueryInterface or IDispatch_Invoke. It is not expected that applications will directly use these calls and they are not documented here. See the Windows Platform SDK for details of these calls.
  • At the next layer, TWAPI provides object wrappers around COM interfaces like IUnknown, IDispatch, ITypeInfo etc. They provide a more convenient programming interface as well as better efficiency by caching type information etc. They also provide access to type libraries and other system facilities.
  • The highest layer exposes COM automation servers through "proxy" objects created through the comobj command. All details of method lookup, type management and runtime dispatching are internally handled. The COM automation server's methods and properties are directly accessible to the application. In the rest of this documentation the proxy object and underlying COM automation object are both refered to as "object" unless the distinction is significant.

Creation and Destruction of COM automation objects

A COM automation proxy object is created through the command comobj using the PROGID or CLSID of the corresponding COM class. This returns a Tcl object command that may be used to access the object's methods and properties. The example below creates a proxy object using the PROGID for Internet Explorer.

set xl [comobj Excel.Application]

To attach to an existing COM instance instead of creating a new one, the -active option may be specified.

set xl [comobj Excel.Application -active]

The above command requires an instance of Excel to be running else an error is returned.

Alternatively, the comobj_object command can be used to bind to a COM object identified by its display name. For example, the following creates a COM object for an Excel file.

set xlso [comobj_object c:\\data\\myspreadsheet.xls]

When an object is no longer required, it must be explicitly destroyed by calling the command with the -destroy subcommand.

The list of existing COM automation objects in the application can be retrieved with the comobj_instances command. The command comobj? can be used to check if a command is a COM object.

Accessing Properties and Methods of Automation Objects

The properties and methods of a COM object can be accessed through the proxy object returned by the comobj command. The following sequence of commands shows a sample session that drives Internet Explorer through its properties and methods.

Start up Internet Explorer (note it will not be visible yet)

set ie [comobj InternetExplorer.Application -enableaaa]

Automation objects can be associated with a default property that is retrieved if no property or method are specified. This is the property marked as the default value in the COM object's IDL definition. In TWAPI this default property can be accessed using the -default method on the object.

$ie -default

Properties can be directly retrieved and modified. For example, the following commands makes its window visible by changing its Visible property.

$ie Visible true

In theory, the names of properties and methods of an automation object can overlap. Althouth TWAPI can usually figure out whether a property is being retrieved/set or a method is being called, you can explicitly control this by using the -get, -set or -call subcommands followed by the actual name. So the above call could also have been written as

$ie -set Visible true

to explicitly indicate we want to set the property called Visible as opposed to making a call to the COM object's method of the same name (if there was one).

To go to the TWAPI home page, invoke the Navigate method

$ie Navigate http://twapi.sf.net

Again, we could specify this is a method call, not a property, by explicitly indicating that as follows:

$ie -call Navigate http://twapi.sf.net

Explicitly specifying -call may also be required to disambiguate between methods that are implemented within the TWAPI comobj command object and the actual COM automation object itself. For example, the method destroy destroys the command object. If the underlying automation object also had a destroy method, you would need to invoke it as

$ie -call destroy

To continue with the example, we can read the LocationURL property to find the URL after redirection

$ie LocationURL

Ask the application to exit by calling its Quit method.

$ie Quit

Finally, destroy the proxy object and release the underlying COM object,

$ie destroy

Named Arguments

Some COM object methods may have a large number of arguments. Usually, these have default values and do not need to be specified. However, sometimes you may want to specify one or two of these. In such cases, having to specify all preceding arguments by position can be cumbersome. Using named arguments makes this easier. To use named arguments, use -callnamedargs instead of -call. For example, suppose in the call above to Navigate, we wanted to specify the page to be displayed in a new window without specifying all intervening parameters. We could call it as follows:

$ie -callnamedargs Navigate url http://twapi.sf.net TargetFrameName _blank

In the above call, url and TargetFrameName are parameter names. The parameter names for a call are generally specified in the documentation for the object.

COM Collections

Some COM objects are collection of items which may even be other COM objects. The items within these collections can be accessed by their index (which is not necessarily an integer) using the Item method as shown below.

set fso [comobj Scripting.FileSystemObject]
set drives [$fso Drives]
set cdrive [$drives Item c:]
puts "Drive C: is [lindex {{not ready} ready} [$cdrive IsReady]]"
$cdrive -destroy
$drives -destroy
$fso -destroy

In the above example, the Drives method of the Scripting.FileSystemObject object (implemented as an automation object by the Windows Shell) returns a collection drives. The drive letter c: is used to index into the collection object drives. As an alternative to explicit indexing in this fashion, TWAPI provides the -iterate method for iterating over all items in the collection. This is similar to the VBScript For each statement. The following example illustrates this.

set fso [comobj Scripting.FileSystemObject]
set drives [$fso Drives]
$drives -iterate drive {
    set drive_letter [$drive DriveLetter]
    if {[$drive IsReady]} {
        puts "Drive $drive_letter free space: [$drive FreeSpace]"
    } else {
        puts "Drive $drive_letter is not ready."
    }
    $drive -destroy
}
$drives -destroy
$fso -destroy

The -iterate operator on the collection then loops through each item in the collection, assigning the item to drive. In this case, each item is itself a COM automation object on which commands can be invoked. Note that the drive object generated in each iteration has to be explicitly destroyed.

Navigating Automation Objects

In many cases, the resource represented by a COM object has to be accessed by navigating through multiple intermediary objects. For example, the following example sets all cells within a range in a spreadsheet to 12345.

set xl [comobj Excel.Application]
$xl Visible true
set workbooks [$xl Workbooks]
set workbook [$workbooks Add]
set sheets [$workbook Sheets]
set sheet [$sheets Item 1]
set cells [$sheet range a1 c3]
$cells Value2 12345
$cells -destroy
$sheet -destroy
$sheets -destroy
$workbook -destroy
$workbooks -destroy
$xl Quit
$xl -destroy

In the above example, in order to get to the range we have to navigate through a hierarchy of objects, starting with the application, the workbook collection, a workbook within the collection, the worksheets collection, a worksheet within that collection and finally the cell range. After setting the value, all the created objects have to be deleted.

As an alternative, TWAPI automation proxy objects provide the -with internal method to simplify this process:

set xl [comobj Excel.Application]
$xl Visible true
$xl -with {
    Workbooks
    Add
    Sheets
    {Item 1}
    {range a1 c3}
} Value2 12345
$xl -destroy

The -with method takes a list of intermediate methods and associated parameters each of which should return a new object. Each method in the method list is invoked on the object returned by the previous method and should itself return a new object. The final object created from this list is passed the remaining arguments in the command. All intermediate objects are automatically destroyed.

COM Events

Some COM objects may generate notifications when certain events occur. A callback script may be registered using the -bind subcommand on a COMOBJ object. This script is invoked for every notification event generated by the COM object. The event name and parameters provided by the COM event source are appended to the script.

The following example receives events from Internet Explorer and prints them.

proc print_event args {puts "Received: [join $args ,]"}
set ie [comobj InternetExplorer.Application -enableaaa]
$ie Visible true
set bind_id [$ie -bind print_event]
$ie Navigate http://www.tcl.tk
after 2000
$ie -unbind $bind_id
$ie Quit
$ie -destroy

Note that the script is unregistered using the -unbind subcommand when no longer needed.

Interface Wrappers

In addition to the high level comobj based access to COM automation objects, TWAPI also provides object based wrappers for certain standard COM interfaces. These are provided for finer control of COM operation when the high level comobj does not provide enough flexibility. These wrapped include IUnknown, IDispatch, IDispatchEx, ITypeInfo, ITypeLib and ITypeComp. The corresponding wrapper classes are named with a Proxy suffix. For example, IUnknown is wrapped by the class IUnknownProxy.

Use of the classes requires a detailed understanding of COM programming techniques including lifetime management of objects through reference counting. Individual methods of these objects are not documented here. See the Windows SDK for details on these.

In addition to the standard methods defined by these interfaces, the proxy wrappers also implement additional helper methods that simplify working with the interfaces.

The following illustrates how these wrappers might be used:

set tlib [ITypeLibProxy_from_path  c:/windows/system32/stdole2.tlb]
set count [$tlib GetTypeInfoCount]
for {set i 0} {$i < $count} {incr i} {
    if {[$tlib GetTypeInfoType $i] == 4} {
        puts [lindex [$tlib GetDocumentation $i] 0]
    }
}
$tlib Release

The example starts off by getting a ITypeLibProxy object which wraps the ITypeLib interface for the stdole2.tlb type library. It then iterates through to print the names of dispatch interfaces in the type library using the ITypeLib methods GetTypeInfoCount, GetTypeInfoType and GetDocumentation as documented in the Windows SDK.

Note the object is released by calling Release and not its destroy method. This follows standard COM methodology. Calling the destroy method will delete the object while there might still be other references to it.

The same may be written with the @Foreach helper method as follows:

set tlib [ITypeLibProxy_from_path c:/windows/system32/stdole2.tlb]
$tlib @Foreach -type dispatch ti {
    puts [$ti @GetName]
    $ti Release
}
$tlib Release

The @Foreach method passes ITypeInfoProxy objects into the loop for every dispatch interface type entry in the library.

Using Type Libraries

Normally, TWAPI accesses COM components by looking up the method and property definitions at run time when the method or property is actually invoked. However, in some situations it is beneficial for reasons of convenience or efficiency to define these up front. TWAPI therefore provides facilities to extract the classes, interfaces and other data definitions associated with COM components from type libraries.

The primary command used for this purpose is the generate_code_from_typelib command. During development, this command can be used to write a file containing a Tcl script that will load the appropriate class and type definitions. The Tcl source command can then be used to load the class and type definitions at run time. Alternatively, the command can also return the script itself which can then be run via the Tcl eval command to immediately define the classes and types. Both these are illustrated by the examples below.

The following command will evaluate a script for defining type definitions for Microsoft Excel and then create a new instance of Excel.

eval [twapi::generate_code_from_typelib "c:/program files/microsoft office/office12/excel.exe"]
set xl [excel::Application new]
$xl Visible 1

In the example, the namespace excel is created based on the internal name of the library, not the file name though they happen to be the same. Within the namespace, classes such as Application, Worksheet, are defined corresponding to various COM objects. Invoking new on these classes will create instances of a COM automation object just like in the comobj command and can be used the same way.

In addition, the above will also define arrays within the namespace corresponding to the enums defined in the type library. For example, excel::XlRgbColor will contain the values mapping rgb color names. Similarly, constant variable definitions within a module will be contained within an array of that name.

Instead of evaling the returned script, we could also have saved it to a file using the -output option. This file could then be shipped with the application and read using the Tcl source command to recreate the definitions.

generate_code_from_typelib "c:/program files/microsoft office/office12/excel.exe" -output exceldefs.tcl

The following examples illustrate other options and scenarios. Note the commands do not eval the result which is just output to the screen so you can see the effect of the various options and the generated code. The stdole2.tlb type library is used as it is small enough to be viewed without clutter.

The following creates a script for all type definitions within the type library.

generate_code_from_typelib c:/windows/system32/stdole2.tlb

The next example creates a script for all type definitions within the type library, but within the ns namespace instead of the default stdole which is the internal type library name. If an empty string was specified instead of ns, the classes and enum array would be created in the current namespace.

generate_code_from_typelib c:/windows/system32/stdole2.tlb -namespace ns

Type libraries can be quite large and sometimes you need only a subset of the definitions. The following commands restrict the generated code to only define enums and a specific COM class respectively.

generate_code_from_typelib c:/windows/system32/stdole2.tlb -type enum

generate_code_from_typelib c:/windows/system32/stdole2.tlb -type coclass -name StdPicture

The choice between pregenerating type definitions versus runtime discovery of methods depends on several factors. The former provides some convenience; for example, enum constants can be used symbolically. Also, with some components (Microsoft Installer being one example), the type information may not be available on the target system and pregeneration is the only way to access them. The other factor is performance. If only a few components and methods are used, runtime discovery may be more efficient but for heavy use of pregeneration may offer better performance.

Controlling Parameter Types

Generally, TWAPI uses type information present in COM objects to detect parameter types and convert Tcl values appropriately. However, there are two circumstances where TWAPI has to guess the parameter type. The first case is when the COM object does not provide type information. The second case is when the parameter type is defined as a VARIANT which is a union that may be instantiated as one of several types. The COM object method may change its behaviour depending on the concret type of the passed parameter.

In languages like Visual Basic, the type of the passed parameter can be deduced because the language itself is typed. In Tcl, where "Everything Is A String", this is not possible. To deal with this situation, the application can use the tclcast command to appropriately force the passed value to a specific type. So for example, to force the passed parameter to be treated as a boolean, and not an integer, the application could call a method as follows:

$obj Visible [tclcast boolean 1]

Sometimes the COM component may not provide type information or mark a parameter as a generic VARIANT and yet expect a specific type. In such cases, even casting may not be sufficient to correctly pass parameters in the expected format. As a last resort to deal with such cases, TWAPI allows definition of prototypes for methods and properties for a COM component through the define_dispatch_prototypes command.

In the above example, instead of using a cast, a prototype for the method could be defined instead:

define_dispatch_prototypes guid {func 19 int Visible([in] bool bval)}

where guid is the GUID for the COM component and 19 is its DISPID (roughly, the index into the dispatch table). Note this requires some detailed knowledge of the COM component, like the GUID and the DISPID values for the member methods and properties.

Commands

clsid_to_progid CLSID
Returns the PROGID for a given CLSID. For example,

(tclsh) 53 % clsid_to_progid "{0002DF01-0000-0000-C000-000000000046}"
InternetExplorer.Application.1

comobj PROGID_OR_CLSID ?options?
Creates a COM object and returns a proxy object that can be used to access it. PROGID_OR_CLSID is either the PROGID or the CLSID for the COM object.

The returned value COMOBJ is itself a Tcl command object that can be used to access the COM object. When the object is no longer required it should be deleted by calling the command with the -destroy subcommand. You should not delete the command simply by calling the Tcl rename command as this will lead to memory and resource leaks. options may contain one or more of the options in the table below. Refer to the CLSCTX documentation in the Windows SDK for details regarding these options.

-active | If true, the returned object is attached to an existing COM instance instead of creating a new one. If no instances are running, an error is generated. Other options are ignored if this option is specified.
-disablelog BOOLEAN | If specified as true, disables logging of failures. Corresponds to the flag CLSCTX_NO_FAILURE_LOG in the SDK.
-download BOOLEAN If specified as true, allows downloading of code from the Internet or Directory Service. This corresponds to setting the flag CLSCTX_ENABLE_CODE_DOWNLOAD. If specified as false, disallows downloading of code from the Internet or Directory Service. This corresponds to setting the flag CLSCTX_DISABLE_CODE_DOWNLOAD.

If this option is not specified, neither of the flags is set in the underlying call to CoCreateInstance.
-enableaaa BOOLEAN If specified as true, enables activate-as-activator activations where a server process is launched under the caller's identity. This corresponds to setting the flag CLSCTX_ENABLE_AAA. If specified as false, disables activate-as-activator activations. This corresponds to setting the flag CLSCTX_DISABLE_AAA.

If this option is not specified, neither of the flags is set in the underlying call to CoCreateInstance.
-interface IDISPATCHINTERFACE | By default, the command will bind to the object's IDispatch interface. If the object is known to support the IDispatchEx interface as well, this option may be used to specify that should be used instead. IDISPATCHINTERFACE must be IDispatch or IDispatchEx.
-model MODELLIST | Specifies which of the COM hosting models are acceptable. MODELLIST must be a list containing one or more of the symbols localserver, remoteserver, inprocserver, inprochandler, or any signifying any model is acceptable.
-nocustommarshal BOOLEAN | If true, the object creation will fail if it uses custom marshalling. Corresponds to the flag CLSCTX_NO_CUSTOM_MARSHAL.

COMOBJ NAME ?parameter ...?
The command interprets NAME as a property or method name of the COM object. In case of ambiguity (the object has read and write properties or a method of the same name), the command is interpreted as a property get if no additional parameters are specified, as a property put if exactly one additional parameters is specified and a method invocation otherwise.
COMOBJ -bind SCRIPT
Registers SCRIPT as a script to be invoked in the global scope whenever COMOBJ generates an event notification. The name of the event and any additional parameters in the notification are appended to the script.

The command returns an id. This id must be passed to the -unbind subcommand to unregister the script.

The binding is automatically deleted when COMOBJ is destroyed or may be removed explicitly through the -unbind subcommand.

See COM Events for an example.
COMOBJ -call METHOD ?parameter ...?
Calls the specified COM object method with the given parameters and returns the result if any. Trailing parameters with default values need not be specified.
COMOBJ -callnamedargs METHOD ?parametername parameter...?
Calls the specified COM object method with the given parameters and returns the result if any. The parameters are specified as an alternating list of the parameter names and the corresponding parameter values. The order of specification is not important and parameter names are not case sensitive. Any parameters that are not specified must have default values.
COMOBJ -default
Returns the default property of the COM object.
COMOBJ -destroy
Destroys the COM object, removing any bindings and releasing resources.
COMOBJ -dispid NAME
Returns the DISPID for a property or name. This is useful when manually defining prototypes using define_dispatch_prototypes.
COMOBJ -get PROPERTY ?parameter ...?
Returns the value of the specified property. Optional parameters may be specified if the property is an indexed property.
COMOBJ -interface ADDREF
Returns the internal IDispatch pointer. Used for debugging purposes. If ADDREF is true (default), the interface reference count is incremented and caller must at some point call twapi::IUknown_Release on the returned interface pointer to release the interface. If ADDREF is false, caller must not release the interface itself.
COMOBJ -isnull
Returns true if the object is a NULL COM object, false otherwise. This corresponds to a NULL IDispatch pointer that might be returned in some COM operations, for example, to indicate the end of a collection.
COMOBJ -iterate VARNAME SCRIPT
Iterates over items in COMOBJ which must be a COM collection. In each iteration, SCRIPT is executed in the caller's context with VARNAME being set to the value of the current item.

Note that if the item is itself a COM object, VARNAME will contain the name of a TCL command corresponding to that object and must be destroyed when no longer needed (not necessarily within SCRIPT).

Like the Tcl iteration commands, -iterate always returns the empty string.

See COM Collections for an example.
COMOBJ -print
Prints to stdout the methods and properties of the object. Used for debugging.
COMOBJ -set PROPERTY VALUE ?VALUE ...?
Sets the value of the specified property. Additional optional parameters may be specified if supported by the underlying COM object.
COMOBJ -unbind BINDID
Deletes the COM event binding identified by BINDID.
COMOBJ -with METHODLIST ?parameters ...?
The -with subcommand takes a list of intermediate methods and associated parameters. Each element of this list should itself be a list the first element being the method or property name and remaining elements being the parameters to pass when that method/property is invoked. The method or property should return a new object and the next element in the list is invoked on the previously returned object. The final object created from this list is passed the remaining arguments in the command.

All the intermediate objects created are automatically destroyed.

See Navigating Objects for an example.
comobj? COMOBJ
Returns 1 if the COMOBJ refers to a COMOBJ object and 0 otherwise.
comobj_idispatch IDISPATCHINTERFACE
Creates a COM wrapper object for the specified IDispatch or IDispatchEx interface. Caller must hold a reference (count) to IDISPATCHINTERFACE that will be released by the COM wrapper object when it is destroyed. If caller wants to use IDISPATCHINTERFACE for its own purpose, it must do an additional IUnknown_AddRef itself to ensure the interface is not released when the returned COM wrapper instance is destroyed.
comobj_instances
Returns the list of existing COM proxy objects created through the comobj command.
comobj_object DISPLAYNAME ?-interface IDispatch|IDispatchEx?
Creates a COM object identified by its display name DISPLAYNAME and returns a proxy object that can be used to access it. See comobj for more details.

By default, the command will bind to the object's IDispatch interface. If the object is known to support the IDispatchEx interface as well, the -interface option may be used to specify that should be used instead.
define_dispatch_prototypes IID PROTOTYPES
Explicitly defines the prototype (call signature) for one or more methods or properties of a COM component. IID is the interface identifier for the dispatch interface of the COM component. PROTOTYPES contains one or more prototype definitions, each of which has the following form

MEMBERTYPE DISPID RETTYPE NAME (PARAMS)

. Note PROTOTYPES is a text string, not a Tcl list. NAME is the name of the method or property. MEMBERTYPE is one of func, propget, or propput depending on whether the prototype is for a function (method), a property get operation or a property put operation. Note all three may be defined for a single name. DISPID is the dispatch index for the method or property in the component's dispatch table. This can generally be obtained from either the type library or the component's IDL definition. RETTYPE is the type of the return value (see below). PARAMS is a comma separated sequence of parameter definitions. A parameter definition has the form

?PARAMATTR? PARAMTYPE ?PARAMNAME?

The parameter name PARAMNAME is optional but all parameters must be named or none must be named. The parameter attributes PARAMATTR are also optional. If specified, it is enclosed in [] and is a list of zero or more of in, out, inout and optional which indicate whether the parameter is a input parameter, an output parameter, or both, and whether it is optional. If no attributes are specified, they default to in.

PARAMTYPE, like RETTYPE, specifies the type of the parameter. It consists of a base type optionally followed by [] indicating an array of the base type, followed optionally by * indicating a pointer. The base type may be one of bool, bstr, cy, date, decimal, i1, i2, i4, r4, r8, idispatch, iunknown, ui1, ui2, ui4, variant or void.

define_dispatch_prototypes [name_to_iid ITwapiTest] {
    func 1 bstr GetBstr(int index, bstr[] strings, [out optional] int *lengthPtr)
    propget 2 int IntegerProp()
    propput 3 void IntegerProp(int)
}

generate_code_from_typelib PATH ?options?
Generates Tcl code to access enums, interfaces and COM classes defined within a type library. PATH specifies the type library path. The following options may be specified with the command.

-name ITEMNAME | Normally the command processes all items of the specfied type. If this option is specified, the generated script only contains definitions for the specified ITEMNAME.
-namespace NAMESPACE | By default, the enum values and classes are defined within a namespace corresponding to the library name, converted to lower case. This option may be specified to use a different namespace instead. NAMESPACE may also be specified as an empty string in which case the script will be run in the context of the namespace it is evaluated in.
-output SCRIPTPATH | The command normally returns the generated script. If this option is specified, the generated script is written out to the specified file. SCRIPTPATH may also be specified as stdout in which case it is written out to standard output.
-type TYPE | Normally, the generated script processes definitions of all types. If this option is specified, only definitions of that type are processed. TYPE must be one of enum, coclass, interface or module.
See Using Type Libraries for more details about the generated code and examples.

get_typelib_path_from_guid GUID MAJOR MINOR ?-lcid LCID?
Returns the path to the type library identified by GUID that is registered with the system. MAJOR and MINOR specify the version of the libary. An optional LCID may also be specified.
iid_to_name IID
Returns the name for the interface identifier IID (a GUID).
ITypeLibProxy_from_path PATH ?-registration REGOPT?
Reads a type library from the file at PATH and returns an ITypeLibProxy object for it. The type library is also optionally registered in the system registry. If -registration is not specified or specified as none, the type library is not registered. If REGOPT is register, the type library is registered. If REGOPT is default, the system's default rules for registration are followed.

The returned ITypeLibProxy object must be freed when done by calling its Release method.
ITypeLibProxy_from_guid GUID MAJOR MINOR ?-lcid LCID?
Returns an ITypeLibProxy object for a type library identified by GUID that is registered with the system. MAJOR and MINOR specify the version of the libary. An optional LCID may also be specified.

The returned ITypeLibProxy object must be freed when done by calling its Release method.
name_to_iid INTERFACENAME
Returns the unique interface identifier (IID) for the specified interface name, for example IDispatch.
progid_to_clsid PROGID
Returns the CLSID for a given PROGID. For example,

(wish) 51 % progid_to_clsid InternetExplorer.Application
{0002DF01-0000-0000-C000-000000000046}

timelist_to_variant_time TIMELIST
Several COM applications store date and time information as type double with the integral part representing the number of days since an epoch and the fractional part representing the time in the day. This command converts TIMELIST to this format. TIMELIST must be a list of 7 elements representing the year, month, day, hour, minutes, seconds and milliseconds.
unregister_typelib GUID MAJOR MINOR ?-lcid LCID?
Unregisters the type library identified by GUID with version MAJOR.MINOR from the system registry. An LCID may be optionally specified.
variant_time_to_timelist DOUBLE
Several COM applications store date and time information as type double with the integral part representing the number of days since an epoch and the fractional part representing the time in the day. This command takes such a time value and returns a list of 7 elements representing the year, month, day, hour, minutes, seconds and milliseconds.

COPYRIGHT

Copyright © 2006-2012 Ashok P. Nadkarni


Windows Shell - Windows Shell

Windows Shell

Windows shell commands

SYNOPSIS

package require twapi_shell

get_shell_folder CSIDL ?-create?
CloseThemeData
GetCurrentThemeName
GetThemeColor
GetThemeFont
invoke_url_shortcut SHORTCUTPATH ?options?
IsAppThemed
IsThemeActive
OpenThemeData
read_shortcut SHORTCUTPATH ?options?
read_url_shortcut SHORTCUTPATH
recycle_file FILENAME ?-confirm BOOLEAN? ?-showerror BOOLEAN?
shell_execute ?options?
shell_object_properties_dialog OBJECTPATH ?options?
systemtray addicon HICON ?CMDPREFIX?
systemtray modifyicon ICONID ?options?
systemtray removeicon ICONID
write_shortcut SHORTCUTPATH ?options?
write_url_shortcut SHORTCUTPATH URL ?-missingprotocol usedefault|guess?

DESCRIPTION

This module provides procedures related to the Windows shell.

Item Identifiers

The Windows shell identifies objects in its namespace, including non-file objects such as Control Panel applets and printers, using an item ID. Similar to a file system path, an object resides within the shell namespace object hierarchy and the entire path to the object is defined by item identifier list.

Folder Paths

The command get_shell_folder returns the path to the directory specified by a Windows Shell CSIDL.

File Operations

The command shell_execute allows invocation of any operation of a file or resource as from Windows Explorer, for example, opening a URL in a browser, searching a directory, starting a program and so on.

The command recycle_file sends the specified file to the Windows Recycle Bin.

Shell Dialogs

The command shell_object_properties_dialog displays the property page dialogs for the shell objects such as files, printers and volumes.

Themes

The commands OpenThemeData, CloseThemeData, IsThemeActive, IsAppThemed, GetCurrentThemeName, GetThemeColor and GetThemeFont provide access to information related to the current theme if the underlying platform supports themes. See the Windows SDK for documentation about these.

Shortcuts

The commands read_shortcut and write_shortcut allow reading and writing of shell shortcuts.

The commands read_url_shortcut and write_url_shortcut allow reading and writing of URL shortcuts. A URL shortcut can be invoked by invoke_url_shortcut.

Taskbar

TWAPI also provides commands to display and manage in the system tray (the Windows taskbar notification area). To display an icon in the system tray, application must first retrieve a handle to an icon using commands such as load_icon_from_file, load_icon_from_module or load_icon_from_system. This icon can then be displayed in the taskbar with the systemtray addicon command with optional callbacks when the icon is clicked or selected. Icons can be removed from the system tray via the systemtray removeicon command. Standard features like display of menus or balloons can be implemented either via the callbacks and systemtray modifyicon command.

Commands

get_shell_folder CSIDL ?-create?
Returns the path to the file system directory corresponding to the Windows shell folder identified by CSIDL. The path is always returned in native format.

CSIDL must be one of the following symbols or the corresponding integer values values as defined in the Windows SDK: csidl_admintools, csidl_common_admintools, csidl_appdata, csidl_cdburn_area, csidl_common_appdata, csidl_common_desktopdirectory, csidl_common_documents, csidl_common_favorites, csidl_common_music, csidl_common_pictures, csidl_common_programs, csidl_common_startmenu, csidl_common_startup, csidl_common_templates, csidl_common_video, csidl_cookies, csidl_desktopdirectory, csidl_favorites, csidl_history, csidl_internet_cache, csidl_local_appdata, csidl_mymusic, csidl_mypictures, csidl_myvideo, csidl_nethood, csidl_printhood, csidl_profile, csidl_profiles, csidl_programs, csidl_program_files, csidl_program_files_common, csidl_recent, csidl_sendto, csidl_startmenu, csidl_startup, csidl_system, csidl_templates, csidl_windows.

Refer to the documentation in the Windows SDK for the meaning of each of these identifiers.

If the option -create is specified, the folder will be created if it does not currently exist.

On some platforms, some of the above CSIDL's may be invalid. In this case, the command will attempt to return equivalent paths through other means such as environment variable settings.

The command will return an empty string if the CSIDL does not exist on the platform or if its value cannot be retrieved.
CloseThemeData
See Themes.
GetCurrentThemeName
See Themes.
GetThemeColor
See Themes.
GetThemeFont
See Themes.
invoke_url_shortcut SHORTCUTPATH ?options?
Invokes a URL shortcut. SHORTCUTPATH specifies the path of the URL shortcut itself. The following options may be specified.

-allowui | Allows user interaction.
-hwin HWIN | Specifies the parent window handle for user interaction. This is ignored if -verb is specified or if -allowui is not specified.
-verb VERB | Specifies the verb to invoke on the shortcut, for example open, edit etc.

IsAppThemed
See Themes.
IsThemeActive
See Themes.
OpenThemeData
See Themes.
read_shortcut SHORTCUTPATH ?options?
Reads a shortcut. SHORTCUTPATH specifies the path of the shortcut itself. The contents of the shortcut are returned as a keyed list with the following fields.

-args | Command line arguments for the link.
-desc | Description of the shortcut. This is the string that is visible to the user as the label of the shortcut.
-hotkey | The hotkey associated with the shortcut. This is an integer as described in the documentation of the IShellLink::Hotkey command in the Platform SDK.
-iconindex | The index of the icon within the icon file specifies by the -iconpath field.
-iconpath | The path to the file from which the icon for the shortcut is to be taken.
-idl | The item identifier list for the object pointed to by the shortcut.
-path | The file system path in the case that the shortcut points to a file.
-runas | A boolean value that indicates whether the target program is invoked as a different user or not.
-showcmd | The initial state of the window.
-workdir | The working directory of the shortcut.
Note that the field names are the same as the options for the write_shortcut command so you can modify a shortcut by reading it, changing the specific fields and passing the same list to write_shortcut.

The content format and operation of the command may be controlled through the following options.

-hwin HWIN | Identifies the window to be used as the parent of the dialog box that pops up to ask the user for more information when the shortcut cannot be resolved.
-install | Calls the MSI installer if the shortcut is an advertised shortcut and the target has not been installed yet.
-nolinkinfo | Disables distributed link tracking.
-nosearch | Normally, the command will search for the target if it cannot be found in the location pointed to by the shortcut. Specifying this option disables this search.
-notrack | Specifies that distributed link tracking to be not used.
-noui | Specifies that no dialog box should be displayed even if the link cannot be resolved.
-rawpath | Normally, the command resolves any embedded environment variables contained in the returned -path field and verifies the path exists. Specifying this option disables both these features and returns raw path contained in the shortcut.
-shortnames | The path contained in the returned -path field uses short name (8.3) format.
-timeout TIMEOUT | Specifies the timeout, in milliseconds, for resolving the link. This option has no effect unless the -noui is also specified.
-uncpath | The path contained in the returned -path field is in UNC format.

read_url_shortcut SHORTCUTPATH
Returns the URL pointed to by a URL shortcut. SHORTCUTPATH specifies the path of the URL shortcut itself.
recycle_file FILENAME ?-confirm BOOLEAN? ?-showerror BOOLEAN?
Sends the specified file to the Windows Recycle Bin. Returns true on success and false if user aborted the command. Any errors will generate a Tcl exception.

-confirm BOOLEAN | If true, a confirmation dialog is displayed to the user. Default is false.
-showerror BOOLEAN | If true, an error dialog is displayed to the user in case of errors. Default is false.

shell_execute ?options?
The shell_execute command is a wrapper around the Windows ShellExecuteEx function that allows invocation of various operations on file and other resources in the same manner as exposed by Windows Explorer as shown in the examples below.

The command supports the options shown in the table below and returns an empty string unless the -getprocesshandle option is specified.

-asyncok BOOLEAN | TBD.
-class BOOLEAN | TBD.
-connect BOOLEAN | TBD.
-dir PATH | Path of the working directory. Defaults to the current directory.
-getprocesshandle BOOLEAN | Normally, the command returns an empty string. If this option is specified, the command returns a handle to the process, if any, that was created by the shell to handle the request. If no such process was required to be created, or was already running, an empty string is returned. If a non-empty handle is returned, it must be closed by calling close_handle.
-hicon HANDLE | TBD.
-hkeyclass BOOLEAN | TBD.
-hmonitor HANDLE | Specifies a handle to a monitor on multiple-monitor systems. Cannot be used with the -hicon option.
-hotkey BOOLEAN | TBD.
-hwin BOOLEAN | Specifies the parent window handle, if any, for dialogs that are displayed. By default, no parent window is specified.
-idl BOOLEAN
-invokeidlist BOOLEAN | Normally, the shell will look up the registry for the list of verbs applicable for a file. If this option is specified as true, the shell will look up verbs dynamically added by shell extensions. See examples below. Default is false.
-logusage BOOLEAN | If true, the invocation will add to the counter maintained by Windows for determining the applications that show up on the Start menu. Default is false. Requires Windows XP or later and will generate an error on earlier versions of Windows.
-noconsole BOOLEAN | If true, the current process is not used for any processes created for the operation. A new console window is created if required. Default is false.
-noui BOOLEAN | If true, no user interaction, such as error display is done. Default is false.
-nozonechecks BOOLEAN | TBD.
-params STRING | Contains the parameter string to be passed to the invoked application. Use standard Windows syntax for separating parameters using spaces and quotes.
-path STRING | Path of the file or object on which the action is to be invoked. If unspecified, defaults to the current directory.
-show STRING | Specifies how the application invoking the action is to be displayed. Must be one of hide, shownormal, normal, showminimized, showmaximized, maximize, shownoactivate, show, minimize, showminnoactive, showna, restore, showdefault, or forceminimize. See the Windows SDK documentation of ShellExecute for details. Default is normal.
-substenv BOOLEAN | If true, any environment variables present in the values of the -path and -dir options are expanded. Default is false.
-unicode BOOLEAN | TBD.
-verb ACTION | Specifies the action to invoke on the resource, for example open, edit etc. See the examples below.
-wait BOOLEAN | Wait for the action to complete before returning. The exact effect of this depends on the action being invoked and the application handling the action. Default is false.
-waitforinputidle BOOLEAN | If specified as true, the command will wait up to one minute for any processes that are created as part of the invocation to enter the idle loop. Default is false.
Examples: Start up an application (notepad.exe):

shell_execute -path notepad.exe

Start up an application with parameters:

shell_execute -path notepad.exe -params {sample.txt}

Invoke the default action for a particular document. In most cases, this will open the application associated with the document type:

shell_execute -path sample.doc

Invoke a non-default action on a document (printing using the associated application):

shell_execute -path sample.doc -verb print

Invoke a non-default action (search) on a directory:

shell_execute -path c:/temp -verb find

Open a document in the home directory using environment variables:

shell_execute -path {%HOMEDRIVE%\%HOMEPATH%\My Documents\darknet.pdf} -substenv true

Launch a browser for a URL:

shell_execute -path http://www.google.com

Compose a email message:

shell_execute -path mailto:someone@somewhere.com

Invoke a dynamic action on a file. This will bring up the property sheet for notepad.exe instead of executing it.

shell_execute -path notepad.exe -verb properties -invokeidlist true

shell_object_properties_dialog OBJECTPATH ?options?
Displays the shell property dialog for the specified object which may be a file, a printer or a volume. OBJECTPATH is the path or the name of the object. The following options may be specified:

-hwin HWIN | If specified, HWIN is the handle to the window to be used as the parent for the dialog.
-type file|printer|volume | Specifies the type of the object identified by OBJECTPATH. Defaults to file.

systemtray addicon HICON ?CMDPREFIX?
Adds the icon referenced by handle HICON to the system tray and returns an identifier to be used with the systemtray modifyicon and systemtray removeicon commands.

If argument CMDPREFIX is specified and is not empty, it is invoked in response to user interface events (such as mouse clicks) related to the displayed icon. Four additional arguments are appended to CMDPREFIX before it is invoked - the associated identifier (as returned by this command), the notification event, the location of the mouse (as a pair of X,Y coordinates) when the event occured, and the clock ticks (as returned by the Windows GetClockTicks API) at the time of the event.

The notification event indicates the event and is one of the following constants:

select | Sent when the user selects the icon with the mouse (generally by clicking the left mouse button).
keyselect | Sent when the user selects the icon with the keyboard.
contextmenu | Sent when the user clicks the right mouse button.
mousemove | Sent when the mouse cursor is moved within the icon display area.
lbuttondown | Sent when the left mouse button is pressed.
lbuttonup | Sent when the left mouse button is released.
lbuttondblclk | Sent on a left button double-click.
rbuttondown | Sent when the right mouse button is pressed.
rbuttonup | Sent when the right mouse button is released.
rbuttondblclk | Sent on a right button double-click.
mbuttondown | Sent when the middle mouse button is pressed.
mbuttonup | Sent when the middle mouse button is released.
mbuttondblclk | Sent on a middle button double-click.
mousewheel | Sent when the mouse wheel is rotated.
xbuttondown | Sent when the x mouse button is pressed.
xbuttonup | Sent when the x mouse button is released.
xbuttondblclk | Sent on a x button double-click.
balloonshow | Sent when the balloon help associated with the icon is displayed.
balloonhide | Sent when the balloon icon is hidden.
balloontimeout | Sent when the balloon is hidden after a timeout.
balloonuserclick | Sent when the user clicks on the balloon.
Generally, applications should need to only handle the select, keyselect and contextmenu events. If the double-click events are also used, applications should be aware that select and button up/down events will also be sent and filter these appropriately.

For future compatibility, applications should ignore any notification events not listed above.

systemtray modifyicon ICONID ?options?
Modifies the specified system tray icon as per the specified options. ICONID is the identifier for the icon as returned by systemtray addicon. The following options may be specified:

-hicon HICON | Sets the icon to that specified by the handle HICON.
-tip STRING | Sets the tooltip that displayed when the mouse hovers over the icon. Truncated to 127 characters.
-balloon BALLOONTEXT | Displays BALLOONTEXT in the balloon tool tip for the icon. The balloon is removed after a timeout based on system setting. BALLOONTEXT is truncated to 255 characters.
-balloontitle BALLOONTITLE | Sets the title of the balloon, truncated to 63 characters.
-balloonicon BALLOONICON | Sets the icon displayed in the balloon tooltip. BALLOONICON must be one of info, warning, error, user, or none (default). The icon is not displayed if the balloon title is not specified.
-silent BOOLEAN | If true, sounds associated with the balloon (based on the icon type), are not played. Default is false (sounds are enabled).

systemtray removeicon ICONID
Removes the specified icon from the system tray. ICONID is the identifier for the icon as returned by systemtray addicon.
write_shortcut SHORTCUTPATH ?options?
Writes or creates a shortcut. SHORTCUTPATH specifies the path of the shortcut itself. The following options control the contents of the shortcut.

-args ARGUMENTS | Specifies the command line arguments for the link.
-desc DESCRIPTION | Specifies the description of the shortcut. This is the string that is visible to the user as the label of the shortcut.
-hotkey HOTKEY | Specifies the hotkey to be associated with the shortcut. HOTKEY should be an integer as described in the documentation of the IShellLink::Hotkey command in the Platform SDK or a symbolic string as described in the register_hotkey command.
-iconindex INDEX | Specifies INDEX as the index of the icon within the icon file specifies by the -iconpath option.
-iconpath ICONPATH | Specifies ICONPATH as the path to the file from which the icon for the shortcut is to be taken.
-idl IDL | Specifies that the shortcut should point to the object identified by the item identifier list IDL. This is useful in cases where the target of the short cut is not a file.
-path TARGETPATH | Specifies TARGETPATH as the file system path to which the shortcut points. This must be a full absolute path else Windows will return an error.
-runas BOOLEAN | If BOOLEAN as true, the command will be invoked as a different user (effect depends on version of Windows).
-showcmd WINDOWSTATE | Specifies the initial state of the window. WINDOWSTATE should be one of minimized, maximized or normal.
-workdir DIRPATH | Specifies DIRPATH as the working directory of the shortcut.

write_url_shortcut SHORTCUTPATH URL ?-missingprotocol usedefault|guess?
Writes or creates a URL shortcut. SHORTCUTPATH specifies the path of the URL shortcut itself. URL is the URL to which the shortcut should point.

If the -missingprotocol option is specified, the system will attempt to fill in the protocol if URL itself does not specify a protocol. If the value of this option is guess, the system will attempt to guess the protocol based on the URL string. If the option value is usedefault, the system will use the default protocol scheme.

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


Keyboard and mouse input - Keyboard and mouse input

Keyboard and mouse input

Simulation of user input and support for system-wide hotkeys

SYNOPSIS

package require twapi_input

block_input
click_mouse_button BUTTON
get_input_idle_time
get_keyboard_layout_name
get_mouse_location
move_mouse XPOS YPOS ?-relative?
register_hotkey HOTKEY SCRIPT ?-append?
send_input INPUTLIST
send_input_text TEXT
send_keys KEYSEQUENCE
turn_mouse_wheel WHEELUNITS
unblock_input
unregister_hotkey HOTKEY_ID

DESCRIPTION

This package provides procedures related to user input on Windows platforms. The commands send_input, send_keys, send_input_text, move_mouse, click_mouse_button and turn_mouse_wheel can be used to simulate user input. The mouse position can be retrieved using get_mouse_location. The commands block_input and unblock_input can be used to prevent interference from real user input while simulating input.

The commands register_hotkey and unregister_hotkey can be used to register scripts to be invoked when the user presses a hotkey combination.

The amount of time elapsed since the last keyboard or mouse input event can be obtained through get_input_idle_time.

The name of the current keyboard layout can be retrieved with get_keyboard_layout_name.

Commands

block_input
This command blocks real physical input events and simulated events from threads other than the caller from being entered into the input queue. The command can be used to prevent interference when the commands such as send_input, send_input_text, click_mouse_button are used to simulate user input. The command unblock_input should be called to renable input.

The return value of block_input is 1 if the input was previously unblocked and 0 if the input was already blocked.
click_mouse_button BUTTON
Generates input to simulate clicking the specified mouse button. BUTTON may have one of the values left, right, middle, x1 or x2 to specify the button that was clicked.
get_input_idle_time
Returns the elapsed time in milliseconds since the last keyboard or mouse input event.
get_keyboard_layout_name
Returns the string identifier for the current keyboard layout.
get_mouse_location
Returns a pair of integers containing the mouse cursor's X and Y screen coordinates in pixels.
move_mouse XPOS YPOS ?-relative?
Generates input to simulate mouse movement. Movement is in absolute mouse coordinates unless the option -relative is specified. See description of send_input for more details.
register_hotkey HOTKEY SCRIPT ?-append?
Registers a script to be invoked when the user presses the hotkey specified by HOTKEY. Note that the script is invoked when the hotkey is pressed even if some other application had the input focus. If the caller had previously registered a script for the same hotkey, it is replaced by SCRIPT unless the -append option is specified. In this latter case, SCRIPT is added to the list of scripts. These are invoked in turn in the order they were registered. If any of the scripts returns an error or a return code value of 3 (break), subsequent scripts in the list are not invoked. Any errors are reported as background errors using the standard Tcl background error mechanism.

HOTKEY is a string describing the key combination and consists of 0-4 modifiers followed by the key code, all separated by the - character. A modifier may be one of ctrl (or control), alt (or menu), shift or win. The key code itself may be a single alphanumeric character, one of the virtual key names, such as F9, listed in send_input, or the actual virtual key code itself. Examples are ctrl-alt-a, shift-f9 and ctrl-alt-65.

The command returns an identifier corresponding to the specified hotkey registration. It should be deregistered when no longer needed by calling the unregister_hotkey function.
send_input INPUTLIST
Simulates user input by generating keyboard and mouse events based on INPUTLIST. This must be in the form of a list of sublists, each sublist being a keyboard or mouse input event specification.

A keyboard input specification takes the form

"KEYTYPE VK SCANCODE ?keyopts?".

KEYTYPE may have one of the following values:

key | Specifies a virtual key being pressed and released. This is a more convenient form of specifying consecutive keydown, keyup events. VK should be an integer in the range 1-254 and specifies the virtual key. SCANCODE specifies a hardware scancode for the key. If -usescan is specified in keyopts, the specified scan code is used and VK will be ignored by the system. If -extended is specified in keyopts, the key is treated as an extended key with the scan code being preceded by a byte that has value 0xE0.
keydown | Specifies a virtual key being pressed. VK should be an integer in the range 1-254 and specifies the virtual key. SCANCODE specifies a hardware scancode for the key. keyopts may have the same values as specified for vkey.
keyup | Specifies a virtual key being released. VK should be an integer in the range 1-254 and specifies the virtual key. SCANCODE specifies a hardware scancode for the key. keyopts may have the same values as specified for vkey.
unicode | Specifies a unicode character. SCANCODE should contain the integer corresponding to the unicode character. VK and any keyopts are ignored if specified.

For more detailed information, refer the the documentation of the KEYBDINPUT structure in the Windows SDK.

send_input should generally be used only for the most low level input sequences involving both keyboard and mouse input. The commands send_input_text and send_keys provide more convenient alternatives for sending pure text and a combination of text and special keys respectively.

A mouse input specification takes the form

"mouse XPOS YPOS ?mouseopts?".

Arguments XPOS and YPOS specify the position of the mouse in absolute (default) or relative coordinates. In the former case, the values range from 0 to 65535 and are in mouse coordinates. In the latter case, the values are in pixels. Note when relative mode is used, the system will take into account the mouse speed and acceleration settings. The command move_mouse is much simpler to use unless you have a need to send complex mouse input sequences.

mouseopts may contain one or more of the following options:

-relative | Indicates that XPOS and YPOS should be treated as relative to the last reported position, and not as absolute coordinates.
-ldown | Indicates that the left mouse button has been pressed since the last reported event.
-lup | Indicates that the left mouse button has been released since the last reported event.
-rdown | Indicates that the right mouse button has been pressed since the last reported event.
-rup | Indicates that the right mouse button has been released since the last reported event.
-mdown | Indicates that the middle mouse button has been pressed since the last reported event.
-mup | Indicates that the middle mouse button has been released since the last reported event.
-x1down | Indicates that the first X button has been pressed since the last reported event.
-x1up | Indicates that the first X button has been released since the last reported event.
-x2down | Indicates that the second X button has been pressed since the last reported event.
-x2up | Indicates that the second X button has been released since the last reported event.
-moved | Indicates that the mouse has moved since the last reported event.
-wheel WHEELUNITS | Indicates that the mouse wheel was rotated by WHEELUNITS. This may be a positive integer for forward rotation, or a negative integer for backward rotation. This option may not be used with any of the X button options.
For more detailed information, refer the the documentation of the MOUSEINPUT structure in the Windows SDK.

The commands move_mouse, click_mouse_button and turn_mouse_wheel may be more convenient for common cases.

send_input_text TEXT
Simulates user input by generating keyboard events corresponding to TEXT.
send_keys KEYSEQUENCE
Simulates user input of keyboard events. This function differs from send_input_text in that the keys generated may include non-text keys such as function keys, modifier keys etc.. KEYSEQUENCE indicates the keys to be generated and is specified with the syntax defined below. This syntax is a superset of the syntax used by the Visual Basic SendKeys command.

All characters in KEYSEQUENCE result in the corresponding keystroke being generated except for the following characters which have a special meaning:

The ~ character stands for the ENTER key.

The +, ^ and % characters are used as key modifiers for the following character or character groups. The + character is used to indicate the following character should be entered as though the SHIFT key was pressed while entering the character. Similarly, ^ and % indicate the CTRL and ALT modifiers respectively. For example, the sequence +ab will result in the following key stroke sequence being generated: SHIFT is pressed and held down, the a key is pressed and released, the SHIFT key is released, and finally the b key is pressed and released.

The ( and ) characters are used to group a set of characters together. This is used for applying a key modifier to a sequence of characters. For example, the sequence +(abc) will result in the following key stroke sequence being generated: SHIFT is pressed and held down and then the keys a, b and c are pressed and released before the SHIFT key is released.

The { and } keys are used to indicate special keys such as function keys and to enter the special characters such as +. Thus, {+} will result in the key + being pressed and released. Similarly, {(} and {}} indicate the character ( and } being entered. As a special case, the form {C N} results in the character C being entered N times. Note that the character may be any character, not just a special character that needs to be escaped.

The other use of the braced escape sequence is to enter special keys. These special sequences and the corresponding generated keystrokes are:

{BACKSPACE} | Backspace
{BACK} | (same as {BACKSPACE})
{BS} | (same as {BACKSPACE})
{BKSP} | (same as {BACKSPACE})
{TAB} | Tab
{CLEAR}
{ENTER} | Enter key on the main keyboard
{RETURN} | (same as {ENTER})
{SHIFT} | Shift (see note below on difference between this and use of the + modifier).
{CONTROL} | Shift (see note below on difference between this and use of the ^ modifier).
{ALT} | Shift (see note below on difference between this and use of the % modifier).
{MENU} | (same as {ALT})
{PAUSE} | Pause
{BREAK} | Break
{CAPSLOCK} | Caps Lock
{CAPITAL} | (same as {CAPSLOCK})
{KANA}
{HANGEUL}
{HANGUL}
{JUNJA}
{FINAL}
{HANJA}
{KANJI}
{ESCAPE} | Escape
{ESC} | (same as {ESCAPE})
{CONVERT}
{NONCONVERT}
{ACCEPT}
{MODECHANGE}
{SPACE} | Spacebar
{PGUP} | Page Up
{PRIOR} | (same as {PGUP})
{PGDN} | Page Down
{NEXT} | (same as {PGDN})
{END} | End
{HOME} | Home
{LEFT} | Left arrow
{UP} | Up arrow
{RIGHT} | Right arrow
{DOWN} | Down arrow
{SELECT}
{PRTSC} | Print Screen key
{PRINT} | Print key
{EXECUTE}
{SNAPSHOT}
{INSERT} | Insert
{INS} | (same as {INSERT})
{DELETE} | Delete
{DEL} | (same as {DELETE})
{HELP} | Help
{LWIN} | Left Windows key
{RWIN} | Right Windows key
{APPS}
{SLEEP}
{NUMPAD0} | Numeric keypad 0
{NUMPAD1} | Numeric keypad 1
{NUMPAD2} | Numeric keypad 2
{NUMPAD3} | Numeric keypad 3
{NUMPAD4} | Numeric keypad 4
{NUMPAD5} | Numeric keypad 5
{NUMPAD6} | Numeric keypad 6
{NUMPAD7} | Numeric keypad 7
{NUMPAD8} | Numeric keypad 8
{NUMPAD9} | Numeric keypad 9
{MULTIPLY} | Numeric keypad *
{ADD} | Numeric keypad +
{SEPARATOR}
{SUBTRACT} | Numeric keypad -
{DECIMAL} | Numeric keypad .
{DIVIDE} | Numeric keypad /
{F1} | Function key F1
{F2} | Function key F2
{F3} | Function key F3
{F4} | Function key F4
{F5} | Function key F5
{F6} | Function key F6
{F7} | Function key F7
{F8} | Function key F8
{F9} | Function key F9
{F10} | Function key F10
{F11} | Function key F11
{F12} | Function key F12
{F13} | Function key F13
{F14} | Function key F14
{F15} | Function key F15
{F16} | Function key F16
{F17} | Function key F17
{F18} | Function key F18
{F19} | Function key F19
{F20} | Function key F20
{F21} | Function key F21
{F22} | Function key F22
{F23} | Function key F23
{F24} | Function key F24
{NUMLOCK} | Numlock
{SCROLL} | Scroll lock
{SCROLLLOCK} | Scroll lock
{LSHIFT} | Left Shift
{RSHIFT} | Right Shift
{LCONTROL} | Left Control
{RCONTROL} | Right Control
{LALT} | Left Alt
{LMENU} | (same as {LALT})
{RALT} | Right Alt
{RMENU} | (same as {RALT})
{BROWSER_BACK} | Back
{BROWSER_FORWARD} | Forward
{BROWSER_REFRESH}
{BROWSER_STOP} | Stop
{BROWSER_SEARCH} | Search
{BROWSER_FAVORITES} | Favorites
{BROWSER_HOME} | Web Home
{VOLUME_MUTE}
{VOLUME_DOWN}
{VOLUME_UP}
{MEDIA_NEXT_TRACK}
{MEDIA_PREV_TRACK}
{MEDIA_STOP}
{MEDIA_PLAY_PAUSE}
{LAUNCH_MAIL}
{LAUNCH_MEDIA_SELECT}
{LAUNCH_APP1}
{LAUNCH_APP2}
Note that use of the braced sequences for the modifier keys such as SHIFT is not the same as the corresponding special characters. For example, the string {SHIFT}a results in the key sequence where the SHIFT key is pressed and released before the a key is pressed. The string +a on the other hand results in a key sequence where the SHIFT key is released after the a is pressed and released.

turn_mouse_wheel WHEELUNITS
Generates input to simulate turning the wheel. A positive value of WHEELUNITS simulates forward rotation by the specified number of units, a negative value simulates backward rotation.
unblock_input
This command reverses the effect of a previous call to block_input.

The return value of unblock_input is 1 if the input was previously blocked and 0 if the input was already unblocked.
unregister_hotkey HOTKEY_ID
Unregisters a hot key that was previously registered. HOTKEY_ID should be a hotkey identifer returned by a previous call to register_hotkey. All scripts associated with the hotkey are unregistered.

COPYRIGHT

Copyright © 2003, 2004, Ashok P. Nadkarni


Sound - Playing sounds

Sound

Basic sound functions

SYNOPSIS

package require twapi_multimedia

beep ?options?
play_sound NAME ?options?
stop_sound

DESCRIPTION

This package provides commands for playing sounds on Windows platforms.

Overview

The commands beep, play_sound and stop_sound provide basic functions for generating sound. For more sophisticated needs, there are other Tcl extensions available, such as the Snack Sound Toolkit.

Commands

beep ?options?
Generates a sound on the system speaker. The following options may be specified:

-frequency FREQUENCY | The frequency of the sound to be produced (default 1000 Hz).
-duration MILLISECONDS | The duration of the sound to be produced (default 100 milliseconds).
-type SOUNDIDENTIFIER | Specifies the type of sound to produce. SOUNDIDENTIFIER may be one of ok, hand, question, exclamation or asterisk. These will produce the corresponding sounds configured in the Windows control panel. If this option is specified, the options -duration and -frequency are ignored.

play_sound NAME ?options?
Plays a sound on the system audio device. The sound may either be a WAV file or a system defined sound (if the -alias option is specified). The command returns 1 if successful else 0.

The following options may be specified to control the sound:

-alias | By default, NAME is assumed to be the path of a WAV file. If -alias is specified, NAME is assumed to be the name of a system sound. The following system defined sounds are guaranteed to be present on all systems: SystemAsterisk, SystemExclamation, SystemExit, SystemHand, SystemQuestion and SystemStart. Other system defined names can be located under the HKEY_CURRENT_USER\AppEvents\EventLabels registry key. Note that a sound will only be played if a WAV file has been associated with it through the control panel.
-async | If specified, the sound is played asynchronously and command will return immediately. By default, the command will return only after the sound has completed playing.
-loop | Specification of this option causes the sound to be played repeatedly until stopped through a stop_sound command. This option also automatically enables the -async option.
-nodefault | If the system cannot find the specified sound, it plays a default sound file. If this option is specified, the command will return without playing any sound if the specified sound file is not found.
-nostop | Normally, the audio device is playing some other file, the command will attempt to stop the currently playing sound. If -nostop is specified, the command will return immediately without attempting to stop the current sound.
-wait | If the audio driver is busy, the command will return right away. If this option is specified, the command will wait for the driver to become available.

stop_sound
Stops all currently playing sounds that have been started by the current task. Returns 1 if successful, else 0.

COPYRIGHT

Copyright © 2003, Ashok P. Nadkarni


Clipboard - Clipboard access

Clipboard

Commands related to accessing the clipboard

SYNOPSIS

package require twapi_clipboard

clipboard_format_available FORMAT
close_clipboard
empty_clipboard
get_clipboard_formats
get_registered_clipboard_format_name FORMAT
open_clipboard
read_clipboard FORMAT
read_clipboard_text ?-raw BOOLEAN?
register_clipboard_format FORMATNAME
start_clipboard_monitor SCRIPT
stop_clipboard_monitor MONITOR_ID
write_clipboard FORMAT DATA
write_clipboard_text TEXT ?-raw BOOLEAN?

DESCRIPTION

This module provides procedures to read and write the clipboard.

Overview

The command read_clipboard and write_clipboard allow reading and writing to the Windows clipboard. Tcl/Tk has a clipboard command that provides similar functionality. The TWAPI commands are useful in two circumstances:

  • The Tcl clipboard command is not available in console-based Tcl programs that do not load Tk. The TWAPI command may be used to access the clipboard in this case.
  • More control is desired over the specific format of the data stored into the clipboard.
In other cases, the Tcl/Tk clipboard command should be preferred.

Clipboard formats

Data may be stored in the clipboard in any number for formats identified by integer values. When reading clipboard data, applications must check in what formats the current clipboard data is currently available and specify one of these formats when reading the data. Similarly, when writing data to the clipboard, applications need to specify the format in which data is to stored in the clipboard. In some cases, Windows will automatically make multiple formats available. For example, storing text in format type 1 (text) will also make format type 13 (Unicode) available in the clipboard.

In addition to the standard set of formats defined by Windows applications may register their own formats with the system. The format values associated with these are created the first time the format name is registered through register_clipboard_format and can be retrieved later with the same call. Conversely, the name associated with a format can be obtained through the get_registered_clipboard_format_name command. An example of a registered application format name is "HTML Format" which is used by Internet Explorer to store HTML fragments on the clipboard.

Multiple formats may be simultaneously stored into the clipboard. The formats currently stored in the clipboard may be obtained through the get_clipboard_formats command.

When reading or writing data, the application is responsible for formatting data appropriately, possibly through the use of Tcl's binary command. The exceptions to this are the read_clipboard_text and write_clipboard_text commands which assume the data is just text.

Reading and Writing Data

In the general case, the clipboard must first be opened with the open_clipboard call before data can be read or written to it. Data may be read and written using the read_clipboard and write_clipboard commands respectively. If data is to be written, ownership must first be claimed by calling empty_clipboard else the writes may not succeed. The clipboard must then be closed by calling close_clipboard. There may be multiple write commands between the clipboard open and close to store data in multiple formats.

For the simple case of reading and storing text data, the commands read_clipboard_text and write_clipboard_text may be used.

Monitoring clipboard changes

An application can monitor the clipboard by calling start_clipboard_monitor to set up a notification callback that is invoked when the contents of the clipboard change.

Commands

clipboard_format_available FORMAT
Returns 1 if the clipboard contains data in the specified format, and 0 otherwise. This command does not require the clipboard to have been opened.
close_clipboard
Closes the clipboard which must have been previously opened with open_clipboard.
empty_clipboard
Empties the clipboard and claims ownership for further writes. The clipboard must have been previously opened with open_clipboard. This command must be called before any writes to the clipboard.
get_clipboard_formats
Returns a list of the formats currently available in the clipboard. The clipboard must have been opened before this function is called.
get_registered_clipboard_format_name FORMAT
Returns the name associated with a registered clipboard format. FORMAT identifies the format and must correspond to a registered format. An exception will be raised if FORMAT is a standard Windows format or a unregistered private format.
open_clipboard
Opens the clipboard for reading or writing. Most clipboard operations require the clipboard to have been previously opened. The clipboard must be closed once the operations are done by calling close_clipboard.
read_clipboard FORMAT
Reads the contents of the clipboard in the given format and returns it. The clipboard must have been previously opened through open_clipboard and remains open when the command returns except in the case of any Tcl exceptions. In these cases, the clipboard is closed before the exception is thrown.

FORMAT must be one of the clipboard formats as defined in Clipboard formats. The content is an exact copy of the contents of the clipboard in binary format. Callers will need to use Tcl commands such as binary and encoding to parse the data.
read_clipboard_text ?-raw BOOLEAN?
Retrieves the content of the clipboard as text. The clipboard must have been previously opened through open_clipboard and remains open when the command returns except in the case of any Tcl exceptions. In these cases, the clipboard is closed before the exception is thrown.

If -raw is specified as false (default), the command converts CR-LF line terminators in clipboard content to LF line terminators. If -raw specified as true, the command does no conversion of the clipboard data.
register_clipboard_format FORMATNAME
Registers an application defined format with the system (see Clipboard Formats). FORMATNAME is the name associated with the format. The command returns an integer format identifier that may be used in calls to read and write data. If the format name is already registered, the same integer format value is returned. This command does not require the clipboard to be open.
start_clipboard_monitor SCRIPT
Begins monitoring of clipboard contents. SCRIPT will be invoked when the clipboard is written to by any application.

The command returns a handle. When no longer required, this handle must be passed to the command stop_clipboard_monitor.

Multiple clipboard monitoring scripts may be active at the same time. However, all returned handles must be passed to stop_clipboard_monitor. before the application exits.
stop_clipboard_monitor MONITOR_ID
Stops a previously registered script that monitors clipboard contents. MONITOR_ID is monitoring handle previously returned by start_clipboard_monitor.
write_clipboard FORMAT DATA
Writes DATA to the clipboard in the given format. The clipboard must have been previously opened through open_clipboard and ownership claimed through the empty_clipboard command. The clipboard remains open when the command returns except in the case of any Tcl exceptions. In these cases, the clipboard is closed before the exception is thrown. This ensures other applications are not locked out of the clipboard on errors.

FORMAT must be one of the clipboard formats as defined in Clipboard formats. The content is an exact copy of the contents of the clipboard in binary format. Callers will need to use Tcl commands such as binary and encoding to parse the data.

Multiple write_clipboard commands may be executed between a open_clipboard and close_clipboard pair as long as the specified formats are different for each. Writing a format previously specified in the sequence overwrites the previous contents of that format.
write_clipboard_text TEXT ?-raw BOOLEAN?
Writes the given text string to the clipboard. The clipboard must have been previously opened through open_clipboard and ownership obtained using empty_clipboard. The clipboard remains open when the command returns except in the case of any Tcl exceptions. In these cases, the clipboard is closed before the exception is thrown. This ensures other applications are not locked out of the clipboard on errors.

If -raw is specified as false (default), the command converts LF line terminators without a preceding CR to CRLF line terminators. If -raw specified as true, the command does no conversion.

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


System - System and processor

System

Operating system and machine configuration and control

SYNOPSIS

package require twapi_os

abort_system_shutdown ?-system SYSTEM?
find_domain_controller ?options?
get_computer_name ?NAMETYPE?
get_computer_netbios_name
get_memory_info ?options?
get_numa_config
get_primary_domain_controller ?options?
get_primary_domain_info ?options?
get_os_description
get_os_info
get_os_version
get_processor_count
get_processor_group_config
get_processor_info PROCESSOR ?options?
get_system_parameters_info PARAMETER
get_system_sid
get_system_time
get_system_uptime
lock_workstation
logoff ?-force? ?-forceifhung?
min_os_version osmajor ?osminor? ?spmajor? ?spminor?
set_system_parameters_info PARAMETER VALUE ?-persist? ?-notify?
shutdown_system ?options?
suspend_system ?options?

DESCRIPTION

This module provides commands related to the system configuration including operating system functions and hardware configuration.

Overview

The commands get_os_version and min_os_version get and verify operating system version information.

The commands get_os_info and get_os_description allow retrieval of more detailed operating system information than the standard Tcl commands which do not distinguish between service packs, Professional versus Server versions and so on.

The command get_computer_name returns one of several forms of the system name. The command get_computer_netbios_name returns the NETBIOS name of the computer. Domain and workgroup information about the system can be obtained through the get_primary_domain_info command. find_domain_controller returns information about a domain controller with specified characteristics. get_primary_domain_controller returns the name of the primary domain controller of the computer.

The commands get_processor_count, get_processor_group_configuration and get_processor_info retrieve information about the processors in the system.

The command get_memory_info returns the physical and virtual memory configuration of the system.

The command get_system_time returns the current system time in high resolution. The command get_system_uptime returns the how long the system has been running. The command shutdown_system may be used to shutdown or reboot the system. The command abort_system_shutdown may be used to abort an ongoing system shutdown. The command suspend_system may be used to put the system in stand by or hibernate states. You can prevent the system from being suspended due to inactivity through the SetThreadExecutionState command. The commands logoff and lock_workstation may be used to log out of a user account and to lock a workstation respectively.

Various system settings related to the user experience can be retrieved and set through the get_system_parameters_info and set_system_parameters_info commands.

Commands

abort_system_shutdown ?-system SYSTEM?
Aborts a previously initiated system shut down or reboot. Note this is only possible if the system shutdown was initiated with a non-zero timeout value. The command enables any required privileges and restores the original privileges before returning.
find_domain_controller ?options?
Returns the name of a domain controller with specified characteristics and optionally, details about its characteristics and capabilities.

-allowstale BOOLEAN | If specified as true, the system will return cached domain controller information even if it is marked as expired. Default is false. This option has no effect if -rediscover is specified as true.
-avoidself BOOLEAN | If specified as true, and the command is run on a domain controller, the domain controller will return the name of another domain controller, not itself. Default is false.
-domain DOMAINNAME | Specifies the domain whose domain controller is to be retrieved. If unspecified, defaults to the primary domain of the computer.
-domainguid GUID | If the domain specified by the -domain option or the primary domain of system cannot be found, the command will attempt to return the domain controller for the domain with the specified GUID. Note this option may require -system to specify a system that knows about the specified domain GUID.
-getdetails | By default, the command returns the name of the domain controller. If this option is specified, the command returns detailed information whose format is described below.
-inputnameformat NAMEFORMAT | Specifies the format of the specified domain name. NAMEFORMAT may be one of dns, which implies DNS format, netbios which implies flat Netbios format, or any (default) which results in the command searching both namespaces.
-justldap BOOLEAN | If specified as true, the command searches for a LDAP server without caring if it is a domain controller.
-rediscover BOOLEAN | If specified as true, the system ignores any cached domain controller data. Default is false. Note specifying this option as true significantly increases the time to execute the command.
-outputaddrformat ADDRFORMAT | If ADDRFORMAT is specified as ip, the -dcaddr field in the returned information is the Internet address.
-outputnameformat NAMEFORMAT | Specifies the format in which the domain controller and domain names should be returned. NAMEFORMAT may be one of dns, which implies DNS format, netbios which implies flat Netbios format, or any (default). The command will raise an error if the name is not available in the specified format.
-prefer FEATURE | Indicates that the domain controller that support the specified features and services is returned in preference to one that does not. FEATURE is either directoryservice or timeserver (see below).
-require FEATURELIST | Indicates that the domain controller to be returned must support the specified features and services. FEATURELIST is a list of zero or more features from the following: directoryservice (Active Directory support), globalcatalog (global catalog server for the forest rooted by this domain), pdc (primary domain controller for this domain) kdc (Kerberos Key Distribution center service) timeserver (running Windows Time Service) writable (must not be read-only). Note that the features pdc, kdc and globalcatalog are mutually exclusive and must not be specified together.
-site SITENAME | Specifies the name of the site where the domain controller should be physically located. If an empty string (default), the command will attempt to return a controller in a site that is closest to the site of the system specified by the -system option.
-system COMPUTERNAME | Specifies the DNS or NETBIOS name of the computer on which the lookup is to be done. If unspecified, defaults to the local system.
If the -getdetails option is specified, the command returns detailed information about the controller instead of just its name. The returned information is a flat list of key value pairs with the following elements:

-clientsite | The name of the site containing the system specified by the -system option.
-dcname | Name of the domain controller which may be either in DNS or Netbios format.
-dcnameformat | Either dns if the -dcname field is in DNS format, or netbios if it is a Netbios name.
-dcaddr | Address of the domain controller. This may be either the Netbios address or the IP address depending on the value of the specified -outputaddrformat option.
-dcaddrformat | Either ip if the -dcaddr field is in IP address format, or netbios if it is a Netbios address.
-dcsite | The name of the site containing the domain controller.
-dnsforest | Name of the domain that is at the root of the directory service tree.
-dnsforestformat | Either dns if the -dnsforest field is in DNS format, or netbios if it is a Netbios name.
-domainguid | GUID of the domain.
-domain | Name of the domain.
-domainformat | Either dns if the -domain field is in DNS format, or netbios if it is a Netbios name.
-features | Contains a list describing domain controller features. This list may contain zero or more of the following: closest (domain controller is closest site to client), directoryservice (Active Directory support), ldap (supports LDAP access), globalcatalog (global catalog server for the forest rooted by this domain), pdc (primary domain controller for this domain), kdc (Kerberos Key Distribution center service), timeserver (running Windows Time Service), goodtimeserver (running Windows Time Service with a physical clock), writable (is not read-only).
Note that any of these fields may have empty string values if the information is not relevant or cannot be found.

get_computer_name ?NAMETYPE?
Returns the name of the computer. NAMETYPE must be one of the following:

netbios | Returns the NETBIOS name of the local computer or the cluster virtual server if it is in a cluster.
dnshostname | Returns the DNS host name of the local computer or the cluster virtual server if it is in a cluster.
dnsdomain | Returns the DNS domain of the local computer or the cluster virtual server if it is in a cluster.
dnsfullyqualified | Returns the fully qualified DNS domain of the local computer or the cluster virtual server if it is in a cluster.
physicalnetbios | Returns the NETBIOS name of the local computer.
physicaldnshostname | Returns the DNS host name of the local computer.
physicaldnsdomain | Returns the DNS domain of the local computer.
physicaldnsfullyqualified | Returns the fully qualified DNS name of the local computer.
If NAMETYPE is not specified, it defaults to netbios.

get_computer_netbios_name
Returns the NETBIOS name of the computer.
get_memory_info ?options?
Returns various information about the physical and virtual memory configuration of the system. The information returned is in the form of a flat list of the form "field1 value1 field2 value2 ..." depending on which of the following options are specified:

-all | Returns all the options listed below.
-allocationgranularity | Returns the granularity with which virtual memory is allocated.
-availcommit | Returns the amount of additional memory that can be committed by the system without extending the paging files.
-availphysical | Returns the amount of free physical memory.
-kernelpaged | Returns the amount of memory in the kernel paged pool.
-kernelnonpaged | Returns the amount of memory in the kernel non-paged pool.
-maxappaddr | Returns the highest address that may be mapped into an application's address space.
-minappaddr | Returns the lowest address that may be mapped into an application's address space.
-pagesize | Returns the size of a virtual memory page
-peakcommit | Returns the peak size of the paging files since the last system reboot.
-physicalmemoryload | Percentage of physical memory currently in use.
-processavailcommit | Returns the amount of additional memory that can be committed by the current process.
-processcommitlimit | Returns the maxiumm amount of memory that can be committed by the current process.
-processtotalvirtual | Size of the user-mode virtual address space of the current process.
-processavailvirtual | Size of the user-mode virtual address space that is currently not reserved or committed.
-systemcache | Returns amount of memory used for the system cache.
-swapfiles | Returns a list of the swap files for the system.
-swapfiledetail | Returns a flat list of pairs corresponding to the swap files. The first element of each pair is the name of the swap file. The second element is a list of consisting of the current size of the file (in pages), the number of pages in use, and the peak number of pages that have been used in the file.
-totalcommit | Returns the maximum amount of virtual memory that can be committed without extending the swap files.
-totalphysical | Returns the total amount of physical memory installed in the system.
-usedcommit | Returns the current size of memory committed.

get_numa_config
Returns the NUMA configuration of the system as a dictionary keyed by the NUMA node number. The corresponding value is a nested dictionary with keys -group and -processormask which processors in a processor group comprise that NUMA node.

Returns an empty string if the Windows version does not support NUMA.
get_primary_domain_controller ?options?
Returns the primary domain controller (PDC) for a domain. The command find_domain_controller should be preferred to this command.

The following options may be specified:

-domain DOMAINNAME | Specifies the domain whose PDC is to be retrieved. If unspecified, defaults to the primary domain.
-system COMPUTERNAME | Specifies the DNS or NETBIOS name of the computer on which the lookup is to be done. If unspecified, defaults to the local system.

get_primary_domain_info ?options?
Returns information about the primary domain or workgroup of the system as a flat list of option value pairs. The following options control what information is returned.

-all | Equivalent to specifying all options.
-dnsdomainname | Returns the DNS name of the primary domain.
-dnsforestname | Returns the DNS forest name of the primary domain.
-domainguid | Returns the GUID of the primary domain.
-name | Returns the domain or workgroup name.
-sid | Returns the SID of the primary domain.
-type | Returns workgroup or domain depending on whether the system belongs to a workgroup or a domain.
If the system belongs to a workgroup, all options will return empty values except -name and -type.

get_os_description
This commmand returns the same operating system information as returned by get_os_info but in a form suitable for displaying to a user.
get_os_info
This command retrieves operating system version and configuration information and returns a keyed list with the following fields:

os_build_number | Contains the operating system build number.
os_major_version | Major operating system version.
os_minor_version | Minor operating system version.
sp_major_version | Major service pack version.
sp_minor_version | Minor service pack version.
suites | Contains a list of values (see below) that indicate various options that may be installed as part of the operating system.
system_type | Indicates the operating system base type. This is workstation for Windows NT 4.0 Workstation, Windows 2000 Professional, or any Windows XP operating system versions. If the system is a domain controller, this value is domain_controller. In all other cases, this value is server.
The suites element in the returned array contains a list of values from the following set that indicates additional operating system components that are present:

backoffice | Microsoft BackOffice components are installed.
blade | Windows .NET Server 2003 family Web Edition is installed.
communications | A version of Microsoft Office Communications Server is installed.
compute_server | Windows Server 2003 family Computer Cluster Edition is installed.
datacenter | Datacenter version of Windows 2000, Windows Server 2003 or Windows Server 2008 is installed.
embeddednt | Windows XP Embedded is installed.
embedded_restricted
enterprise | Windows 2000 Advanced Server, or the Enterprise version of Windows Server 2003 or Windows Server 2008 is installed.
personal | A Home Edition of Windows XP, Windows Vista or Windows 7 is installed.
security_appliance | A hardened installation of Windows Server 2003 in a security appliance.
singleuserrts | Remote desktop is supported only for a single interactive session.
smallbusiness | Microsoft Small Business Server is installed.
smallbusiness_restricted | Microsoft Small Business Server is installed with the restrictive client license in force.
storage_server | A Windows Storage Server version of Windows 2003 or Windows 2003 R2 is installed.
terminal | Terminal Services are installed.
wh_server | Windows Home Server is installed.

get_os_version
This command returns the operating system version as list of four elements - the operating system major version number, the operating system minor version number, the service pack major version number, the service pack minor version number.
get_processor_count
Returns the number of processors in the system.
get_processor_group_config
Newer versions of Windows partition processors into processor groups when there more than 64 processors in the system. This command returns information about how the groups are configured. The return value is a dictionary with two keys, -maxgroupcount which is the maximum number of processor groups that can be configured in the system, and -activegroups which is a dictionary keyed by the processor group number. The corresponding value is a nested dictionary with keys -maxprocessorcount, -activeprocessorcount and -processormask which contains the maximum number of processors that can be configured in the group, the number of currently active processors and the group's processor mask.

On older versions of Windows, the information returned will contain the single processor group 0.
get_processor_info PROCESSOR ?options?
Returns various pieces of information related to the processors in the system. PROCESSOR identifies the processor whose information is to be retrieved. If specified as an empty string, information across all processors in the processor group for the current process is returned. Note this is different from processors across the entire system when it has more than 64 processors.

The return value is a dictionary keyed by the specified options:

-all | Returns all fields listed below.
-arch | Returns the processor architecture.
-dpctime | The amount of CPU time in 100ns units spent in servicing deferred procedure calls. Note this value is included in the -privilegedtime value.
-idletime | The amount of idle CPU time in 100ns units since system start. Note this value is included in the -privilegedtime value.
-interrupts | Returns the total number of interrupts serviced since system start.
-interrupttime | The amount of CPU time in 100ns units spent in servicing interrupts. Note this value is included in the -privilegedtime value.
-privilegedtime | The amount of privileged (kernel) context CPU time since system start in 100ns units. Note this includes the DPC, interrupt and idle CPU cycles.
-processormodel | Returns the processor model. PROCESSOR must not be an empty string if this option is specified.
-processorname | Returns a human readable form of the processor description. PROCESSOR must not be an empty string if this option is specified.
-processorrev | Returns the processor revision as defined by the CPU manufacturer. PROCESSOR must not be an empty string if this option is specified.
-processorspeed | Returns the nominal speed in Mhz of the processor PROCESSOR must not be an empty string if this option is specified.
-processorlevel | Returns the processor level as defined by the CPU manufacturer.
-usertime | The amount of user context CPU time in 100ns units since the system was started.

get_system_parameters_info PARAMETER
This command wraps the Windows SystemParametersInfo function and allows retrieval of various user interface settings such as screensaver timeout, mouse speed etc. The information retrieved depends on the PARAMETER which must be one of the SPI_ symbols listed in the SystemParametersInfo documentation.
get_system_sid
Returns the SID of the system.
get_system_time
Returns the current system time in UTC as the number of 100 nanosecond units since Jan 1, 1601. This can be converted to a format suitable for use with the clock command through the use of the command large_system_time_to_secs_since_1970.
get_system_uptime
Returns the number of seconds elapsed since the system was booted.
lock_workstation
Initiates a request to lock the work station display.
logoff ?-force? ?-forceifhung?
Logs off the current session. If -force is specified, it forces processes to terminate without notifying them. This options should generally not be specified as it can result in data loss. If -forceifhung is specified, it only terminates processes if they do not respond to the session end notifications.
min_os_version osmajor ?osminor? ?spmajor? ?spminor?
This function checks that the operating system version meets the specified minimum version. It returns 1 if the operating system version is greater than osmajor.osminor.spmajor.spminor. Otherwise it returns 0. Any unspecified optional arguments default to 0.
set_system_parameters_info PARAMETER VALUE ?-persist? ?-notify?
This command wraps the Windows SystemParametersInfo function and allows setting of various user interface settings such as screensaver timeout, mouse speed etc. The information retrieved depends on the PARAMETER which must be one of the SPI_ symbols listed in the SystemParametersInfo documentation. The corresponding setting is assigned VALUE.

If the -persist is specified, the changed setting is written to the user's profile. If -notify is specified, all applications are notified of the change. Note -notify only has effect if -persist is also specified since other applications will update based on the user's persistent profile.
shutdown_system ?options?
Initiates a system shut down or reboot. The command enables any required privileges and restores the original privileges before returning.

The following options may be specified:

-system SYSTEMNAME | Specifies the system to be shut down. By default, this is the local system.
-timeout SECONDS | Specifies the amount of time to wait before shutting down the system. During this time, a shutdown dialog is displayed to the user. If a value of 0 is specified, the system is shut down immediately and no dialog is displayed to the user.
-message MESSAGE | Specifies a message to be displayed to the user in the shutdown dialog.
-force | Normally, the system displays a dialog box asking the user to close any applications with unsaved data. If the -force option is specified, applications are forcible closed resulting in possible data loss.
-restart | If specified, the system is restarted after the shut down.

suspend_system ?options?
Places the system in a stand by or hibernate state. The command takes the following options:

-state STATE | STATE must be one of standby (default) or hibernate depending on whether the state into which the system is to be placed.
-force BOOLEAN | If false (default), the system sends a PBT_ATMQUERYSUSPEND message to all applications before placing the system in stand by or hibernate states. If this option is specified as true, the message is not sent and the system is immediately placed into the appropriate state.
-disablewakeevents BOOLEAN | If false (default), system wake events remain enabled. If true they are disabled.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Processes, threads and DLLs - Processes, threads and shared libraries

Processes, threads and DLLs

Commands related to processes, threads and dynamic link libraries

SYNOPSIS

package require twapi_process

create_process PROGRAM ?options?
end_process PID ?options?
get_current_process_id
get_current_thread_id
get_device_drivers ?options?
get_module_handle ?-path PATH? ?-pin BOOLEAN?
get_module_handle_from_address ADDRESS ?-pin BOOLEAN?
get_pid_from_handle HPROCESS
get_priority_class PID
get_process_commandline PID ?options?
get_process_elevation ?-pid PID | -hprocess HPROCESS?
get_process_exit_code HPROCESS
get_process_handle PID ?-access ACCESSRIGHTS? ?-inherit INHERITMODE?
get_process_ids ?options?
get_process_info PID ?options?
get_process_integrity ?-pid PID | -hprocess HPROCESS? ?-raw | -label?
get_process_modules PID ?options?
get_process_name PID
get_process_parent PID
get_process_path PID
get_process_thread_ids PID
get_thread_handle TID ACCESSMODE ?INHERITMODE?
get_thread_info TID ?options?
get_thread_relative_priority TID
get_thread_parent_process_id TID
is_idle_pid PID
is_system_pid PID
process_exists PID ?options?
process_in_administrators
process_waiting_for_input PID ?-wait MILLISECONDS?
resume_thread TID
set_priority_class PID PRIORITYCLASS
set_process_integrity INTEGRITY ?-pid PID | -hprocess HPROCESS?
set_process_virtualization ENABLED ?-pid PID | -hprocess HPROCESS?
set_thread_relative_priority TID PRIORITY
SetThreadExecutionState EXECUTIONSTATE
suspend_thread TID
virtualized_process ?-pid PID | -hprocess PROCESSHANDLE?
wow64_process ?-pid PID | -hprocess PROCESSHANDLE?

DESCRIPTION

This module provides procedures related to process, thread and shared library management.

Overview

The commands get_process_ids and get_current_process_id retrieve process id (PID) information. get_process_parent returns the PID for the parent process. The commands is_system_pid and is_idle_pid determine if the given PID is that of the system or idle process.

The command get_current_thread_id retrieves the current thread id (TID). get_thread_parent_process_id retrieves the PID of the process containing the specified thread. get_process_thread_ids retrieves the TID's of all threads in the specified process.

Process and thread handles with the appropriate access rights may retrieved through the get_process_handle and get_thread_handle commands respectively. A process handle may be mapped back to the corresponding PID through get_pid_from_handle.

get_process_name and get_process_path get the name and path respectively for a process. The command get_process_info retrieves detailed information about internal process data. Similarly, get_thread_info retrieves detailed information about a thread.

get_process_commandline retrieves the command line with which a process was invoked.

process_exists checks for the existence of a process. The command process_waiting_for_input can be used to check if a process is waiting for input, and more specifically if it has finished initialization.

get_process_modules retrieves information pertaining to the modules and DLL's loaded into a process. The commands get_module_handle and get_module_handle_from_address retrieve handles to individual modules in the current process.

The commands create_process and end_process allow creation and termination of a process. The exit code from a process can be retrieved with the get_process_exit_code command.

The commands suspend_thread and resume_thread allow threads to be suspended and resumed.

The commands get_priority_class, set_priority_class, get_thread_relative_priority and set_thread_relative_priority deal with retrieving and setting process and thread scheduling priorities.

get_device_drivers retrieves information about the device drivers loaded on the system.

Commands is_wow64_process deal with features related to 64-bit Windows.

Command process_in_administrators can be used to check if the current process is in the administrators group.

Commands get_process_elevation, get_process_integrity and, set_process_integrity and, virtualized_process, set_process_virtualization deal with Windows UAC related features.

Commands

create_process PROGRAM ?options?
Creates a new child process. PROGRAM specifies the program to be run and must either include the full path to the program or the program must be in the current working directory. The function does not search the PATH environment variable to locate the program. PROGRAM may be specified as an empty string if the -cmdline option is specified and includes the path to the program as the first argument.

The command returns a list of two elements - the process id and the thread id of the child process. If the -returnhandles option is specified, two additional elements are returned - handles to the child process and thread. Both these handles must be closed when no longer required by calling close_handles.

The following arguments control various characteristics of the child process. For all options that take a boolean argument, the default is 0 (false) unless stated otherwise.

-background COLORLIST | Specifies the background color if the child process receives a new console. COLORLIST is a list of one or more of the following values: blue, red, green, bright, white and black. The specified colors are combined to form the foreground color. The default is black.
-cmdline CMDLINE | Specifies the command line to be passed to the created process. This generally includes the program being executed as the first token in CMDLINE. Caller should ensure that CMDLINE is quoted appropriately. The -cmdline option must be specified if the PROGRAM parameter is empty.
-childprocesssecd SECURITY_DESCRIPTOR | Specifies a security descriptor for the child process. If unspecified, the default security descriptor is used.
-childthreadsecd SECURITY_DESCRIPTOR | Specifies a security descriptor for the child thread. If unspecified, the default security descriptor is used.
-createsuspended BOOLEAN | If BOOLEAN is true, the process and thread are created suspended. The process will not run until the thread is resumed with a call to resume_thread.
-debugchild BOOLEAN | If BOOLEAN is true, indicates that the calling thread will be debugging the child process being created. The thread is notified of debug events in the child process. There is currently no way to receive these events.
-dontdebugchild BOOLEAN | If the calling process is itself being debugged, then any debug events from the child process are sent to the debugger if BOOLEAN is false. Otherwise, the child process has no interaction with the debugger.
-desktop DESKTOPNAME | Specifies the desktop, optionally along with the window station, for the new process. By default, this is the same as the current process. If DESKTOPNAME is the empty string, the system determines if a new desktop and window station need to be created.
-detached BOOLEAN | This option only affects console processes. If BOOLEAN is 0, the child process inherits the current process' console. If BOOLEAN is 1, the console is not inherited.
-env LIST | Specifies the environment variables inherited by the child process. LIST is a flat list of the form returned by array get consisting of ENVVARNAME VALUE pairs. By default, the child process inherits the same environment variables as the current process.
-feedbackcursoron BOOLEAN | If true, specifies that the feedback cursor (normally a pointer with an hourglass) is shown while the new process starts up.
-feedbackcursoroff BOOLEAN | If true, specifies that the feedback cursor is not shown while the new process starts up.
-foreground COLORLIST | Specifies the foreground color if the child process receives a new console. COLORLIST is a list of one or more of the following values: blue, red, green, bright, white and black. The specified colors are combined to form the foreground color. The default is white.
-fullscreen BOOLEAN | If true, the child process is run in full screen mode if it is a console process.
-inheritablechildprocess BOOLEAN | If true, the handle to the child process is inheritable by other child processes spawned off later.
-inheritablechildthread BOOLEAN | If true, the handle to the thread in the child process is inheritable by other child processes spawned off later.
-inheriterrormode BOOLEAN | If true (default), the child process inherits the error mode setting of the current process.
-inherithandles BOOLEAN | If true, the child process will inherit all inheritable handles of the current process.
-newconsole BOOLEAN | If true, a new console is created for the child process if it is a console mode program. By default, the child process inherites the console of the current process if that latter is also a console mode program. This option cannot be used with the -detached option.
-priority PRIORITY | Specifies the priority of the child process. This should have one of the values normal, abovenormal, belownormal, high, realtime, or idle.
-returnhandles BOOLEAN | Normally the create_process command returns only the ids of the created process and thread. If this option is specified as true, the command appends handles of the child process and thread to the return value. These must later be closed by calling the close_handles command.
-screenbuffersize XY | For console processes, this controls the initial width and height of the screen buffer in characters. XY can be specified as either a list of two integers or as a X,Y string.
-separatevdm BOOLEAN | If true, child processes that are 16-bit executables are started in a separate virtual machine. By default, the system will follow the setting specified in the registry.
-sharedvdm BOOLEAN | If true, child processes that are 16-bit executables are started in a common virtual machine. By default, the system will follow the setting specified in the registry.
-showwindow WINDOWMODE | Specifies the mode in which the first window of the child process is displayed. WINDOWMODE must be one of normal, minimized, maximized or hidden.
-startdir PATH | Specifies the initial starting directory of the child process. By default the child process starts in the calling thread's current directory.
-stdhandles HANDLELIST Specifies the standard input and output handles for the child process. HANDLELIST is a list of three elements corresponding to the handles to be used for standard input, standard output and standard error respectively. The handle values passed must be Windows handles and must be inheritable. Also, the -inherithandles option must be true if -stdhandles is specified. Note that if these handles correspond to files, the file position pointer is shared with the child process.

This option cannot be used together with the -stdchannels option.
-stdchannels CHANNELS Specifies the standard input and output handles for the child process. CHANNELS is a list of three elements corresponding to the Tcl channels to be used for standard input, standard output and standard error respectively. Note that if these channels correspond to files, the file position pointer is shared with the child process.

This option cannot be used together with the -stdhandles option. Also, the -inherithandles option must be true if -stdchannels is specified.
-title TITLE | Specifies the text to diaplay in the title bar if the child process is a console program and receives a new console. By default, the name of the executable is displayed.
-windowpos XY | Specifies the initial position in pixels of the top left corner of the main window of the child process if the child creates the window using defaults. XY can be specified as either a list of two integers or as a X,Y string.
-windowsize XY | Specifies the initial size in pixels of the main window of the child process if the child creates the window using defaults. XY can be specified as either a list of two integers or as a X,Y string.
For further details, see the documentation of CreateProcess in the Windows SDK documentation.

end_process PID ?options?
Terminates the process with id PID. This function will first try to gracefully end the process by sending all its toplevel windows a WM_CLOSE command. If the process does not have any toplevels or if it does not end by this means and the -force option is specified, it is forcibly terminated.

The function returns 1 if the process ended and 0 otherwise. Note that if -wait has not been specified, or is too short, the function may return a value of 0 in the case where the process is in the process of terminating but has not fully exited by the time the command returns.

The following options may be specified with this command:

-force | If this option is specified, the process will be forcibly terminated if it does not terminate in response to WM_CLOSE messages.
-wait MS | Normally, the function will return without actually waiting for the process to end. If this option is specified, the function returns after waiting for MS milliseconds for the process to end.
-exitcode EXITCODE | Specifies the exit code that should be returned by the terminating process. This is 1 by default. Depending on the application being terminated, this may not be the actual exit code returned on application exit. Caller should not rely on this.

get_current_process_id
Returns the PID of the current process.
get_current_thread_id
Returns the TID of the current thread.
get_device_drivers ?options?
Returns a record array describing the device drivers loaded in the system. The fields of the record array are based on which of the following options are specified:

-all | Returns all device driver attributes below.
-base | Returns the base address in memory where the driver is loaded
-path | Returns the path to the file from which the driver was loaded. In some cases, this may not contain a fully qualified path.
-name | Returns the name of the driver - generally the file name portion of the file from which the driver was loaded.

get_module_handle ?-path PATH? ?-pin BOOLEAN?
Retrieves a handle for a module loaded in the process. If no arguments are specified, returns a handle to the .exe file from which calling process was created.

If the -path option is present, the command returns a handle to the module loaded from the file specified by PATH. PATH may be either a full path or just the file name.

The command will normally increment the reference count for the specified module. The returned handle must later be released by calling free_library (not close_handle). However, if the -pin option is specified as true, the module will stayed loaded until the process terminates irrespective of how many calls are made to free it.
get_module_handle_from_address ADDRESS ?-pin BOOLEAN?
Retrieves a handle for the module in whose address range the specifed ADDRESS lies.

The command will normally increment the reference count for the specified module. The returned handle must later be released by calling free_library (not close_handle). However, if the -pin option is specified as true, the module will stayed loaded until the process terminates irrespective of how many calls are made to free it.
get_pid_from_handle HPROCESS
Returns the PID of the process corresponding to the process handle HPROCESS.
get_priority_class PID
Returns the scheduling priority class of the process with id PID.
get_process_commandline PID ?options?
Returns the command line with which the process with id PID was invoked. The following options may be specified with the command.

-noexist DEFAULTVALUE | If a process does not exist, the command returns the string "(no such process)". This option may be used to specify a different string to be returned for non-existent processes.
-noaccess DEFAULTVALUE | If a process exists but cannot be accessed to retrieve the name, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.

get_process_elevation ?-pid PID | -hprocess HPROCESS?
If no options are specified, information for the current process is returned. A different process may be specified using its PID with the -pid option, or with a handle to it through the -hprocess option.

See get_token_elevation for details on the return value and semantics of this command.
get_process_exit_code HPROCESS
Returns the exit code for a process. HPROCESS is a handle to the process of interest. If the process is still running, a null string is returned.
get_process_handle PID ?-access ACCESSRIGHTS? ?-inherit INHERITMODE?
Returns a handle to the process with id PID. If option -access is specified, ACCESSRIGHTS are the desired access rights and may be specified as a list of integer access rights flags or symbols as described in Access Rights. If option -inherit is specified and INHERITMODE is non-0, the returned handle can be inherited by child processes. If it is 0 (default), the handle cannot be inherited by child processes.
get_process_ids ?options?
This command returns a list of the process ids. If no options are specified, the list includes all processes on the system. The following options may be specified to return a subset of these:

-glob | This option modifies the meaning of the -path and -name options. Normally, the match is done using case-insensitive, exact comparison. If -glob is specified, the PROCESSNAME and EXECUTABLEPATH are matched using glob-style pattern matching as in Tcl's string match command.
-name PROCESSNAME | If this option is specified, the returned list only includes those processes whose name matches PROCESSNAME. Generally the name is the same as the filename portion of the executable file path. If this information is not available for a process, it is not included in the returned list. This option cannot be used with the -path option.
-path EXECUTABLEPATH | If this option is specified, the returned list only includes those processes created from the executable file matching EXECUTABLEPATH. If this information is not available for a process, it is not included in the returned list. This option cannot be used with the -name option.
-logonsession LUID | If this option is specified, the returned list only includes those processes running inside the logon session identified by the specified LUID.
-user ACCOUNT | If this option is specified, the returned list only includes those processes running under the specified account. ACCOUNT may be either a user name or its SID.

get_process_info PID ?options?
Returns various pieces of information related to the process whose id is PID. The information returned is dictionary whose keys are one or more of the following options that specify the information to be returned:

-all | Returns all values except those for unsupported options.
-basepriority | Returns the base priority of the process.
-commandline | Returns the command line with which the process was invoked.
-createtime | Returns the time the process was created as the number of 100ns units since Jan 1, 1601. This can be converted to a date and time string by passing it to large_system_time_to_secs and formatting the result using clock format.
-disabledprivileges | Returns the list of privileges for the process that are currently disabled.
-elapsedtime | Returns the total time (seconds) that the process has been running.
-elevation | Returns the elevation level of the process (see get_process_elevation).
-enabledprivileges | Returns the list of privileges that are enabled in the process.
-groupattrs | Returns the list of groups SIDs and attributes in the process security token. See get_token_info for a description of the return value.
-groups | Returns the list of groups that the process belongs to. For domain accounts, an error is raised if the domain is unreachable. Use -groupattrs to avoid this.
-handlecount | Returns the number of handles that the process currently has open.
-integrity | Returns the numeric integrity level of the process (see get_process_integrity).
-integritylabel | Returns the label for the integrity level range of the process (see get_process_integrity).
-iootherbytes | Returns number of non-data bytes the process has read or written through I/O operations.
-iootherops | Returns number of non-data I/O operations the process has executed.
-ioreadbytes | Returns number of data bytes the process has read through I/O operations.
-ioreadops | Returns number of data read I/O operations the process has executed.
-iowritebytes | Returns number of data bytes the process has written through I/O operations.
-iowriteops | Returns number of data write I/O operations the process has executed.
-logonsession | Returns the LUID of the logon session for the process.
-name | Returns the name of the process. This is identical to the value returned by the get_process_name function.
-noaccess DEFAULTVALUE | If a process exists but cannot be accessed to retrieve the name, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.
-noexist DEFAULTVALUE | If a process does not exist, the command returns the string "(no such process)". This option may be used to specify a different string to be returned for non-existent processes.
-pagefilebytes | Returns total number of bytes in use for this process in all the system paging files.
-pagefilebytespeak | Returns the maximum number of bytes that have been used for this process in the system paging file since the process started.
-parent | Returns id of the process that invoked this process. For the system and system idle processes, an empty string is returned since they have no parent process.
-path | Returns the path to the executable file from which this process was invoked. This value is the same as that returned by the get_process_path command.
-pid | Returns the process id of this process, which will be identical to that passed in as the PID argument if the process exists. Otherwise it is set to the value of the -noexist option.
-poolnonpagedbytes | Returns the number of bytes of nonpaged pool memory in use for the process.
-poolpagedbytes | Returns the number of bytes of paged pool memory in use for the process.
-primarygroup | Returns the primary group that the process belongs to. For domain accounts, an error is raised if the domain is unreachable. Use -primarygroupsid to avoid this.
-primarygroupsid | Returns the SID of primary group that the process belongs to.
-priorityclass | Returns the priority class of the process.
-privilegedtime | The amount of privileged context CPU time used by the process in 100ns units.
-privileges | Returns the list of enabled and disabled process privileges in the same format as get_token_privileges. Deprecated, use -enabledprivileges and -disabledprivileges instead.
-restrictedgroupattrs | Returns the list of restricted group SIDs and attributes in the process security token. See get_token_info for a description of the return value.
-restrictedgroups | Returns the list of restricted groups in the process security token. For domain accounts, an error is raised if the domain is unreachable. Use -restrictedgroupattrs to avoid this.
-threadcount | Returns the total number of threads in the process.
-tids | Returns a list of ids of the threads in the process.
-tssession | Returns the terminal server session id of the process.
-user | Returns the user account under which the process is running.
-usertime | The amount of user context CPU time used by the process in 100ns units.
-virtualbytes | Returns the current size of the process' virtual address space.
-virtualbytespeak | Returns the maximum amount of virtual address space that the process has used in the course of its execution.
-virtualized | Returns trued if the process is virtualized and false otherwise. See virtualized_process.
-workingset | Returns the number of bytes currently in the process' working set.
-workingsetpeak | Returns the maximum number of bytes in the process' working set since it began execution.
Note that all the information is not retrieved in a single snapshot so there may be discrepancies between various values. For example, the number of thread ids returned via -tids may not match the thread count returned via -threadcount.

The get_process_info command is intended for one-time retrieval of information and is too inefficient for usage in an application like performance monitoring. Direct access to the performance data should be used in those cases.

get_process_integrity ?-pid PID | -hprocess HPROCESS? ?-raw | -label?
If no options are specified, information for the current process is returned. A different process may be specified using its PID with the -pid option, or with a handle to it through the -hprocess option.

See get_token_integrity for details on the other options, return value and semantics of this command.
get_process_modules PID ?options?
This command returns information about the modules loaded in the process with id PID. If no options are specified, the command returns a list of handles to the modules.

If any options are specified, the returned information is a record array with one record per module. The fields of the record array depend on which of the following options are specified.

-all | Returns the data for all options described below.
-base | Includes the base address of the module.
-entry | Includes the address of the entry point to the module.
-handle | Includes the handle to the module in the returned data for each module.
-name | Includes the name of the module - generally the file name portion of the path.
-path | Includes the full path from which the module was loaded.
-size | Includes the size of the module.

get_process_name PID
Returns the name of the process with id PID. This is generally the file name component of the full path of the executable file from which the process was loaded. The following options may be specified to with the command:

-noexist DEFAULTVALUE | If a process does not exist, the command returns the string "(no such process)". This option may be used to specify a different string to be returned for non-existent processes.
-noaccess DEFAULTVALUE | If a process exists but cannot be accessed to retrieve the name, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.

get_process_parent PID
Returns the PID of the process from whom the process with id PID inherited handles and environment. An empty string is returned if PID corresponds to the System or the System Idle Process. The following options may be specified to with the command:

-noexist DEFAULTVALUE | If a process does not exist, the command returns the string "(no such process)". This option may be used to specify a different string to be returned for non-existent processes.
-noaccess DEFAULTVALUE | If a process exists but cannot be accessed to retrieve the parent, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.

get_process_path PID
Returns the full path of the executable file from which the process with id PID was loaded. The following options may be specified to with the command:

-noexist DEFAULTVALUE | If a process does not exist, the command returns the string (no such process). This option may be used to specify a different string to be returned for non-existent processes.
-noaccess DEFAULTVALUE | If a process exists but cannot be accessed to retrieve the path information, the command normally returns the string (unknown). This option may be used to specify a different string to be returned in such cases.

get_process_thread_ids PID
Returns a list of ids of all threads in the process whose id is PID.
get_thread_handle TID ACCESSMODE ?INHERITMODE?
Returns a handle to the thread with id TID. ACCESSMODE specifies the desired access rights and may be specified as a list of integer access rights flags or symbols. Refer to the documentation of TWAPI Security module for more details. If INHERITMODE is non-0, the returned handle can be inherited by child processes. If it is 0 (default), the handle cannot be inherited by child processes.
get_thread_info TID ?options?
Returns various pieces of information related to the thread whose id is TID. The return value is a dictionary whose keys are one or more of the following options that specify what information is to be returned:

-all | Returns all values.
-basepriority | Returns the base priority of the thread.
-contextswitches | Returns the number of context switches done by the thread.
-createtime | Returns the time the thread was created as the number of 100ns units since Jan 1, 1601. This can be converted to a date and time string by passing it to large_system_time_to_secs and formatting the result using clock format.
-disabledprivileges | Returns the list of privileges for the thread that are currently disabled.
-elapsedtime | Returns the total time (seconds) that the thread has been running.
-enabledprivileges | Returns the list of privileges that are enabled in the thread.
-groupattrs | Returns the list of groups SIDs and attributes in the thread's security token. See get_token_info for a description of the return value.
-groups | Returns the list of groups that the thread belongs to. For domain accounts, an error is raised if the domain is unreachable. Use -groupattrs to avoid this.
-interval INTERVAL | Specifies the number of milliseconds over which rate based fields are to be measured. The command will not return until this time has elapsed. By default this is 100ms. If none of the fields requested is a rate based field, this option is ignored and the command returns immediately.
-noaccess DEFAULTVALUE | If a thread but cannot be accessed, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.
-noexist DEFAULTVALUE | If a thread does not exist, the command returns the string "(no such thread)". This option may be used to specify a different string to be returned for non-existent threads.
-pid | Returns the id of the process the thread belongs to.
-primarygroup | Returns the primary group that the thread belongs to. For domain accounts, an error is raised if the domain is unreachable. Use -primarygroupsid to avoid this.
-primarygroupsid | Returns the SID of primary group that the process belongs to.
-priority | Returns the current priority of the thread.
-privilegedtime | The amount of privileged context CPU time used by the thread in 100ns units.
-privileges | Returns the list of the current thread privileges. Deprecated, use -enabledprivileges and -disabledprivileges instead.
-relativepriority | Returns the priority level of the thread relative to the priority class of the containing process.
-restrictedgroupattrs | Returns the list of restricted group SIDs and attributes in the thread's security token. See get_token_info for a description of the return value.
-restrictedgroups | Returns the list of restricted groups in the thread's security token. For domain accounts, an error is raised if the domain is unreachable. Use -restrictedgroupattrs to avoid this.
-startaddress | Returns the address at which the thread began execution.
-state | Returns the current state of the thread.
-tid | Returns the thread id of this process (which should be identical to that passed in as the TID argument.
-user | Returns the user account under which the thread is running.
-usertime | The amount of user context CPU time used by the thread in 100ns units.
-waitreason | Returns the reason a thread is in wait state. This is only valid when the state field is 5 indicating the thread is in a wait state.
Note that all the information is not retrieved in a single snapshot so there may be discrepancies between various values.

Like the get_process_info command, get_thread_info is intended for one-time retrieval of information and is too inefficient for usage in an application like performance monitoring. Direct access to the performance data should be used in those cases.

get_thread_relative_priority TID
Returns the scheduling priority value of the thread with id TID. This is an integer value relative to the process' priority class as described in the Windows SDK.
get_thread_parent_process_id TID
Returns the id of the parent process of the thread with id TID.
is_idle_pid PID
Returns true if the passed PID is that of the system idle process.
is_system_pid PID
Returns true if the passed PID is that of the system process.
process_exists PID ?options?
This command returns 1 if a process with id PID exists and 0 otherwise. The following options may be specified to further restrict the match:

-path EXECUTABLEPATH | If this option is specified, the matched process must have been created from the executable file matching EXECUTABLEPATH. This option cannot be used with the -name option.
-name PROCESSNAME | If this option is specified, the matched process must have a name that matches PROCESSNAME. Generally the name is the same as the filename portion of the executable file path. This option cannot be used with the -path option.
-glob | This option modifies the meaning of the -path and -name options. Normally, the match is done using case-insensitive, exact comparison. If -glob is specified, the PROCESSNAME and EXECUTABLEPATH are matched using glob-style pattern matching.

process_in_administrators
Returns true if a process belongs to an account which is in the Windows administrators group and false otherwise.
process_waiting_for_input PID ?-wait MILLISECONDS?
Returns 1 if the specified process is idle, waiting for input, and 0 otherwise. The main use of this command is to detect when a process (for example, a child process that has just been created) has finished initialization. Note that a console process will always return 1.

The command normally returns right away. Specifying the -wait option causes the command to wait until either MILLISECONDS have passed or the process is idle before returning. Specifying a value of -1 will cause the command to wait without timing out.
resume_thread TID
The command checks the suspend count (see suspend_thread) of the specified thread. If it is 0, the thread is not suspended and the command has no effect. Otherwise, the suspend count is decremented. If the value is now 0, the thread resumes execution. The command returns thread's previous suspend count - a value of 0 meaning the thread was not suspended, 1 meaning the suspending thread is not resumed, and other values signifying that the thread is still suspended.
set_priority_class PID PRIORITYCLASS
Sets the scheduling priority class of the process with id PID to PRIORITYCLASS. PRIORITYCLASS is an integer value identifying a priority class as described in the Windows SDK.
set_process_integrity INTEGRITY ?-pid PID | -hprocess HPROCESS?
Sets the integrity level of a process to INTEGRITY. If no options are specified, the integrity level of the current process is modified. A different process may be specified using its PID with the -pid option, or with a handle to it through the -hprocess option.

See set_token_integrity for possible values of INTEGRITY.
set_process_virtualization ENABLED ?-pid PID | -hprocess HPROCESS?
Enables or disables the virtualization state of a process depending on the boolean value of ENABLED. If no options are specified, the virtualization level of the current process is modified. A different process may be specified using its PID with the -pid option, or with a handle to it through the -hprocess option.

See set_token_integrity for more information.
set_thread_relative_priority TID PRIORITY
Sets the scheduling priority value of the thread with id TID to PRIORITY. PRIORITY is an integer value relative to the process' priority class as described in the Windows SDK.
SetThreadExecutionState EXECUTIONSTATE
Refer to the Windows SDK documentation for details.
suspend_thread TID
Suspends execution of the thread with id TID. The system keeps track of a suspend count for each thread. This is incremented every time a call is made to suspend the thread, and decremented every time a call is made to resume it. The command returns thread's previous suspend count.
virtualized_process ?-pid PID | -hprocess PROCESSHANDLE?
Returns true if a process is running as a virtualized process where the system redirects writes to protected file and registry locations and false otherwise. On systems that do not support UAC, the command will always return false.

With no options specified, the command checks the current process. If the -pid option is specified, it checks the process with the specific PID. If the -hprocess option is specified, PROCESSHANDLE must be a handle to the process to be checked. The two options must not be used together.
wow64_process ?-pid PID | -hprocess PROCESSHANDLE?
Returns true if a process is running as a 32-bit Windows process on a 64-bit Windows system and returns false otherwise. With no options specified, the command checks the current process. If the -pid option is specified, it checks the process with the specific PID. If the -hprocess option is specified, PROCESSHANDLE must be a handle to the process to be checked. The two options must not be used together.

COPYRIGHT

Copyright © 2003-2012 Ashok P. Nadkarni


Services - Windows services configuration

Services

Commands for configuring and monitoring Windows services

SYNOPSIS

package require twapi_service

continue_service INTERNAL_SERVICE_NAME ?options?
create_service INTERNAL_SERVICE_NAME COMMAND ?options?
delete_service INTERNAL_SERVICE_NAME ?options?
get_dependent_service_status INTERNAL_SERVICE_NAME ?options?
get_multiple_service_status ?options?
get_service_configuration INTERNAL_SERVICE_NAME ?options?
get_service_display_name SERVICE_NAME ?options?
get_service_internal_name SERVICE_NAME ?options?
get_service_state INTERNAL_SERVICE_NAME
get_service_status INTERNAL_SERVICE_NAME ?options?
interrogate_service INTERNAL_SERVICE_NAME ?options?
pause_service INTERNAL_SERVICE_NAME ?options?
run_as_service SERVICES ?-interactive BOOLEAN? ?-controls CONTROLLIST?
service_exists SERVICE_NAME ?options?
set_service_configuration INTERNAL_SERVICE_NAME ?options?
start_service INTERNAL_SERVICE_NAME ?options?
stop_service INTERNAL_SERVICE_NAME ?options?
update_service_status SERVICENAME SEQNO STATE ?options?

DESCRIPTION

This module provides procedures for managing and controlling Windows services and also allows for writing Windows services in Tcl.

Service Configuration and Monitoring

The commands get_service_internal_name and get_service_display_name map back and forth between the internal name and display name of a service.

The command service_exists checks for the existence of a service while get_service_state returns its state. The commands get_service_status, get_multiple_service_status and get_dependent_service_status retrieve status information for one or more services. interrogate_service can be used to request a service to update its status with the service control manager (SCM).

Service configuration changes, including creation of new services and deletion of existing ones, can be done through the commands create_service, delete_service, get_service_configuration and set_service_configuration.

The commands start_service, stop_service, pause_service and continue_service control the run state of a service.

Writing services in Tcl

The command run_as_service allows an application to run as a Windows service. Services are implemented as callback handlers that are invoked in response to control signals received from the system. These signals include controls to stop the service, to pause and continue, or may be notifications of events such as session changes. The list of such signals and their handling is detailed in run_as_service.

While running as a service, applications need can update their status with the SCM, either asynchronously or in response to control signals. This can be done through update_service_status.

Standard Options

Most commands allow the following options to be specified:

-system SYSTEMNAME | Specifies the name of the system on which the command should be invoked. By default, this is the local system.
-database DATABASE | Specifies the service control database to be operated on. By default, this is the active service control database on the target system.

Commands

continue_service INTERNAL_SERVICE_NAME ?options?
This command resumes the specified service which must be in a paused state. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The command returns 1 if the service has resumed to a running state when the command completes and 0 otherwise. Note that a return value of 0 does not imply an error, just that the service had not completely resumed by the time the command returned.

The standard options described in Standard Options may be specified with this command. In addition, if the option "-wait MILLISECONDS" is specified the command will wait until the service is running or until MILLISECONDS milliseconds have expired.
create_service INTERNAL_SERVICE_NAME COMMAND ?options?
This command creates a new Windows service in the service control manager database.

INTERNAL_SERVICE_NAME is the internal name by which the service is identified by the service control manager.

COMMAND contains the system command to be executed to start the service. This includes the path to the executable as well as arguments to be passed to it. If the path contains spaces, it must be specifically quoted else the operating system will interpret all characters after the first space as arguments to be passed to the service. For example,

"\"C:\\Program Files\\MyService\\service.exe\" arg1 arg2"

In addition to the Standard Options, the following additional options may be specified which control various aspects of the service:

-displayname DISPLAYNAME | Specifies the user visible name for the service. This is the name that is shown in the net start command and the SCM control panel applet.
-servicetype SERVICETYPE Specifies the service type and may have one of the following values:

win32_own_process | Service that runs in its own process. This corresponds to the SERVICE_WIN32_OWN_PROCESS in the Windows SDK documentation. This is the default if the option is not specified.
win32_share_process | Service that runs inside a process shared with other services. This corresponds to the SERVICE_WIN32_SHARE_PROCESS in the Windows SDK documentation.
file_system_driver | File system driver. This corresponds to the SERVICE_FILE_SYSTEM_DRIVER in the Windows SDK documentation.
kernel_driver | Kernel driver. This corresponds to the SERVICE_KERNEL_DRIVER in the Windows SDK documentation.

-interactive BOOLEAN | This option specifies whether the service should be allowed to interact with the desktop. This is only valid when -servicetype is specified to be win32_own_process or win32_share_process. The -account option must not be used with this option since interactive services must run under the LocalSystem account.
-starttype STARTTYPE Specifies how the service is to be started. STARTTYPE should have one of the following values:

auto_start | The service should be automatically started by the service control manager during system startup. This is the default if the option is not specified.
boot_start | The service should be automatically started by the system loader during system boot. This is only valid when -servicetype is specified to be kernel_driver or file_system_driver.
demand_start | The service should be started by the system upon receiving an explicit program request.
disabled | The service is disabled and cannot be started even on program request.
system_start | The service is a driver that is started by the operating system IoInitSystem function during system initialization. This is only valid when -servicetype is specified to be kernel_driver or file_system_driver.

-errorcontrol ERRORCONTROLMODE This option specifies how errors during service start are to be handled. ERRORCONTROLMODE may have one of the following values:

ignore | An error message will be logged to the Windows event log. The system startup will continue.
normal | An error message will be logged to the Windows event log and a popup displayed to the user. The system startup will continue. This is the default.
severe | An error message will be logged to the Windows event log. The system startup will continue only if the last known good configuration is active. Otherwise, the system is restarted with the last known good configuration.
critical | An error message will be logged to the Windows event log if possible. If the last known good configuration is active, the system startup is aborted. Otherwise, the system is restarted with the last known good configuration.

-loadordergroup GROUPNAME | Specifies GROUPNAME to be the service load order group to which the service belongs. If the option is not specified, the service is assumed to not belong to any load order group.
-dependencies DEPENDENCYLIST | Specifies the services and service load order groups that are required by this service and that must start before this service. DEPENDENCYLIST is a list of service names and load order groups. A load order group name must be prefixed with a + character to indicate that it is a group name and not a service.
-account ACCOUNTNAME | Specifies ACCOUNTNAME to be the user account under which the service should run. ACCOUNTNAME takes the form domain\username. If the account is a local account, ACCOUNTNAME may be specified as .\username or username. If this option is not specified, the service will run under the LocalSystem account. When -servicetype is kernel or filesystem, ACCOUNTNAME should be the name of the driver object that the system uses to load the driver.
-password PASSWORD | Specifies the password corresponding to the user account specified in the -account option. PASSWORD but should be in encrypted form as returned by by the read_credentials or conceal commands. This option is ignored if the -account option is not specified.

delete_service INTERNAL_SERVICE_NAME ?options?
This command deletes the specified service from the service control manager database. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The standard options described in Standard Options may be specified with this command.
get_dependent_service_status INTERNAL_SERVICE_NAME ?options?
Retrieves the status of services that are dependent on INTERNAL_SERVICE_NAME and that match a specified service state. The standard options described in Standard Options may be specified with this command. In addition, the following options may be specified to only include services in a given state. If neither of these is specified, services in all states are included in the returned list.

-inactive | Specifying this option will result in inclusion of services that are in the stopped state.
-active | Specifying this option will result in inclusion of services that are not in the stopped state.
The command returns a record array with the following fields.

checkpoint | Contains the last checkpoint value reported by the service during a lengthy operation.
controls_accepted | Contains a bitmask indicating the control commands accepted by the service. Refer to the Windows SDK documentation for ControlService for details.
displayname | Indicates the user visible name of the service
exitcode | The last exit code of the service. If this value is 1066, a service specific error code is returned in the service_code field.
interactive | Indicates whether the service is allowed to interact with the desktop (1) or not (0).
name | Indicates the internal name of the service
service_code | In case the exitcode field contains 1066, this field contains a service specific code stored by the service.
serviceflags | Integer value. If the low bit is set, the service runs in a system process that must alway be running.
servicetype | Indicates the type of the service, and is one of win32_own_process, win32_share_process, kernel_driver, file_system_driver, adapter, recognizer_driver or an integer denoting the type if not one of the above.
state | Contains the latest reported status of the service and may have one of the values stopped, start_pending, stop_pending, running, continue_pending, pause_pending, paused or an integer value indicating the status of the service if not one of the above.
wait_hint | Estimated time required to complete an start, stop, pause or continue operation as last reported by the service.

get_multiple_service_status ?options?
Retrieves the status of multiple services matching the specified service type and/or state. The standard options described in Standard Options may be specified with this command. In addition, the options may be specified to only include services of a given type and in a given state.

One or more from the following service type options may be specified to limit the types of services that are included in the returned list: -kernel_driver, -file_system_driver, -win32_own_process, -win32_share_process, -adapter or -recognizer_driver. See the description of the -servicetype option in the create_service command for the semantics of these values. If no service type options are specified, all types of services are included in the returned list.

One of the following options may be specified to limit the returned services to those in a specific state. If neither of these is specified, services in all states are included in the returned list.

-inactive | Specifying this option will result in inclusion of services that are in the stopped state.
-active | Specifying this option will result in inclusion of services that are not in the stopped state.
The command returns a record array with the following fields.

checkpoint | Contains the last checkpoint value reported by the service during a lengthy operation.
controls_accepted | Contains a bitmask indicating the control commands accepted by the service. Refer to the Windows SDK documentation for ControlService for details.
displayname | Indicates the user visible name of the service
exitcode | The last exit code of the service. If this value is 1066, a service specific error code is returned in the service_code field.
interactive | Indicates whether the service is allowed to interact with the desktop (1) or not (0).
name | Indicates the internal name of the service
pid | The PID of the process in which the service is running. A value of -1 indicates the service is stopped or that the process id of the service cannot be determined.
service_code | In case the exitcode field contains 1066, this field contains a service specific code stored by the service.
servicetype | Indicates the type of the service, and is one of win32_own_process, win32_share_process, kernel_driver, file_system_driver, adapter, recognizer_driver or an integer denoting the type if not one of the above.
state | Contains the latest reported status of the service and may have one of the values stopped, start_pending, stop_pending, running, continue_pending, pause_pending, paused or an integer value indicating the status of the service if not one of the above.
wait_hint | Estimated time required to complete an start, stop, pause or continue operation as last reported by the service.

get_service_configuration INTERNAL_SERVICE_NAME ?options?
This command returns the current configuration data for the specified service. INTERNAL_SERVICE_NAME is the internal name by which the service is identified by the service control manager. The standard options described in Standard Options may be specified with this command.

The return value is a dictionary which can be passed to the set_service_configuration command. The keys of the returned dictionary depend on which of the following options are specified:

-all | Returns all option values
-description | Returns description of the service if available, otherwise the empty string.
-displayname | Returns the user visible name of the service.
-errorcontrol | Returns an indication of how errors during service startup will be handled. See description of create_service for details.
-servicetype | Returns the service type. See description of create_service for details.
-interactive | Returns 1 if the service is allowed to interact with the desktop and 0 otherwise.
-loadordergroup | Returns the name of the service load order group to which the service belongs.
-dependencies | Returns a list of names of services and service load order groups that are required by this service and that must start before this service.
-account | Returns the user account under which the service runs.
-starttype | See description of create_service for details.
-command | Returns the command, including the executable name and parameters, that is invoked to run the Windows service.

get_service_display_name SERVICE_NAME ?options?
This command returns the display name of the specified service. If SERVICE_NAME is the display name of a service, it is returned. If it is the internal name of a service, the corresponding display name is returned. Otherwise, an error is raised. The standard options described in Standard Options may be specified with this command.
get_service_internal_name SERVICE_NAME ?options?
This command returns the internal name of the specified service. If SERVICE_NAME is the internal name of a service, it is returned. If it is the display name of a service, the corresponding internal name is returned. Otherwise, an error is raised. The standard options described in Standard Options may be specified with this command.
get_service_state INTERNAL_SERVICE_NAME
Returns the last reported state of the service. See the description of the state field for the command get_service_status for possible values.
get_service_status INTERNAL_SERVICE_NAME ?options?
This command returns the latest status information sent by the given service to the service control manager. The standard options described in Standard Options may be specified with this command. The return value is a dictionary with the following keys:

checkpoint | Contains the last checkpoint value reported by the service during a lengthy operation.
controls_accepted | Contains a bitmask indicating the control commands accepted by the service. Refer to the Windows SDK documentation for ControlService for details.
exitcode | The last exit code of the service. If this value is 1066, a service specific error code is returned in the service_code field.
interactive | Indicates whether the service is allowed to interact with the desktop (1) or not (0).
pid | The PID of the process in which the service is running. A value of -1 indicates that the process id of the service cannot be determined or is stopped.
serviceflags | Integer value. If the low bit is set, the service runs in a system process that must alway be running.
servicetype | Indicates the type of the service, and is one of win32_own_process, win32_share_process, kernel_driver, file_system_driver, adapter, recognizer_driver or an integer denoting the type if not one of the above.
state | Contains the latest reported status of the service and may have one of the values stopped, start_pending, stop_pending, running, continue_pending, pause_pending, paused or an integer value indicating the status of the service if not one of the above.
service_code | In case the exitcode field contains 1066, this field contains a service specific code stored by the service.
wait_hint | Estimated time required to complete an start, stop, pause or continue operation as last reported by the service.

interrogate_service INTERNAL_SERVICE_NAME ?options?
This command asks the specified service to update the service control manager with its current status. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The standard options described in Standard Options may be specified with this command.
pause_service INTERNAL_SERVICE_NAME ?options?
This command pauses the specified service. INTERNAL_SERVICE_NAME is the internal name of the service, not the display name. The command returns 1 if the service is paused when the command completes and 0 otherwise. Note that a return value of 0 does not imply an error, just that the service had not completely changed to a paused state by the time the command returned. A Tcl error is generated if the service was not running.

The options described in Standard Options may be specified with this command. In addition, if the option "-wait MILLISECONDS" is specified the command will wait until the service is paused or until MILLISECONDS milliseconds have expired.
run_as_service SERVICES ?-interactive BOOLEAN? ?-controls CONTROLLIST?
This command sets up the mechanisms that allow a Tcl application to act as a Windows service. It must be only called when the application is started by the Windows SCM as a Windows service, else it will fail silently. The command does not return until the service is ready to exit. Rather, it invokes the service handlers that implement each service in response to notifications received from the system as described below.

SERVICES is a list of SERVICENAME HANDLER pairs that describe the services that will run in the process. Note a single process may host multiple services. SERVICENAME is the internal name of a service. HANDLER is a script that will be invoked for that service in response to various system notifications as described below.

The option -interactive indicates whether the services running in the application will require interaction with the desktop.

The option -controls configures what controls messages from the system, signals and notifications, are understood by the services. The SCM will restrict itself to sending only these although for robustness it is recommended that all services gracefully handle all signals as described below. Note that it is not possible to specify different values for this on a per-service basis. By default, CONTROLLIST includes control signals stop and shutdown. Note the notification start is implicit and must be handled by every service.

When the application is started by the SCM, it should perform its basic application-wide initialization and then call run_as_service. The command will then set up the communication mechanisms with the SCM and register the specified services. The control signals sent by the SCM to the service are passed on to the HANDLER script registered for the service by the application.

The messages sent to a service fall into two categories - control signals and notifications. Control signals generally require the service to take some action, often a state change such as stopping or pausing the service. Notifications are generally of an informational nature to apprise the service of some system event such as session changes or power events.

There are five controls signals sent by the SCM to control the state of a service. These correspond to the tokens start, stop, shutdown, pause and continue. For each of these, HANDLER is invoked with four additional arguments. The first is control signal token itself. The second is the name of the service for which the control was sent and should match (ignoring case) the corresponding the SERVICENAME values passed to run_as_service. The third argument is a sequence number (more on this later). The fourth argument is a numeric value that is the actual value of the control signal sent by the SCM.

start | Sent to start the service.
stop | Sent to stop the service.
pause | Sent to pause the service without terminating it. This is only received if pause_continue has been specified as an element in the -controls option.
continue | Sent to contiue a service that was previously paused. This is only received if pause_continue has been specified as an element in the -controls option.
shutdown | Sent to indicate the system is shutting down. Should be treated similar to stop.
interrogate | Sent to enquire about the service status. TWAPI handles this internally and never actually sends this to the application.

In response to a control signal, the handler must take whatever action necessary and then notify the SCM by calling update_service_status, passing it new the process state. For example, in response to a pause control, the application may take whatever actions required to temporarily pause the service operation and then respond by passing the paused state to update_service_status. Alternatively, if the service cannot be paused for whatever reason, it may respond by passing the state running. Refer to update_service_status for details on valid responses. It is very important to correctly notify the service control manager of the state change.

The application must respond to every control notification with a corresponding call to update_service_status. There is no hard time limit during which this call must be made but it is a good idea not to delay the response too long. update_service_status can be either invoked from the handler itself or scheduled at some later point after the necessary actions have been taken by the application. During this time, TWAPI may internally send responses to the SCM essentially asking it to keep waiting for an answer without timing out.

Because multiple controls may be received from the SCM before previous controls have been fully processed, and to allow for asynchronous responses from the application, a sequence number is passed as the third argument to the callback. When the application responds using update_service_status, this sequence number should be passed to the call. When responses are made out-of-order, those with older sequence numbers will be ignored.

In addition to the above control signals that may be sent by the SCM, it may also send notifications to the service to inform it of system events. These are passed on to the appropriate service callback handler in the same fashion as the control signals. Unlike for control signals, the application need not, and generally should not, respond with a call to update status. However, it should ensure the script returns an appropriate return value. Generally, the return value should be an integer error code that is passed back to the service control manager (0 being success). In some cases, the script may also return allow or deny.

In addition to the four arguments described for control signals, some notifications may have additional arguments. The various notifiations are shown in the able below.

all_stopped | The all_stopped notification is sent to the last running service in the application when all other services in the process have been stopped. The application should normally clean up and exit when this control is received. The remaining arguments passed to the handler are either empty strings or 0 and should not be used. This notification is internally generated by TWAPI and not sent by the system.
hardwareprofilechange | Notifies the application of events related to changes to the system hardware profile. An additional argument provides the specifics of the change and may be one of configchanged, configchangecanceled or querychangeconfig. In the case of querychangeconfig, the callback script may return allow or deny to allow or deny the request.
paramchange | Notifies the application that one of its configuration parameters has changed and it should re-read its service information from the Windows registry. This is only received if paramchange has been specified as an element in the -controls option to indicate to the service manager that the service can read and change its configuration while running.
netbindadd | Refer to the Windows SDK. This is only received if netbindchange has been specified as an element in the -controls option.
netbinddisable | Refer to the Windows SDK. This is only received if netbindchange has been specified as an element in the -controls option.
netbindenable | Refer to the Windows SDK. This is only received if netbindchange has been specified as an element in the -controls option.
netbindremove | Refer to the Windows SDK. This is only received if netbindchange has been specified as an element in the -controls option.
powerevent This notifies the application of a change in the power status of the system. This is only received if powerevent has been specified as an element in the -controls option. In addition to the standard arguments, an additional argument is appended detailing the nature of the change. This may be one of apmsuspend, apmstandby, apmresumecritical, apmresumesuspend, apmresumestandby, apmbatterylow, apmpowerstatuschange, apmoemevent, apmresumeautomatic, apmquerysuspend, apmquerysuspendfailed, apmquerystandby, or apmquerystandbyfailed.

In the case of apmquerysuspend and apmquerystandby, the callback script may return allow or deny to allow or deny the request.

Note that not all events are present in every version of Windows. See the Windows SDK for platform specific details.
sessionchange Notifies that a session change event has occurred. This is only received if sessionchange has been specified as an element in the -controls option. In addition to the standard arguments, two additional arguments are appended. The first of these indicates the nature of the session change and is one of console_connect, console_disconnect, remote_connect, remote_disconnect, session_login, session_logoff, session_lock, session_unlock or session_remote_control.

The second additional argument is the session identifier for which the event is being reported.
user_defined | The userdefined control is strictly application-dependent and not used by the SCM. User defined controls can be sent to a service using command line utilities such as the Windows sc program. The standard four arguments are passed on except that the fourth argument, the numeric value of the control, will vary within the range 128-255 and can be used by the application to distinguish between different signals.
Running as a service requires a threaded build of Tcl. An exception will be raised on non-threaded builds.

service_exists SERVICE_NAME ?options?
This command returns 1 or 0 depending on whether a service with the specified name exists or not. SERVICE_NAME may be either the internal name of the service or the display name. The options described in Standard Options may be specified with this command.
set_service_configuration INTERNAL_SERVICE_NAME ?options?
This command allows modification of configuration data for the service specified by INTERNAL_SERVICE_NAME. In addition to the options described in Standard Options, the following options may be specified to set configuration data. The values for any unspecified options will remain unchanged.

-displayname DISPLAYNAME | Specifies the user visible name for the service. This is the name that is shown in the net start command and the SCM control panel applet.
-command COMMAND | COMMAND contains the system command to be executed to start the service. See description of create_service for details.
-servicetype SERVICETYPE | Specifies the service type. See description of create_service for details.
-interactive BOOLEAN | This option specifies whether the service should be allowed to interact with the desktop. See description of this option in command create_service for details.
-starttype STARTTYPE | Specifies how the service is to be started. See description of this option in command create_service for valid values for STARTTYPE.
-errorcontrol ERRORCONTROLMODE | This option specifies how errors during service start are to be handled. See description of this option in command create_service for valid values for ERRORCONTROL.
-loadordergroup GROUPNAME | Specifies GROUPNAME to be the service load order group to which the service belongs. If the option is not specified, the service is assumed to not belong to any load order group.
-dependencies DEPENDENCYLIST | Specifies the services and service load order groups that are required by this service and that must start before this service. See description of this option in command create_service for details.
-account ACCOUNTNAME | Specifies ACCOUNTNAME to be the user account under which the service should run. See description of this option in command create_service for details.
-password PASSWORD | Specifies the password corresponding to the user account specified in the -account option. PASSWORD but should be in encrypted form as returned by by the read_credentials or conceal commands.This option is ignored if the -account option is not specified.

start_service INTERNAL_SERVICE_NAME ?options?
This command starts the specified service if it is not already running. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The command returns 1 if the service is up and running when the command completes and 0 otherwise. Note that a return value of 0 does not imply an error, just that the service had not completely started by the time the command returned.

The options described in Standard Options may be specified with this command. In addition, if the option "-wait MILLISECONDS" is specified the command will wait until the service is running or until MILLISECONDS milliseconds have expired.
stop_service INTERNAL_SERVICE_NAME ?options?
This command stops the specified service if it is currently running. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The command returns 1 if the service has stopped by the time the command completes and 0 otherwise. Note that a return value of 0 does not imply an error, just that the service had not completely stopped by the time the command returned.

The options described in Standard Options may be specified with this command. In addition, if the option "-wait MILLISECONDS" is specified the command will wait until the service is stopped or until MILLISECONDS milliseconds have expired.
update_service_status SERVICENAME SEQNO STATE ?options?
This command should be called by applications, running as a Windows service, to update their status information with the Windows service control manager (SCM). The command may be called asynchronously at any time, but is most often called in response to a control notification from the SCM requesting a state change. See run_as_service for more detail.

SERVICENAME is the name of the service whose status is being updated.

SEQ is the sequence number of the control notification to which this is the response. See the discussion in the run_as_service documentation. If the call is not in response to a control notification, SEQ should be set to 0.

STATE is the of the application and should be one of the values stopped, running or paused. Note that an application can stop at any time, but should not generally change state to running or paused on its own without a control notification from the SCM. Doing so will in all likelihood confuse the SCM manager sufficiently to make the service unmanageable.

If the service state being specified is stopped, the application may also indicate a standard Windows exit code and a service-specific exit code by specifying their values through the options -exitcode and -servicecode respectively.

COPYRIGHT

Copyright © 2003-2008 Ashok P. Nadkarni


Storage - Disk information

Storage

Commands related to files, disks and volumes

SYNOPSIS

package require twapi_storage

begin_filesystem_monitor PATH SCRIPT ?options?
cancel_filesystem_monitor MONITORID
find_logical_drives ?-type DRIVETYPELIST?
find_volumes
find_volume_mount_points VOLNAME
flush_channel CHANNEL
get_drive_info DRIVE ?options?
get_drive_type DRIVE
get_file_times FILE ?options?
get_mounted_volume_name MOUNTPOINT
get_volume_info DRIVE ?options?
get_volume_mount_point_for_path PATH
map_drive_local DRIVE PATH ?options?
mount_volume MOUNTPOINTPATH VOLNAME
set_drive_label DRIVE NAME
set_file_times FILE ?options?
unmap_drive_local DRIVE ?options?
unmount_volume MOUNTPOINTPATH
user_drive_space_available drive space

DESCRIPTION

This package provides procedures related to file, logical disk and volume information. For commands related to physical disks see the twapi_device module.

Volumes

The command find_volumes returns a list of volumes on the system. The command get_volume_info returns various information about a volume (logical drive) including size and space utilization, file system characteristics and device.

The command find_volume_mount_points returns the list of volume mount points on a particular volume. Commands mount_volume and unmount_volume can be used to set and remove volumes from volume mount points. The command get_mounted_volume_name will return the name of the volume mounted on a drive letter or volume mount point.

Logical drives

For all drive related commands, the drive parameter may be specified as a single drive letter, a drive letter followed by a :, or as the root path of the drive (eg. C:\)

The command find_logical_drives returns a list of drives in the system of a specified type. get_drive_type returns the type (fixed, remote, etc.) of the logical drive.

The command user_drive_space_available can be used to check if sufficient free space is available on a drive.

The command set_drive_label may be used to set the volume name (drive label).

The command map_drive_local and unmap_drive_local may be used to assign and unassign a drive letter to a local path.

File system

The commands begin_filesystem_monitor and cancel_filesystem_monitor can be used for monitoring changes to the file system.

The commands get_file_times and set_file_times and allow retrieval and setting of the times associated with a file.

The command flush_channel flushes operating system buffers associated with a Tcl channel to disk.

Commands

begin_filesystem_monitor PATH SCRIPT ?options?
Registers SCRIPT to be invoked when the specified types of changes occur in the directory of subtree matching PATH.

The command returns an id corresponding to the monitoring callback. When no longer interested in the specified changes, the returned identifier should be passed to cancel_filesystem_monitor to end the monitoring.

The following options specify the type of changes to be monitored:

-access BOOLEAN | If true, changes to the last access time are monitored.
-attr BOOLEAN | If true, attribute changes, are monitored.
-create BOOLEAN | If true, changes to the creation times are monitored.
-dirname BOOLEAN | If true, directory name changes, including creation and renaming, are monitored.
-filename BOOLEAN | If true, file name changes, including file creation, renaming and deletion, are monitored.
-patterns PATTERNLIST | If specified, notification callbacks are invoked only on those files and directories that match one of the patterns in PATTERNLIST. See below for more detail.
-secd BOOLEAN | If true, changes to security descriptors in the specified directories are monitored.
-size BOOLEAN | If true, size changes in the specified directories are monitored.
-subtree BOOLEAN | If true, all subdirectories under the specified directory PATH are monitored in addition to PATH itself. If false (default), only the directory indicated by PATH is monitored.
-write BOOLEAN | If true, changes to the last write time of files in the specified directories are monitored.
By default, all options are false if unspecified. However, if no options related to the type changes to be monitored are present (either true or false), the command will monitor all types of changes.

When a file system change is detected, the SCRIPT is invoked after being appended with two additional parameters the first being the id that was returned by the command and the second being a list of alternating elements consisting of the notification type and the file or directory name (except when the type is error). The type is one of the following values:

added | The file or directory was added.
removed | The file or directory was deleted.
modified | The file or directory was modified. This includes changes to attributes or timestamps.
renameold | The file or directory was renamed. The associated name is the old name.
renamenew | The file or directory was renamed. The associated name is the new name.
error | There was an error in the operation. In this case the corresponding paired element is an error code. On receiving an error notification, the monitoring should generally be canceled by calling cancel_filesystem_monitor.
Note that the file names being reported may be either in longname or shortname (8.3) format. Moreover, depending on the buffering and caching by the operating system, a single write may result in one or more notifications.

If the -patterns option is specified, then the value associated with the option is a pattern filter that is used to match against the name component being reported. SCRIPT will be invoked only if the pattern filter matches.

Each element of the pattern list is a string beginning with either + or - followed by a pattern that is used for matching using the same rules as for the Tcl string match -nocase command. Note that \ path separator need to be escaped with another \ just as in the string match case. Alternatively, you can use / as the path separator in the pattern.

The name component being reported is matched against each element of the pattern list. When a match occurs, further elements of the pattern list are not matched. If the matching element is prefixed with a +, then SCRIPT is invoked. If the matching element is prefixed with a -, then the pattern filter is deemed to have not matched and SCRIPT is not invoked for the notification. Even in this case, no further matching is attempted against the remaining patterns. Pattern elements that do not begin with +, or - are treated as having an implicit + prefix.

If a non-empty pattern filter is specified but no element matches, the pattern filter is treated as having not matched, and SCRIPT is not invoked. Thus a pattern filter that only has - type elements will never match anything. Note a pattern list where no element matches is different from the case where -patterns is not specified or PATTERNLIST is empty in which case the pattern filter is treated as matched.

Note that the pattern matching is done only against the name component being reported, not against the full path.

Some examples of pattern matching are below (assume callback is your SCRIPT procedure):

begin_filesystem_monitor c:/temp callback -patterns {*.exe}

will only monitor files in c:\temp with .exe extensions.

begin_filesystem_monitor c:/temp callback -patterns {-*.foo +*.fo*}

will monitor files in c:\temp with an extension beginning with .fo except if the extension is .foo.

begin_filesystem_monitor c:/temp callback -patterns {+*.fo* -*.foo}

will monitor files in c:\temp with an extension beginning with .fo including those with extension .foo. The second pattern -*.foo has no effect as the matching stops as soon as a match is found.

This command requires a threaded build of Tcl and will raise an exception on non-threaded builds.
cancel_filesystem_monitor MONITORID
Cancels monitoring of the file system corresponding to MONITORID which must be an identifier returned by begin_filesystem_monitor.
find_logical_drives ?-type DRIVETYPELIST?
Returns a list of the logical drives in the system. If option -type not specified, all drives in the system are returned. Otherwise, only drives whose type is in DRIVETYPELIST are returned. DRIVETYPELIST must be a subset of the values returned by the get_drive_type command.
find_volumes
Returns the list of volumes in the system. Each entry in the list includes a trailing slash.
find_volume_mount_points VOLNAME
Returns the list of volume mount points on the volume whose name is VOLNAME.
flush_channel CHANNEL
Flushes operating system buffers associated with a Tcl channel to disk.
get_drive_info DRIVE ?options?
Synonym for get_volume_info.
get_drive_type DRIVE
Returns the type of the drive - unknown, removable, fixed, remote, cdrom or ramdisk or invalid.
get_file_times FILE ?options?
Retrieves the creation, access and modification timestamps for a file. The latter two are available through the Tcl file command which however does not provide the creation time for a file. FILE may either be the path to the file, an open Tcl channel to the open file or a Win32 handle to an open file. In the latter two cases, the file must have been opened for read access.

The information returned is a flat list of option value pairs. options, which may contain one or more of the following values, controls the information returned.

-all | Returns all fields.
-atime | Returns the time of last access for the file.
-ctime | Returns the creation time for the file.
-mtime | Returns the time of last modification for the file.
All times are returned in the same format as get_system_time.

get_mounted_volume_name MOUNTPOINT
Returns the name of a mounted volume. The returned name has a trailing backslash appended. MOUNTPOINT must specify a root directory of a local drive or path to a volume mount point. Specifying remote file shares will generate an error.
get_volume_info DRIVE ?options?
Returns attributes and properties of the specified volume as a list of the form "option1 value1 ...". DRIVE may be either a DOS drive, file share or a volume. Note certain options are not valid except when DRIVE specifies a drive letter (see below).

The values returned depend on which of the following options are specified:

-all | Returns all fields except -extents, -type and -device which have to be explicitly specified since they are not valid for volumes.
-attr | Returns a list containing one or more of the values case_preserved_names, unicode_on_disk, persistent_acls, file_compression, volume_quotas, supports_sparse_files, supports_reparse_points, supports_remote_storage, volume_is_compressed, supports_object_ids, supports_encryption, named_streams, read_only_volume, sequential_write_once, supports_transactions, supports_hard_links, supports_extended_attributes, supports_open_by_file_id, or supports_usn_journal. These indicate the features supported by the drive's file system. Refer to the documentation for GetVolumeInformation function in the Windows SDK for details on these.
-device | Returns a list the first element of which is the device name mapping for the drive. Remaining elements containing prior undeleted mappings for the drive. Only valid if DRIVE is a drive letter. For UNC paths, an empty string will be returned.
-extents | Returns a list of disk extents describing the physical location of the volume. Each disk extent is a keyed list containing 3 fields: -disknumber identifying the physical disk, -startingoffset containing the byte offset in the physical disk that the extent starts at, and -extentlength containing the size of the extent. An empty list is returned for extents if they cannot be determined (for example, for remote drives).
-freespace | Returns the total size of the unused space on the drive in bytes.
-fstype | Returns the type of the file system on the volume (eg. NTFS).
-label | Returns the label of the drive.
-maxcomponentlen | Returns the maximum length allowed for a single component in a file path.
-serialnum | Returns the serial number of the drive in hexadecimal format.
-size | Returns the size of the drive in bytes.
-type | Returns the type of the drive. Only valid if DRIVE is a drive letter. This may have one of the values unknown, removable, fixed, remote, cdrom or ramdisk. In case the drive path is invalid, the value invalid is returned in this field.
-used | Returns the total size of the used space on the drive in bytes.
-useravail | Returns the total size of the unused space on the drive that is available for the caller. This may be less than the freespace field if quotas are in effect.

get_volume_mount_point_for_path PATH
Returns the volume mount point below which the file specified by PATH resides. Refer to documentation for GetVolumePathName in the Windows SDK for more details.
map_drive_local DRIVE PATH ?options?
Maps the fully qualified path PATH to the specified drive letter. The mapping established by this command is not persistent across reboots. It may also be removed using the unmap_drive_local command.

The following options may be specified with the command:

-raw Specifies that PATH is a raw path specification that includes the device name as opposed to a drive letter.

mount_volume MOUNTPOINTPATH VOLNAME
Mounts the volume specified by VOLNAME at the mount point specified by MOUNTPOINTPATH. The directory MOUNTPOINTPATH must be empty. VOLNAME must be of the form \\?\VOLUME{GUID}\. If any volume is already mounted at MOUNTPOINTPATH, it will be silently unmounted before the new mount is performed.
set_drive_label DRIVE NAME
Sets the volume name for the specified drive. NAME may be an empty string in which case the drive label is removed.
set_file_times FILE ?options?
Sets the creation, access or modification timestamps for a file. FILE may either be the path to the file, an open Tcl channel to the open file or a Win32 handle to an open file. In the latter two cases, the file must have been opened for write access.

The timestamps modified depend on the options specified:

-atime LARGETIMESTAMP | Sets the time of last access for the file.
-ctime LARGETIMESTAMP | Sets the creation time for the file.
-mtime LARGETIMESTAMP | Sets the time of last modification for the file.
-preserveatime | Indicates that the time of last access for an open file should be preserved and not updated when the file is closed. This option can only be specified if FILE is either an open Tcl channel or Win32 handle and not if it is a file path. Also, the option cannot be used together with -atime.
All time values must be specified in the same format as get_system_time. You can use secs_since_1970_to_large_system_time to convert the format used by Tcl's clock command to this format.

unmap_drive_local DRIVE ?options?
Unmaps the drive specified by DRIVE. This must reference a local drive. The following options may be specified with the command:

-path PATH | Specifies that the drive should be unmapped only if it refers to the location specified by PATH. This is useful to ensure drive letters are not unmapped when they have been redefined to point elsewhere.
-raw | Specifies that PATH argument specified with the -path option is a raw path specification that includes the device name as opposed to a drive letter.

unmount_volume MOUNTPOINTPATH
Unmounts the volume at the mount point specified by MOUNTPOINTPATH. If MOUNTPOINTPATH is a root directory of a drive, the corresponding DOS drive letter mapping is removed.
user_drive_space_available drive space
Returns 1 if the given drive has at least space bytes free, and 0 otherwise. Note that space is compared to the free bytes available to the caller as opposed to total free bytes on the drive. The former may be smaller if disk quotas are being enforced on the drive.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Network shares and Lan Manager - Network share and Lan Manager session management

Network shares and Lan Manager

Commands related to management of network shares and Lan Manager sessions

SYNOPSIS

package require twapi_share

close_lm_open_file FILEID ?-system SYSTEMNAME?
connect_share SERVERSHARE ?options?
delete_share SHARENAME ?-system SYSTEMNAME?
disconnect_share SHARE ?options?
end_lm_sessions ?options?
find_lm_connections ?options?
find_lm_open_files ?options?
find_lm_sessions ?options?
get_client_share_info SHAREPATH ?options?
get_client_shares ?options?
get_share_info SHARENAME ?options?
get_shares ?options?
get_lm_open_file_info FILEID ?options?
get_lm_session_info CLIENTSYSTEM USER ?options?
new_share SHARENAME RESOURCE ?options?
set_share_info SHARENAME ?options?

DESCRIPTION

This module provides commands related to management of Windows network shares and the Lan Manager sessions over which they are implemented.

Lan Manager sessions

A Lan Manager (LM) session is a logical connection between the client and server over which all communications related to shares takes place. LM sessions are created and terminated on the fly by the client as and when needed.

Lan Manager sessions on a server can be enumerated through the find_lm_sessions command. Information about individual sessions can be obtained through the get_lm_session_info command. Existing sessions can be deleted using end_lm_sessions.

The files and resource opened within a Lan Manager session can be enumerated through the find_lm_open_files command. Information about individual open files can be obtained through get_lm_open_file_info and closed using close_lm_open_file.

Information about the connections to a shared resource on a system can be obtained through find_lm_connections.

Network Shares - Server

These commands work with all types of Windows network shares exported from a server including files and disks, printers, devices and IPC.

The command new_share creates a new share of the specified type. The command delete_share removes an existing share.

The commands get_shares and get_share_info allow enumeration and retrieval of detailed information about a share. The command set_share_info allows attributes of an existing share to be modified.

Network Shares - Client

The following commands deal with client side of network share connections.

The commands connect_share and disconnect_share are used to establish and remove client side connections to network shares. The command get_client_shares lists all current connections to any network share. Details about a particular connected share can be obtained through the get_client_share_info command.

When a local device (for example, a printer port or a drive letter) is mapped to a network drive, information about the mapping may be obtained through the get_client_share_info command.

Share Types

The type of a network share is indicated by a token that indicates the basic type, such as file or print queue, followed by one or more tokens that indicate additional attributes such as whether it is a temporary share. The basic share type token is one of file, print, ipc or device corresponding to a file, print queue, interprocess communication, and a communication device respectively. Additional type information may contain the tokens temporary, which indicates a temporary share, and special, which indicates a administrative share.

Commands

close_lm_open_file FILEID ?-system SYSTEMNAME?
Closed the file or resource associated with FILEID. The file ids open within a Lan Manager session may be obtained through the find_lm_open_files command. Option -system may be specified to indicate the system on which the command is to be executed. By default, this is the local system.
connect_share SERVERSHARE ?options?
Establishes a new connection to a network share, optionally mapping it to a local device. SERVERSHARE is of the form \\SERVERNAME\SHARE and is the name of the share to connect to.

The command returns the path through which the share should be accessed. If the -localdevice option (see below) is specified, this is the local device the share is mapped to. Otherwise, it is the UNC share path.

The following options may be specified to control the connection characterisics:

-type | Specifies the type of network share. This must be one of any (default), file for file and disk shares or printer for print shares.
-localdevice DEVICENAME By default, the command establishes a connection to SERVERSHARE but does not map it to a local device. Specifying this option maps the network share connection to a local device, for example a drive letter or printer port. DEVICENAME may also be specified as * in which case the system will choose a drive letter to be mapped.

Note that if this option is specified, the -type option must also be specified with a value of disk or printer.
-provider PROVIDERNAME | This option allows specification of a network provider to be used for the connection. Generally, this option should not be specified allowing Windows to select the appropriate network provider based on SERVERSHARE.
-user USERNAME | Specifies the user account to use to connect to the network share. By default, this is the current user account.
-password PASSWORD | Specifies the password to be used for connecting to the network share. PASSWORD but should be in encrypted form as returned by by the read_credentials or conceal commands. This option is ignored if either -defaultpassword or -nopassword is specified.
-defaultpassword | Specifies that the password for the current user account is to be used for connecting. This option cannot be used with the -nopassword option.
-nopassword | Specifies that no password is to be used for connecting. This option cannot be used with the -defaultpassword option.
-interactive | Specifies that a user name and password dialog should be displayed to the user if the network share login fails. The connection is retried using the values entered by the user.
-prompt | Displays a dialog allowing the user to change the user name and password before the connection attempt is made. This option has no effect if -interactive is not specified.
-commandline | If this option is specified, the operating system will prompt the user for the password on the command line rather than showing the password dialog. This option has no effect if -interactive is not specified. This option is not supported on Windows 2000. An error will be generated if this option is specified on those platforms.
-window HWIN | Specifies that the window identified by HWIN is to be used as the owner window for any password dialogs that are displayed.
-updateprofile | If this option is specified, the user's profile is updated so that the network share connection will be reestablished every time the user logs in.

delete_share SHARENAME ?-system SYSTEMNAME?
Deletes a share. By default the share is assumed to be on the local system unless the -system option is specified.
disconnect_share SHARE ?options?
Disconnects the network share SHARE. The following options may be specified:

-force | Forces the network share connection to be closed even if there are open files or print jobs on the connection.
-updateprofile | If this option is specified, the user's profile is updated so that the network share connection will not be reestablished every time the user logs in.

end_lm_sessions ?options?
Terminates all Lan Manager sessions matching the specified options. options may include the following matching criteria:

-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-client SYSTEMNAME | Specifies the name of the client system whose sessions are to be terminated.
-user USERNAME | Specifies the name of the user whose sessions are to be terminated.
Note that at least one of the options -user or -client must be specified.

find_lm_connections ?options?
Returns information about the connections to a share on a server or established from a particular client system. The return value is a record array whose fields correspond to the options below.

-activeseconds | Returns the number of seconds the connection has been established.
-all | Returns all data fields for each connection.
-client CLIENTNAME | Specifies that only connections from client CLIENTNAME should be included in the returned list. This option and option -share are mutually exclusive.
-clientname | Returns the name of the client computer for the connection.
-id | Returns the connection id.
-opencount | Returns number of resources currently opened through the connection.
-share SHARENAME | Specifies that only connections to the share identified by SHARENAME should be included in the returned list. This option and option -client are mutually exclusive.
-sharename | Returns the name of the share to which the connection is attached.
-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-type | Returns the share type of the resource to which the connection is made (see Share Types).
-usercount | Returns number of users currently using the connection.
-user | Returns name of the user that made the connection.

find_lm_open_files ?options?
Returns a record array containing information about files and devices opened through a Lan Manager session. The fields of the record array depend on the specific options. Refer to get_lm_open_file_info for a list of these options.

In addition, the following options specify matching criteria that control which records are returned:

-basepath PATHPREFIX | Specifies that all returned files should have begin with PATHPREFIX. If PATHPREFIX is an empty string (default), all open files are included.
-matchuser USERNAME | Specifies the name of the user whose sessions are to be included. If USERNAME is an empty string (default), all users are included.
-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.

find_lm_sessions ?options?
Returns a record array of Lan Manager sessions matching the specified options. The fields of the record array depend on the options specified. Refer to get_lm_session_info for a list of these options.

In addition, the following options specify matching criteria that control which sessions are returned:

-matchclient cLIENTNAME | Specifies the name of the client system whose sessions are to be included. If CLIENTNAME is an empty string (default), all client systems are included.
-matchuser USERNAME | Specifies the name of the user whose sessions are to be included. If USERNAME is an empty string (default), all users are included.
-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.

get_client_share_info SHAREPATH ?options?
Returns information about the connected network share identified by SHAREPATH. SHAREPATH may be either a UNC format share or a locally mapped device.

The information returned depends on the specified options and is in the form of a dictionary.

-all | Returns all configuration data for the connected share.
-comment | Returns the comment describing the connected share, if any
-domain | Returns the domain name of the connected share.
-localdevice | Returns the local device to which the share is mapped and an empty string otherwise.
-opencount | Returns the number of open handles that are open to resources on the remote share.
-provider | Returns the name of the network service provider that owns the share.
-remoteshare | Returns the name of the remote share.
-status | Returns the status of the share. This may be one of connected, paused, lostsession, disconnected, networkerror, connecting, reconnecting or unknown.
-type | Returns the type of the network share. This may be one of file, printer, char, ipc or unknown.
-usecount | Returns the number of references to the remote share. Note the remote share may be connected multiple times with and without local device mappings.
-user | The name of the user who initiated the connection.

get_client_shares ?options?
Returns a list of network shares to which a system is currently connected.

-system SYSTEMNAME | Specifies the name of the system whose shares are to be enumerated. By default, this is the local system.
-level LEVEL | Specifies the level of detail to be returned (see below).
If the -level option is not specified, the returned list contains the paths of the remote server shares.

If -level is specified, the command returns a record array whose fields depend on LEVEL as follows:

0 | -localdevice, -remoteshare
1 | The fields for level 0 plus -type, -opencount, -status, -usecount.
2 | The fields for level 1 plus -domain, -user.
Refer to get_client_share_info for a description of these fields.

get_share_info SHARENAME ?options?
Retrieves information pertaining to the specified share. By default, the share is assumed to be on the local system. The -system may be used to specify the name of a remote system.

The information returned depends on the specified options and is in the form of a dictionary.

-all | Returns all configuration data for the share.
-name | Returns the name of the share as configured. This is generally SHARENAME but may differ in the character case.
-type | Returns the type of the share. See Share Types for details.
-path | Returns the path or name of the resource being shared.
-comment | Returns the comment associated with the share.
-max_conn | Returns the maximum number of connections that are permitted for the share. A value of -1 indicates that there is no limit.
-current_conn | Returns the current number of connections to the share.
-secd | Returns the security descriptor attached to the share.

get_shares ?options?
This command enumerates all the shares exported on a system. The following options control the shares that are enumerated.

-system SYSTEMNAME | Specifies the name of the system whose shares are to be enumerated. By default, this is the local system.
-level LEVEL | Specifies the level of detail to be returned (see below).
-type SHARETYPE | Specifies the type of the share to include in the enumeration. SHARETYPE must be one of base share types listed in Share Types. By default, all share types are enumerated.
-excludespecial | Specifying this option causes special shares (see Share Types) not to be included in the enumeration.
If the -level option is not specified, the command returns a list of share names. If -level is specified the command returns a record array whose fields depend on LEVEL as follows:

0 | -name
1 | Fields at level 0 plus -comment, -type
2 | Fields at level 1 plus -current_conn, -max_conn, -name, -passwd, -path, -permissions, -comment, -type.
502 | Fields at level 2 plus -reserved, and -secd.
See get_share_info for explanation of these fields.

get_lm_open_file_info FILEID ?options?
Returns a list of field values pairs containing data for a file or resource opened in a Lan Manager session. The file is identified by FILEID. find_lm_open_files returns a list of all such ids. The command will generate an error there is no file open with the specified id.

The actual data returned depends on the options specified. The following options may be specified:

-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-all | Returns all data fields.
-id | Returns the file id of the open resource.
-lockcount | Returns the number of locks on the open resource.
-path | Returns the path of the open resource.
-permissions | Returns a list of zero or more from among read, write and create corresponding to the access permissions for the opening application.
-user | Returns the name of the user that opened the resource.

get_lm_session_info CLIENTSYSTEM USER ?options?
Returns a list of field values pairs containing data for a Lan Manager session. The Lan Manager session is identified by CLIENTSYSTEM which identifies a client system and USER which identifies the user that authenticated the session. The actual data returned depends on the options specified. The command will generate an error if no matching connection is found.

The following options may be specified:

-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-all | Returns all data fields.
-activeseconds | Returns the number of seconds session has been active.
-attrs | Returns a list of tokens describing the session attributes. The tokens may include guest, indicating the session was established using a guest account, and noencryption, indicating the session was established without using password encryption.
-clientname | Returns the UNC name of the client system.
-clienttype | Returns a string identifying the type of client system.
-idleseconds | Returns the number of seconds the session has been idle.
-opencount | Returns the number of open files, devices and pipes opened in the session.
-transport | Returns the name of the underlying transport over which the session runs.
-user | Returns the name of the user account under which the session was established.

new_share SHARENAME RESOURCE ?options?
Creates a new share with name SHARENAME that exports the specified resource RESOURCE. Unless specified through the -type option, the share is assumed to be a file share and RESOURCE is assumed to be the directory path.

The following options control the various attributes of the share:

-system SYSTEMNAME | Specifies the name of the system on which the share is to be created. By default, this is the local system.
-comment COMMENT | Specifies a comment to be associated with the share. This is displayed to users connecting to the share. If unspecified or empty, this defaults to the share name.
-max_conn MAX_NUM_CONNECTION | Specifies the maximum number of connections to be allowed. If this is not specified, or is specified as -1, there is no limit to the number of connections allowed to the share.
-secd SECURITY_DESCRIPTOR | Specifies the security descriptor to be attached to the share. If unspecified, it defaults to allowing group Everyone (well-known SID S-1-1-0) read access similar to default permissions when creating a share from Windows Explorer.
-type SHARETYPE | Specifies the type of the share. See Share Types for details. This defaults to a file share.

set_share_info SHARENAME ?options?
Changes the configuration of the specified share. By default, the share is assumed to be on the local system. The -system may be used to specify the name of a remote system.

The configuration data that is to be modified is specified through the following options:

-comment STRING | Sets the comment associated with the share.
-max_conn INTEGER | Sets the maximum number of connections that are permitted for the share. A value of -1 indicates that there is not limit.
-secd SECD | Sets the security descriptor attached to the share.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Users and Groups - User and group account management commands

Users and Groups

Commands related to user and group accounts

SYNOPSIS

package require twapi_account

add_account_rights ACCOUNTNAME RIGHTS ?-system SYSTEMNAME?
add_user_to_global_group GROUPNAME USERNAME ?-system SYSTEMNAME?
add_member_to_local_group GROUPNAME ACCOUNTNAME ?-system SYSTEMNAME? ?-type name|sid?
add_members_to_local_group GROUP ACCOUNTS ?-system SYSTEMNAME? ?-type name|sid?
delete_global_group GROUPNAME ?-system SYSTEMNAME?
delete_local_group GROUPNAME ?-system SYSTEMNAME?
delete_user USERNAME ?-system SYSTEMNAME?
disable_user USERNAME ?-system SYSTEMNAME?
enable_user USERNAME ?-system SYSTEMNAME?
find_accounts_with_right RIGHT ?-system SYSTEMNAME? ?-name?
get_account_rights ACCOUNTNAME ?-system SYSTEMNAME?
get_global_group_info GROUPNAME ?options?
get_global_group_members GROUPNAME ?options?
get_global_groups ?options?
get_local_group_info GROUPNAME ?options?
get_local_group_members GROUPNAME ?options?
get_local_groups ?options?
get_lockout_policy ?SYSTEMNAME?
get_password_policy ?SYSTEMNAME?
get_user_account_info ACCOUNT ?-system SYSTEMNAME? ?options?
get_user_global_groups ACCOUNT ?-system SYSTEMNAME? ?-all? ?-denyonly?
get_user_local_groups ACCOUNT ?-system SYSTEMNAME? ?-recurse BOOLEAN?
get_users ?-system SYSTEMNAME?
new_global_group GROUPNAME ?-system SYSTEMNAME? ?-comment COMMENT?
new_local_group GROUPNAME ?-system SYSTEMNAME? ?-comment COMMENT?
new_user USERNAME ?options?
remove_member_from_local_group GROUPNAME ACCOUNTNAME ?-system SYSTEMNAME? ?-type name|sid?
remove_members_from_local_group GROUPNAME ACCOUNTS ?-system SYSTEMNAME? ?-type name|sid?
remove_account_rights ACCOUNTNAME RIGHTS ?-system SYSTEMNAME?
remove_user_from_global_group GROUPNAME USERNAME ?-system SYSTEMNAME?
set_lockout_policy DURATION OBSERVEWINDOW THRESHOLD ?SYSTEMNAME?
set_password_policy SETTING VALUE ?SYSTEMNAME?
set_user_account_info account ?-system SYSTEMNAME? ?options?
set_user_comment USERNAME STRING ?-system SYSTEMNAME?
set_user_country_code USERNAME INTEGER ?-system SYSTEMNAME?
set_user_expiration USERNAME DATETIME ?-system SYSTEMNAME?
set_user_full_name USERNAME STRING ?-system SYSTEMNAME?
set_user_home_dir USERNAME PATH ?-system SYSTEMNAME?
set_user_home_dir_drive USERNAME DRIVEPATH ?-system SYSTEMNAME?
set_user_name USERNAME NEWNAME ?-system SYSTEMNAME?
set_user_password USERNAME PASSWORD ?-system SYSTEMNAME?
set_user_profile USERNAME PATH ?-system SYSTEMNAME?
set_user_script_path USERNAME PATH ?-system SYSTEMNAME?
unlock_user USERNAME ?-system SYSTEMNAME?

DESCRIPTION

This module provides procedures related to management of user and group accounts on Windows operating systems.

Standard Options

Most commands allow the following options to be specified:

-system SYSTEMNAME Several commands, for example, looking up account names or adding users, may be carried out on a target system other than the local system. The -system option allows specification of the target system. This option defaults to the local system if unspecified.

User and Group Accounts

Note that the twapi_base provides some commonly used commands for mapping between account names and SIDs.

The commands new_user and delete_user allow addition and deletion of user accounts. The commands enable_user, disable_user and unlock_user may be used to change the state of a user account. The command get_user_account_info returns various attributes and properties of a user account. These may be modified through the set_user_account_info function or alternatively, modified individually through the following set of functions: set_user_name, set_user_password, set_user_home_dir, set_user_comment, set_user_script_path, set_user_full_name, set_user_country_code, set_user_profile, set_user_home_dir_drive, set_user_expiration.

Information about global and local groups may be retrieved through the get_global_group_info and get_local_group_info commands. New global groups may be created and deleted through the new_global_group and delete_global_group commands. The equivalent commands for local groups are new_local_group and delete_local_group. Users may be added and removed using the commands add_user_to_global_group, add_member_to_local_group, add_members_to_local_group, remove_user_from_global, remove_member_from_local_group and remove_member_from_local_group.

The rights and privileges associated with accounts can be managed through the get_account_rights, find_accounts_with_right, add_account_rights and remove_account_rights commands.

Enumerating Accounts

There are several commands for enumerating users and groups, including group membership.

get_users | Enumerates the locally defined user accounts.
get_global_groups | Enumerates the globally defined groups.
get_local_groups | Enumerates the locally defined groups.
get_local_group_members | Enumerates the members of a local group.
get_global_group_members | Enumerates the members of a global group.
get_user_global_groups | Enumerates the global groups in which a specific user account has membership.
get_user_local_groups | Enumerates the local groups in which a specific user account has direct or indirect membership.
With the exception of get_user_local_groups and get_user_global_groups, all these commands follow the same pattern of invocation and use a standard set of options. Without any optional arguments, the commands return a simple list of user or group names as appropriate. However, the commands also allow retrieval of information with additional detail or in incremental fashion.

To get more detail about about the accounts being returned without making separate calls for each individual account, the -level option may be specified. When this option is specified, the list of accounts returned is a record array with fields that contain the detail values for an item. The argument value passed to the -level option is an integer that indicates the level of detail desired. The valid values for the argument and the specific fields returned in the sublist are dependent on the command and are described in the documentation for the command. See the examples below for sample useage.

On systems (including domains) with a very large number of accounts, it may be better for performance and user responsiveness to retrieve the list in incremental fashion through -resume option. On the initial call to any of the commands, the RESUMEHANDLE value for the option must be specified as 0. The command will then return a list of the form { MOREDATA RESUMEHANDLE COUNT DATA }. In the returned list, MOREDATA is a boolean indicating if there are more accounts to be enumerated. If this value is 1, then the appropriate command can be called again, this time passing RESUMEHANDLE as the value for the -resume option. This process can be repeated as long the MOREDATA field in the returned result is 1. If MOREDATA is 0, there is no more data to be retrieved. The RESUMEHANDLE must be treated as opaque and must not be modified in any way before being passed back in the next call to the command. It is critical that the command be repeated with the correct value of RESUMEHANDLE and only if MOREDATA is 1. The system does not protect against bad values which can crash your application. The other elements returned when the -resume option is used are COUNT and DATA. The former is an estimate of the sum of items returned in this call and those remaining to be returned. Note this is only an estimate and should not be relied on except for rough purposes such as displaying a progress bar. The DATA element is the actual values that are the result of the call. The format of this depends on the use of the -level option. If the -level option was not specified, DATA is a simple list of values (such as user names). If -level was specified to the command, DATA is a record array as described above.

The following sample session demonstrates the use of the two options and the format of the returned data:

(tcl) 63 % get_local_group_members Administrators
Administrator ashok
(tcl) 64 % get_local_group_members Administrators -level 1
-name -comment} {{S-1-5-21-1957994488-1801674531-839522115-500 1 Administrator} {S-1-5-21-1957994488-1801674531-839522115-1003 1 ashok}}
(tcl) 65 % get_local_group_members Administrators -resume 0
0 0 2 {Administrator ashok}
(tcl) 66 % get_local_group_members Administrators -resume 0 -level 1
0 0 4 {{-name -comment} {{S-1-5-21-1957994488-1801674531-839522115-500 1 Administrator} {S-1-5-21-1957994488-1801674531-839522115-1003 1 ashok}}}

Global Account Settings

Certain account settings are applicable across all accounts in a security database, either the local SAM database, or Active Directory in case of domain controllers. The following commands allow for retrieval and modification of these settings.

get_lockout_policy | Returns the policy settings for account lockouts, such as lockout duration.
get_password_policy | Returns the policy settings for account passwords, such as minimum password length.
set_lockout_policy | Modifies the global policy settings for account lockouts.
set_password_policy | Modifies the global policy settings for account passwords.

Commands

add_account_rights ACCOUNTNAME RIGHTS ?-system SYSTEMNAME?
Adds the privileges and account rights listed in RIGHTS to the account specified by ACCOUNTNAME. The option -system may be used to specify a system as described in Standard Options.

RIGHTS is a list of privileges and account rights. Refer to Authorization constants in the Windows SDK for valid values. Note: you must use the string form of the privilege or right, for example, SeBatchLogonRight, not SE_BATCH_LOGON_NAME.
add_user_to_global_group GROUPNAME USERNAME ?-system SYSTEMNAME?
Adds the user account specified by USERNAME to the global group GROUPNAME. The option -system may be used to specify a system as described in Standard Options.
add_member_to_local_group GROUPNAME ACCOUNTNAME ?-system SYSTEMNAME? ?-type name|sid?
Adds the account specified by ACCOUNTNAME to the local group GROUPNAME. ACCOUNTNAME may be either a user name or a global group and may include a domain in the form domainname\username.

The option -system may be used to specify a system as described in Standard Options.

If the option -type has the value sid, ACCOUNTNAME is treated as an account SID. By default it treated as an account name.

The command does not raise an error if the specified account is already a member of the group.
add_members_to_local_group GROUP ACCOUNTS ?-system SYSTEMNAME? ?-type name|sid?
Adds the account specified in the list ACCOUNTS to the local group GROUPNAME. ACCOUNTS may contain user accounts and global groups and may include a domain in the form domainname\username. Alternatively, ACCOUNTS may be specified as a list of SID's if the option -type has the value sid.

The option -system may be used to specify a system as described in Standard Options.

Unlike the add_member_from_local_group command, this command raises an error without making any changes if any of the specified accounts does not exist or is not a member of the group. The command does not raise an error if the specified account is already a member of the group.
delete_global_group GROUPNAME ?-system SYSTEMNAME?
Deletes a global group GROUPNAME. Also, deletes any rights associated with the account in the LSA rights database. The option -system may be used to specify a system as described in Standard Options.
delete_local_group GROUPNAME ?-system SYSTEMNAME?
Deletes a local group GROUPNAME. Also, deletes any rights associated with the account in the LSA rights database. The option -system may be used to specify a system as described in Standard Options.
delete_user USERNAME ?-system SYSTEMNAME?
Delete the specified user account. Also, deletes any rights associated with the account in the LSA rights database. The option -system may be used to specify a system as described in Standard Options.
disable_user USERNAME ?-system SYSTEMNAME?
Disables a user account. The option -system may be used to specify a system as described in Standard Options.
enable_user USERNAME ?-system SYSTEMNAME?
Enables a user account. The option -system may be used to specify a system as described in Standard Options.
find_accounts_with_right RIGHT ?-system SYSTEMNAME? ?-name?
Returns a list of all accounts (user and group) that hold the right or privilege specified by RIGHT. The returned list contains the SID's of the account unless the -name option is specified in which case the account names are returned instead.

Refer to Authorization constants in the Windows SDK for valid values for RIGHT. Note: you must use the string form of the privilege or right, for example, SeBatchLogon, not SE_BATCH_LOGON_NAME.

The option -system may be used to specify a system as described in Standard Options.
get_account_rights ACCOUNTNAME ?-system SYSTEMNAME?
Returns the list of rights and privileges for the user or group specified by ACCOUNTNAME. This only includes those directly belonging to the account, and does not include the ones inherited from membership in groups.

The option -system may be used to specify a system as described in Standard Options.
get_global_group_info GROUPNAME ?options?
Retrieves information about the specified global group. The actual information returned depends on the specified options and is returned as a list of the form "option value...". The following options may be specified:

-all | Returns all data items.
-attributes | Returns the group attributes as a list. See get_token_groups_and_attrs for values.
-comment | Returns the comment associated with the group account.
-name | Returns the name of the group.
-sid | Returns the SID for the group.
-members | Returns the members of the group.

get_global_group_members GROUPNAME ?options?
If no options are specified, returns a list of user accounts that are members of the global group GROUPNAME.

The following options may be specified to modify the behaviour of the command.

-system SYSTEMNAME | See Standard Options.
-level LEVEL | See Enumerating Accounts for how this option changes the format of the returned data. The valid values of LEVEL and the corresponding fields returned are described below.
-resume RESUMEHANDLE | Returns account information in incremental mode. See Enumerating Accounts.
The valid values for LEVEL and the corresponding fields of the returned record array are shown in the following table:

0 | -name
1 | -name, -attributes

get_global_groups ?options?
If no options are specified, returns the list of global groups on the system.

The following options may be specified to modify the behaviour of the command.

-system SYSTEMNAME | See Standard Options.
-level LEVEL | See Enumerating Accounts for how this option changes the format of the returned data. The valid values of LEVEL and the corresponding fields returned are described below.
-resume RESUMEHANDLE | Returns account information in incremental mode. See Enumerating Accounts.
The valid values for LEVEL and the corresponding fields in the returned record array are shown in the following table:

0 | -name
1 | -name -comment,
2 | -name -comment, -group_id, -attributes,
3 | -name. -comment, -sid, -attributes, This level may not be supported on all versions of Windows.
Refer to the documentation of get_global_group_info for a description of these fields.

get_local_group_info GROUPNAME ?options?
Retrieves information about the specified local group. The actual information returned depends on the specified options and is returned as a list of the form "option value...". The following options may be specified:

-all | Returns all data items.
-comment | Returns the comment associated with the group account.
-name | Returns the name of the group.
-sid | Returns the SID for the group.
-members | Returns the members of the group.

get_local_group_members GROUPNAME ?options?
If no options are specified, returns a list of user accounts that are members of the local group GROUPNAME.

The following options may be specified to modify the behaviour of the command.

-system SYSTEMNAME | See Standard Options.
-level LEVEL | See Enumerating Accounts for how this option changes the format of the returned data. The valid values of LEVEL and the corresponding fields returned are described below.
-resume RESUMEHANDLE | Returns account information in incremental mode. See Enumerating Accounts.
The valid values for LEVEL and the corresponding fields or the returned record array are shown in the following table:

0 | -sid
1 | -sid, -sidusage, -name
2 | -sid, -sidusage, -domainandname
3 | -domainandname

get_local_groups ?options?
If no options are specified, returns the list of local groups on the system.

The following options may be specified to modify the behaviour of the command and the format of the returned data.

-system SYSTEMNAME | See Standard Options.
-level LEVEL | See Enumerating Accounts for how this option changes the format of the returned data. The valid values of LEVEL and the corresponding fields returned are described below.
-resume RESUMEHANDLE | Returns account information in incremental mode. See Enumerating Accounts.
The valid values for LEVEL and the corresponding fields are shown in the following table:

0 | -name
1 | -comment, -name
Refer to the documentation of get_local_group_info for a description of these fields.

get_lockout_policy ?SYSTEMNAME?
Returns the security database policy for account lockout settings. These may pertain to the SAM database or in the case of domain controllers, Active Directory. SYSTEMNAME is the NetBIOS or DNS name of the system to be queried and defaults to the local system.

The returned value is a dictionary with the following fields:

lockout_duration | Number of seconds that a locked account remains locked.
lockout_observation_window | Maximum time in seconds that can elapse between failed logon events before the account is locked out.
lockout_threshold | Number of logon failures before an account is locked out.

get_password_policy ?SYSTEMNAME?
Returns the security database policy settings for account passwords. These may pertain to the SAM database or in the case of domain controllers, Active Directory. SYSTEMNAME is the NetBIOS or DNS name of the system to be queried and defaults to the local system.

The returned value is a dictionary with the following fields:

force_logoff | Number of seconds before a user is forced to log off. A value of never means the user is never forced to log off.
max_passwd_age | Maximum allowable password age in seconds. A value of none indicates no limit.
min_passwd_age | Minimum allowable time in seconds before a password can be changed.
min_passwd_len | Minimum allowable password length.
password_hist_len | Length of the password history. New passwords must not match any passwords in the password history.

get_user_account_info ACCOUNT ?-system SYSTEMNAME? ?options?
Returns attributes and properties of a user account as a list of the form "option1 value1 ...". ACCOUNT specifies the user account for which the information is to be retrieved. The option -system may be used to specify the system from whose context the account lookup should be performed.

The data returned depends on which of the following options are specified:

-acct_expires | Returns the time when the account is set to expire. This value may be never or unknown or the number of seconds since Jan 1, 1970 00:00:00 UTC as accepted by the Tcl clock command.
-all | Returns all data items.
-bad_pw_count | Returns the number of login attempts for that account that failed because of a bad password. In an environment with backup domain controllers, each domain controller maintains this value independently and must be queried separately (using the -system option).
-code_page | Returns an integer corresponding to the code page for the user's preferred language.
-comment | Returns the comment associated with the user account.
-country_code | Returns an integer country/region value for the user's preferred language.
-full_name | Returns the full name of the user.
-global_groups | Returns the global groups of which the account is a member.
-home_dir | Returns the full path to the user's home directory.
-home_dir_drive | Returns the drive letter assigned to the user's home directory.
-last_logoff | Returns the time in GMT when the user last logged off. This value may also be never or unknown. In an environment with backup domain controllers, each domain controller maintains this value independently and must be queried separately (using the -system option).
-last_logon | Returns the time in GMT when the user last logged in. This value may also be never or unknown. In an environment with backup domain controllers, each domain controller maintains this value independently and must be queried separately (using the -system option).
-local_groups | Returns the local groups of which the account is a member. This includes only groups of which the account is directly a member and does not include indirect membership through a global group which is itself a member of a local group. See get_user_local_groups for a command that will recursively include groups.
-logon_hours | Returns a bit string of 1's and 0's corresponding to each hour in the week that the user is allowed to log on. Note the week starts based on GMT time, not local time.
-logon_server | Returns the name of the server to which logon requests are sent.
-max_storage | Returns the maximum amount of disk space the user is allowed to use.
-name | Returns the name of the account.
-num_logons | Returns the number of times the user has logged on. In an environment with backup domain controllers, each domain controller maintains this value independently and must be queried (using the -system option) separately. A value of -1 indicates the number is unknown.
-parms | Returns an application specific string.
-password_age | Returns the number of seconds since the password was last changed for the account.
-password_expired | Returns a value of 1 if the account password has expired, and 0 otherwise.
-primary_group_id | Returns the the RID (relative id component of a SID) of the primary global group for the account.
-profile | Returns the full path to the user's profile.
-script_path | Returns the full path to the user's logon script.
-sid | Returns the SID of the user.
-status | Returns one of the values disabled, enabled or locked.
-units_per_week | Returns an integer indicating the number of equal time units into which a week is divided (see -logon_hours).
-usr_comment | Returns the user comment for the account.
-user_id | Returns RID component of the user's SID.
-workstations | Returns a comma-separated list of upto eight workstations from which the user can log in.

get_user_global_groups ACCOUNT ?-system SYSTEMNAME? ?-all? ?-denyonly?
Returns a list of global groups in which the given user account is a member. Without any options, the command will only return those groups which are not marked as intended for deny only purposes. If the -denyonly option is specified, only such groups are returned. If -all is specified (which also overrides -denyonly if present), both types of groups are included in the returned list.

The option -system may be used to specify a system as described in Standard Options.
get_user_local_groups ACCOUNT ?-system SYSTEMNAME? ?-recurse BOOLEAN?
Returns the local groups in which the given user account is a member. If -recurse is not specified or is specified as false, only the local groups of which the account is directly a member are returned. If -recurse is specified as true, the returned list includes local groups of which the account is indirectly a member through its membership in a global group which is a member of the local group. This differs from the -local_groups option of the get_user_account_info command.

The option -system may be used to specify a system as described in Standard Options.
get_users ?-system SYSTEMNAME?
If no options are specified, returns the list of user accounts on the system. Note the returned list includes only accounts defined on the system, not all accounts that are known to the system.

The following options may be specified to modify the behaviour of the command.

-system SYSTEMNAME | See Standard Options.
-level LEVEL | See Enumerating Accounts for how this option changes the format of the returned data. The valid values of LEVEL and the corresponding fields returned are described below.
-resume RESUMEHANDLE | Returns account information in incremental mode. See Enumerating Accounts.
The valid values for LEVEL and the corresponding fields that are returned in the record array are shown in the table below. Note that there may be additional fields returned that are not listed. These should be considered internal and their values not relied on.

0 | -name
1 | Fields included in level 0 plus -comment, -status, -home_dir, -password, -password_age, -script_path.
2 | Fields included in level 1 plus -auth_flags, -full_name, -usr_comment, -parms, -workstations -last_logon, -last_logoff, -acct_expires, -max_storage, -units_per_week, -logon_hours, -bad_pw_count, -num_logons, -logon_server, -country_code, -code_page.
3 | Fields included in level 2 plus -user_id, -primary_group_id, -profile, -home_dir_drive, -password_expired.
Refer to get_user_account_info for the meaning of these fields.

new_global_group GROUPNAME ?-system SYSTEMNAME? ?-comment COMMENT?
Creates a global group GROUPNAME. The option -comment allows a comment to be associated with the group. The option -system may be used to specify a system as described in Standard Options.
new_local_group GROUPNAME ?-system SYSTEMNAME? ?-comment COMMENT?
Creates a local group GROUPNAME. The option -comment allows a comment to be associated with the group. The option -system may be used to specify a system as described in Standard Options.
new_user USERNAME ?options?
Creates a new user account. The following options may be specified to set the account properties:

-system SYSTEMNAME | Indicates the system on which to create the account.
-comment STRING | Sets the comment associated with the account.
-home_dir PATH | Sets the account's home directory path.
-script_path PATH | Sets the path to the logon script for the account.
-password PASSWORD | Sets the password for the account. PASSWORD but should be in encrypted form as returned by by the read_credentials or conceal commands.

remove_member_from_local_group GROUPNAME ACCOUNTNAME ?-system SYSTEMNAME? ?-type name|sid?
Removes the user account or global group specified by ACCOUNTNAME from the local group GROUPNAME. ACCOUNTNAME may be a domain account in the form domainname\username.

The option -system may be used to specify a system as described in Standard Options.

If the option -type has the value sid, ACCOUNTNAME is treated as an account SID. By default it treated as an account name.

The command does not raise an error if the specified account is not a member of the group.
remove_members_from_local_group GROUPNAME ACCOUNTS ?-system SYSTEMNAME? ?-type name|sid?
Removes multiple users or global groups from the local group GROUPNAME. ACCOUNTS is a list of may be a domain accounts in the form domainname\username, or as a list of SID's if the -type option has the value sid.

The option -system may be used to specify a system as described in Standard Options.

Unlike the remove_member_from_local_group command, this command raises an error without making any changes if any of the specified accounts does not exist or is not a member of the group.
remove_account_rights ACCOUNTNAME RIGHTS ?-system SYSTEMNAME?
Removes the privileges and account rights listed in RIGHTS from the account specified by ACCOUNTNAME. The option -system may be used to specify a system as described in Standard Options.

RIGHTS is a list of privileges and account rights. Refer to Authorization constants in the Windows SDK for valid values. Note: you must use the string form of the privilege, for example, SeBatchLogonRight, not SE_BATCH_LOGON_NAME.
remove_user_from_global_group GROUPNAME USERNAME ?-system SYSTEMNAME?
Removes the user account specified by USERNAME from the global group GROUPNAME. The option -system may be used to specify a system as described in Standard Options.
set_lockout_policy DURATION OBSERVEWINDOW THRESHOLD ?SYSTEMNAME?
Sets the security database policy account lockout settings. These may pertain to the SAM database or in the case of domain controllers, Active Directory. SYSTEMNAME is the NetBIOS or DNS name of the system to be queried and defaults to the local system. DURATION, OBSERVEWINDOW and THRESHOLD correspond to the lockout_duration, lockout_observation_window and lockout_threshold values returned by get_lockout_policy.
set_password_policy SETTING VALUE ?SYSTEMNAME?
Sets the security database policy settings for account passwords. These may pertain to the SAM database or in the case of domain controllers, Active Directory. SYSTEMNAME is the NetBIOS or DNS name of the system to be queried and defaults to the local system.

SETTING is the name of a setting as returned by get_password_policy and VALUE is the value to be assigned to it.
set_user_account_info account ?-system SYSTEMNAME? ?options?
Sets attributes and properties of a user account. account specifies the user account for which the information is to be retrieved. The option -system may be used to specify the system from whose context the account lookup should be performed. The following options may be specified to set various properties of the account:

-comment STRING | Sets the comment associated with the account.
-full_name STRING | Sets the full name of the user.
-country_code INTEGER | Sets the country code associated with the user account.
-home_dir PATH | Sets the account's home directory path.
-home_dir_drive | Sets the account's home directory drive.
-acct_expires DATETIME | Sets the time at which the account will expire. See set_user_expiration for valid formats for DATETIME.
-name STRING | Sets the name field containing the name of the account.
-script_path PATH | Sets the path to the logon script for the account.
-profile PATH | Sets the path to the account's profile.

set_user_comment USERNAME STRING ?-system SYSTEMNAME?
Sets the comment associated with the specified user account to STRING The option -system may be used to specify a system as described in Standard Options.
set_user_country_code USERNAME INTEGER ?-system SYSTEMNAME?
Sets the country code for the specified user account. The option -system may be used to specify a system as described in Standard Options.
set_user_expiration USERNAME DATETIME ?-system SYSTEMNAME?
Sets the time at which the specified user account expires. DATETIME may be specified as the number of seconds since Jan 1, 1970 00:00:00 UTC, the string never, or in any format accepted by the clock scan command. This last option is only for backward compatibility and is deprecated as it may lead to ambiguity. The option -system may be used to specify a system as described in Standard Options.
set_user_full_name USERNAME STRING ?-system SYSTEMNAME?
Sets the full name for the specified user to STRING. The option -system may be used to specify a system as described in Standard Options.
set_user_home_dir USERNAME PATH ?-system SYSTEMNAME?
Sets the home directory for the specified user account to PATH. The option -system may be used to specify a system as described in Standard Options.
set_user_home_dir_drive USERNAME DRIVEPATH ?-system SYSTEMNAME?
Sets the home directory drive for the specified user account. The option -system may be used to specify a system as described in Standard Options.
set_user_name USERNAME NEWNAME ?-system SYSTEMNAME?
Modifies the name of the specified user account to NEWNAME. The option -system may be used to specify a system as described in Standard Options.
set_user_password USERNAME PASSWORD ?-system SYSTEMNAME?
Sets the password of the specified user account to PASSWORD. PASSWORD but should be in encrypted form as returned by by the read_credentials or conceal commands. The option -system may be used to specify a system as described in Standard Options.
set_user_profile USERNAME PATH ?-system SYSTEMNAME?
Sets the location of the profile of the specified user account to PATH. The option -system may be used to specify a system as described in Standard Options.
set_user_script_path USERNAME PATH ?-system SYSTEMNAME?
Sets the path to the login script for the specified user account. The option -system may be used to specify a system as described in Standard Options.
unlock_user USERNAME ?-system SYSTEMNAME?
Unlocks a user account that has been locked out. The option -system may be used to specify a system as described in Standard Options.

COPYRIGHT

Copyright © 2004-2012, Ashok P. Nadkarni


Network configuration - Network related commands

Network configuration

Commands related to network configuration

SYNOPSIS

package require twapi_network

flush_arp_tables ?INTERFACENAME...?
get_arp_table ?-sort?
get_ipaddr_version IPADDR
get_network_adapter_info NETWORKINTERFACE ?options?
get_network_info ?options?
get_network_adapters
get_network_adapters_detail
get_outgoing_interface DESTADDR
get_route ?options?
get_routing_table ?-sort?
get_system_ipaddrs ?-ipversion IPVERSION? ?-types ADDRTYPELIST?
get_tcp_connections ?options?
get_udp_connections ?options?
hostname_to_address HOSTNAME ?-async SCRIPT? ?-flushcache?
hwaddr_to_ipaddr HWADDR ?VARNAME?
ipaddr_to_hwaddr IPADDR ?VARNAME?
port_to_service PORTNUMBER
resolve_address IPADDRESS ?-async SCRIPT?
resolve_hostname HOSTNAME ?-async SCRIPT? ?-ipversion IPVERSION?
service_to_port SERVICENAME
terminate_tcp_connections ?options?

DESCRIPTION

This module provides procedures to retrieve network information for IPv4 and IPv6.

Overview

This module provides commands to retrieve various network-related data for the local system including DNS and DHCP information, type and configuration of network interfaces, traffic statistics and various other information.

The module also provides some client side name resolution lookup functions including nonblocking name and address lookups.

Some commands only support IPv4 due to lack of underlying Windows support for the underlying Windows API on Windows XP and Windows 2003. This is noted where applicable.

Commands

flush_arp_tables ?INTERFACENAME...?
Note: This command only affects IPv4 tables

Flushes the ARP tables associated with the specified network interfaces. If no arguments are specified, all interfaces are flushed.
get_arp_table ?-sort?
Note: This command only retrieves IPv4 tables

Returns the entries in the system's ARP table. Each entry is a sublist consisting of four elements - the interface index, the hardware address, the IP address and the type. The type is one of dynamic, static, other or invalid. Note the hardware address may be empty, for example when the associated interface is the loopback adapter. If option -sort is specified, returns the entries sorted by interface index, then IP address.
get_ipaddr_version IPADDR
Returns the IP version (4 or 6) of the IP address specified as IPADDR. Returns 0 if IPADDR is not a valid IPv4 or IPv6 address.
get_network_adapter_info NETWORKINTERFACE ?options?
Returns various information about the configuration of a network interface. NETWORKINTERFACE must be the name of a network interface as returned by get_network_adapters.

The information returned depends on the options specified and is in the form of a dictionary whose keys depend on the options specified:

The following options may be specified:

-adaptername | Returns the name of the adapter associated with the interface.
-all | Returns all option values.
-anycastaddresses | Returns list of anycast addresses associated with the interface. Each element in the list is a dictionary, with the key -address containing the address. Other keys in the dictionary should be ignored.
-description | Returns a description of the interface.
-dhcpenabled | Returns 1 if DHCP is enabled on the interface, else 0.
-dnsservers | Returns a list of DNS servers on that interface. Each element in the list is a dictionary, with the key -address containing the address of the server. Other keys in the dictionary should be ignored.
-dnssuffix | Returns the DNS suffix for the adapter.
-friendlyname | Returns the friendly name of the adapter suitable for display to users.
-ipv4ifindex | Returns the IP V4 interface index.
-ipv6ifindex | Returns the IP V6 interface index.
-mtu | Returns the MTU size for the adapter.
-multicastaddresses | Returns list of multicast addresses associated with the interface. Each element in the list is a dictionary, with the key -address containing the address. Other keys in the dictionary should be ignored.
-operstatus | Returns the operational status of the interface as defined in RFC2863. Some common values are 1 (up), 2 (down), 3 (testing mode), 4 (unknown state), 5 (dormant), 6 (not present), 7 (lower layer is down).
-physicaladdress | Returns the physical address of the network interface.
-prefixes | Returns list of address prefixes associated with the interface. Each element in the list is a dictionary, with the key -address containing the address and the key -prefixlength containing the number of bits in the prefix. Other keys in the dictionary should be ignored.
-type | Returns the network interface type. This is an integer value as defined by IANA. Some common values are 6 (Ethernet), 9 (token ring), 23 (PPP), 24 (loopback), 71 (802.11 wireless), 131 (tunneling) and 144 (IEEE 1394 Firewire).
-unicastaddresses | Returns list of unicast addresses associated with the interface. Each element in the list is a dictionary, with the key -address containing the address. Other keys in the dictionary should be ignored.
-zoneindices | Returns list of IPv6 scope IDs.

get_network_info ?options?
Note: This command only returns information related to IPv4 configuration.

Returns various information about network configuration. The information returned depends on the options specified and is in the form of a flat list of the form "option1 value1 ...". The following options may be specified:

-all | Returns all values.
-arpproxyenabled | Returns 1 if ARP proxying is enabled and 0 otherwise.
-dhcpscopeid | Returns the DHCP scope id.
-dnsenabled | Returns 1 if DNS name resolution is enabled on the system and 0 otherwise.
-dnsservers | Returns a list of DNS server addresses used for name resolution.
-domain | Returns the system domain.
-hostname | Returns the host name of the system.
-routingenabled | Returns 1 if routing is enabled on the system and 0 otherwise.

get_network_adapters
Returns a list of network interface names.
get_network_adapters_detail
Returns a record array containing detailed information about all the network interfaces on the system. The record array contains the following fields:

-adaptername | The name of the adapter.
-anycastaddresses | List of anycast addresses associated with the interface. Each element in the list is a dictionary, with the key -address containing the address. Other keys in the dictionary should be ignored.
-description | Description of the interface.
-dnsservers | Returns a list of DNS servers on that interface. Each element in the list is a dictionary, with the key -address containing the address of the server. Other keys in the dictionary should be ignored.
-dnssuffix | The DNS suffix for the adapter.
-flags | Undocumented.
-friendlyname | The friendly name of the adapter.
-ipv4ifindex | The IP V4 interface index.
-ipv6ifindex | The IP V6 interface index.
-mtu | The MTU size for the adapter.
-multicastaddresses | Multicast addresses associated with the interface. Each element in the list is a dictionary, with the key -address containing the address. Other keys in the dictionary should be ignored.
-operstatus | Operational status of the interface as defined in RFC2863. Some common values are 1 (up), 2 (down), 3 (testing mode), 4 (unknown state), 5 (dormant), 6 (not present), 7 (lower layer is down).
-physicaladdress | Physical address of the network interface.
-prefixes | List of address prefixes associated with the interface. Each element in the list is a dictionary, with the key -address containing the address and the key -prefixlength containing the number of bits in the prefix. Other keys in the dictionary should be ignored.
-type | Network interface type. This is an integer value as defined by IANA. Some common values are 6 (Ethernet), 9 (token ring), 23 (PPP), 24 (loopback), 71 (802.11 wireless), 131 (tunneling) and 144 (IEEE 1394 Firewire).
-unicastaddresses | List of unicast addresses associated with the interface. Each element in the list is a dictionary, with the key -address containing the address. Other keys in the dictionary should be ignored.
-zoneindices | List of IPv6 scope IDs.

get_outgoing_interface DESTADDR
Note: This command is only supported for IPv4.

Returns the index of the network interface that will be used to send a packet to the IP address specified by DESTADDR
get_route ?options?
Note: This command is only supported for IPv4.

Returns the best route to a specified destination. The following options may be specified:

-dest DESTADDR | Specifies the destination address for which the route is to be returned. If unspecified, defaults to 0.0.0.0 which corresponds to the default route.
-source SRCADDR | Specifies the source address to be used. This can affect the route selected. Defaults to 0.0.0.0 which indicates the source address should not affect which route is selected.
The returned information is a keyed list with the following fields:

-addr | The destination address that together with the -mask field specifies the address range to which the route applies.
-age | The age of the route in seconds. This is valid only if the Routing and Remote Access service is running and the protocol is netmgmt.
-ifindex | The interface index for this route.
-mask | The network mask that together with -dest specifies the address range to which the route applies.
-metric1 | A routing protocol specific metric value.
-metric2 | A routing protocol specific metric value.
-metric3 | A routing protocol specific metric value.
-metric4 | A routing protocol specific metric value.
-metric5 | A routing protocol specific metric value.
-nexthop | The IP address of next hop in the route to the destination.
-nexthopas | The autonomous system number of the next hop.
-policy | Multi-path route selector condition, typically in IP TOS format as defined in RFC 1354.
-protocol | Protocol that generated the route.
-type | The type of the route. This is one of local, remote, other or invalid.

get_routing_table ?-sort?
Note: This command is only returns routing information for IPv4.

Returns the network routing table as a list of routes. Each element of the route is in the format described in the get_route command description.
get_system_ipaddrs ?-ipversion IPVERSION? ?-types ADDRTYPELIST?
Returns a list of IP addresses for the system.

If -ipversion is not specified, or IPVERSION is 0, any or all, both IPv4 and IPv6 addresses are returned. If IPVERSION is 4 or inet, only IPv4 addresses are returned and if it is 6 or inet6, only IPv6 addresses are returned.

By default, only unicast addresses are returned. If the -types option is specified, ADDRTYPELIST should be a list of one or more of the following: all, unicast, multicast or anycast. In that case, only addresses matching one of those types (or all types in the case of all) are returne.
get_tcp_connections ?options?
Retrieves information about currently active TCP connections similar to the Windows netstat command. The return value is a record array whose fields are controlled through the following options:

-all | Returns all fields for a connection. This option is assumed if no other field option is specified.
-bindtime | Returns the time at which the last bind operation was done on the socket, or 0 if no bind has been done. This may not be available in which case, an empty string is returned for the value. Deprecated
-localaddr | Returns the local address being used for the connection.
-localport | Returns the local port number being used for the connection.
-modulename | Returns the name of the process module that owns the socket. This may not be available in which case, an empty string is returned for the value. This value is always the empty string for IPv6 to work around a Windows bug. Deprecated
-modulepath | Returns the path to the process module that owns the socket. This may not be available in which case, an empty string is returned for the value. This value is always the empty string for IPv6 to work around a Windows bug. Deprecated
-pid | Returns the PID of the process communicating on the port. On some platforms, this may not be available in which case, an empty string is returned for the value.
-remoteaddr | Returns the address of the remote end of the connection.
-remoteport | Returns the port number of the remote end of the connection.
-state | Returns the connection state. This is one of closed, listen, syn_sent, syn_rcvd, estab, fin_wait1, fin_wait2, close_wait, closing, last_ack, time_wait or delete_tcb.
In addition, the connections for which information is returned may be filtered through the following options. Only those connections that match the specified criteria are returned.

-ipversion IPVERSION | If IPVERSION is 0 (default), any or all, both IPv4 and IPv6 connections are returned. If IPVERSION is 4 or inet, only IPv4 connections are returned and if it is 6 or inet6, only IPv6 connections are returned.
-matchlocaladdr HOSTLIST | Only returns those connections whose local address is one of those specified in HOSTLIST. Each element of HOSTLIST may be either an IP address or a host name.
-matchlocalport PORTNUMBER | Only returns those connections whose local port is the specified number.
-matchpid PID | Only returns those connections owned by the process with the specified PID. On platforms where the PID is not available, specifying this option will generate an error.
-matchremoteaddr HOSTLIST | Only returns those connections whose remote address is one of those specified in HOSTLIST. Each element of HOSTLIST may be either an IP address or a host name.
-matchremoteport PORTNUMBER | Only returns those connections whose remote port is PORTNUMBER.
matchstate STATELIST | Only returns those connections whose state is one those specified in STATELIST which should be a list of connection state values (see above).

get_udp_connections ?options?
Retrieves information about currently active UDP sockets similar to the Windows netstat command. The return value is a record array whose fields are controlled through the following options:

-all | Returns all fields for a connection. This option is assumed if no other field option is specified.
-bindtime | Returns the time at which the last bind operation was done on the socket, or 0 if no bind has been done. This may not be available in which case, an empty string is returned for the value. Deprecated
-localaddr | Returns the local address being used for the connection.
-localport | Returns the local port number being used for the connection.
-modulename | Returns the name of the process module that owns the socket. This may not be available in which case, an empty string is returned for the value. This value is always the empty string for IPv6 to work around a Windows bug. Deprecated
-modulepath | Returns the path to the process module that owns the socket. This may not be available in which case, an empty string is returned for the value. This value is always the empty string for IPv6 to work around a Windows bug. Deprecated
-pid | Returns the PID of the process communicating on the port. On some platforms, this may not be available in which case, an empty string is returned for the value.
In addition, the connections for which information is returned may be filtered through the following options. Only those connections that match the specified criteria are returned.

-ipversion IPVERSION | If IPVERSION is 0 (default), any or all, both IPv4 and IPv6 connections are returned. If IPVERSION is 4 or inet, only IPv4 connections are returned and if it is 6 or inet6, only IPv6 connections are returned.
-matchlocaladdr HOSTLIST | Only returns those connections whose local address is one of those specified in HOSTLIST. Each element of HOSTLIST may be either an IP address or a host name.
-matchlocalport PORTNUMBER | Only returns those connections whose local port is the specified number.
-matchpid PID | Only returns those connections owned by the process with the specified PID. On platforms where the PID is not available, specifying this option will generate an error.

hostname_to_address HOSTNAME ?-async SCRIPT? ?-flushcache?
This command is deprecated in favor of resolve_hostname. It only returns IPv4 addresses.
hwaddr_to_ipaddr HWADDR ?VARNAME?
Note: This command is only supported for IPv4.

Returns the IP address corresponding to the given hardware address. If VARNAME is specified, the command stores the result in a variable of that name in the caller's context if a mapping can be found and returns 1. Otherwise the command returns 0 without affecting the variable. If VARNAME is not specified, the command returns the IP address if a mapping is found and generates a Tcl exception otherwise.
ipaddr_to_hwaddr IPADDR ?VARNAME?
Note: This command is only supported for IPv4.

Returns the hardware address corresponding to the given IP address. If VARNAME is specified, the command stores the result in a variable of that name in the caller's context if a mapping can be found and returns 1. Otherwise the command returns 0 without affecting the variable. If VARNAME is not specified, the command returns the hardware address if a mapping is found and generates a Tcl exception otherwise.
port_to_service PORTNUMBER
Returns the service name (e.g. http) corresponding to the specified port number. If no corresponding service name exists, an empty string is returned.
resolve_address IPADDRESS ?-async SCRIPT?
Attempts to map the specified Internet address IPADDRESS to its fully qualified DNS name (FQDN). IPADDRESS may be an IPv4 or IPv6 address.

If the -async option is not specified, the command returns the FQDN if available and the empty string otherwise. Note that this is a blocking call and the Tcl event loop will not be run until the command returns.

If the -async option is specified, the command returns right away. The address resolution is done in the background and when completed, SCRIPT is called at the global scope. Three additional arguments are appended to the script before it is executed - IPADDRESS, status success or fail and either the FQDN (when the status is success) or the Winsock error code (when the status is fail). The Winsock error code may be translated to an error string using the map_windows_error command. If no names are found, the status is success but the third argument will be an empty string.

Note the -async option requires a threaded build of Tcl and will raise an exception on non-threaded builds.

Note the address to hostname mapping is no longer cached internally by TWAPI as in older releases. Applications can do the caching themselves if desired.
resolve_hostname HOSTNAME ?-async SCRIPT? ?-ipversion IPVERSION?
Attempts to map the specified host name to its IP addresses. Note there may be more than one address associated with a host name.

If -ipversion is not specified, or IPVERSION is 0, any or all, both IPv4 and IPv6 addresses are returned. If IPVERSION is 4 or inet, only IPv4 addresses are returned and if it is 6 or inet6, only IPv6 addresses are returned.

If the -async option is not specified, the command returns the list of IP addresses corresponding to the host if available and an empty list otherwise. Note that this is a blocking call and the Tcl event loop will not be run until the command returns.

If the -async option is specified, the command returns right away. The name resolution is done in the background and when completed, SCRIPT is called at the global scope. Three additional arguments are appended to the script before it is executed - HOSTNAME, status success or fail and either the list of IP addresses (when the status is success) or the Winsock error code (when the status is fail). The Winsock error code may be translated to an error string using the map_windows_error command. Note that on some platforms, if no addresses are found, callback may be invoked with a status of success and an empty list for the third argument, or it may be invoked with a status of fail and an appropriate error code.

Note the -async option requires a threaded build of Tcl and will raise an exception on non-threaded builds.
service_to_port SERVICENAME
Returns the port number corresponding to the specified service name (e.g. http). If the service name is not defined, an empty string is returned. If SERVICENAME is a port number, it is returned.
terminate_tcp_connections ?options?
Note: This command is only supported for IPv4 connections

Terminates all connections that match all the options specified. Any options that are not specified are assumed to match. The valid matching options are:

-matchlocaladdr IPADDR | Only matches those connections whose local address is bound to IPADDR.
-matchlocalport PORTNUMBER | Only matches those connections whose local port is the specified number.
-matchpid PID | Only matches those connections owned by the process with the specified PID. On platforms where the PID is not available, specifying this option will generate an error.
-matchremoteaddr IPADDR | Only matches those connections whose remote address is bound to IPADDR.
-matchremoteport PORTNUMBER | Only matches those connections whose remote port is PORTNUMBER.
matchstate STATELIST | Only matches those connections whose state is one those specified in STATELIST which should be a list of connection state values. See get_tcp_connections for a list of valid values.
The system attempts to terminate the specified connections but no error is raised if the connection cannot be terminated. Caller should retrieve the list of connections to check if the termination was successful.

COPYRIGHT

Copyright © 2004-2014, Ashok P. Nadkarni


Named pipes - Named pipe channels

Named pipes

Commands related to named pipes

SYNOPSIS

package require twapi_namedpipe

impersonate_namedpipe_client CHANNEL
namedpipe_client PIPENAME ?-access ACCESS?
namedpipe_server PIPENAME ?options?

DESCRIPTION

This module provides a Tcl channel based interface to Windows named pipes.

Overview

This module provides commands to perform I/O over Windows named pipes using standard Tcl commands like puts, gets, read and the Tcl 8.5 chan command. Named pipe channels support blocking and non-blocking operations in the same manner as the standard Tcl channel types. The Tcl commands fileevent and fconfigure, or its newer version chan configure, can be used with named pipe channels.

Windows named pipes support two data transmission modes - byte stream and message. TWAPI supports only the byte stream mode of operation as message mode is not supported by the Tcl channel based script commands. In byte stream mode, data is sent and received as a stream of bytes with no boundaries between consecutive writes or reads. This is similar to the TCP socket based operation of the Tcl socket command.

Named pipes are an alternative to sockets for communicating between processes on either the same or different systems. Named pipes are very efficient when both processes are on the same system but lag TCP socket based protocols when communicating between systems, particularly across a slow link. Named pipes are also not as scalable as sockets when servicing a very large number of clients. The primary advantage of named pipes over sockets is that they provide a very easy way of authenticating clients using the Windows security authentication infrastructure. An example might be a Windows service running in the LocalSystem account that needs to communicate with an application running on the user desktop. For local system communication, named pipes also have an advantage over Windows sockets in certain limited configurations in that they do not require a configured network adapter to be present (on some Windows versions, event the loopback interface, 127.0.0.1, will not work without a enabled network adapter).

Named Pipe Servers

A named pipe server creates a named pipe channel through the namedpipe_server command. This creates a single instance of the specified named pipe. To allow multiple clients to connect, the server must open multiple instances of the pipe using this command. Note the difference in behaviour compared to sockets. In the case of a socket-based server, a single listening socket is created and as clients connect, a new socket is created automatically for each new connection. This is not the case with named pipes where the incoming connection uses the existing named pipe instance. The server application must create a new instance to accept the next connection. Because incoming connect requests will be denied until the new instance is created, the application may open multiple instance of the named pipe to reduce the likelihood of missed connections.

Named Pipe Clients

A client application can connect to a named pipe using the namedpipe_client command. When the command returns the named pipe is connected and the channel can be used to send and receive data.

Named Pipe Access Control

Client access to a named pipes can be controlled through standard Windows security mechanisms. When a server creates a named pipe instance, it can specify a security descriptor to be attached to the pipe. When a client attempts a connect, its credentials are checked against the descriptor and access is granted accordingly.

Servers can also retrieve and impersonate the client's credentials through impersonate_namedpipe_client. Conversely, the client can specify options to namedpipe_client to control the degree to which the server can impersonate its security context.

Commands

impersonate_namedpipe_client CHANNEL
Changes the security context of the calling thread to that of the client of a named pipe. CHANNEL is a Tcl channel identifier for the server end of a named pipe. This call will fail unless some data is first read from the channel.

The caller must be careful that exceptions raised by this command are handled correctly. It should not continue with normal processing as though the security context was changed to that of the named pipe client.
namedpipe_client PIPENAME ?-access ACCESS?
Connects to the named pipe specified by PIPENAME and returns a Tcl channel identifier that can be used with the Tcl channel commands.

The command raises a Tcl exception on error. One possible error is caused by all instances of the server pipe being busy. In this case, the Tcl errorCode global is set to the value TWAPI_WIN32 231 LANGUAGE_DEPENDENT_ERROR_MESSAGE. The application may check for this and retry after some interval.

Unlike sockets, named pipes may be opened in read-only or write-only mode. This is configured through the -access option. ACCESS is a list consisting one or both of read and write depending on the access desired. By default, the pipe is opened for both read and write access.

For consistency with the Tcl socket command, the channel is configured with the default system encoding with line ending translation enabled. Use the fconfigure command to change this. Note the encoding and line ending options must match those the server side else data might appear to be corrupted.

-access ACCESS | Unlike sockets, named pipes may be opened in read-only or write-only mode. This is configured through the -access option. ACCESS is a list consisting one or both of read and write depending on the access desired. By default, the pipe is opened for both read and write access. Subsequent calls to create new instances of the pipe must also specify the same access mode else the call will fail.
-impersonatecontexttracking BOOLEAN | If specified as TRUE, the client security context is dynamically tracked by the server. Default is FALSE. This option is ignored unless -impersonationlevel is also specified.
-impersonateeffectiveonly BOOLEAN | If specified as FALSE (default), all aspects of the client security context are visible to the server. If TRUE, only the enabled aspects (groups and privileges) are visible to the server. This option is ignored unless -impersonationlevel is also specified.
-impersonationlevel IMPERSONATIONLEVEL | Sets the impersonation level at which the server is allowed to impersonate the client. Must be one of anonymous, identification, impersonation or delegation. See Impersonation for details.

namedpipe_server PIPENAME ?options?
Creates an instance of the named pipe specified by PIPENAME and returns a Tcl channel identifier that can be used with the Tcl channel commands. The command returns immediately. However, no input or output can be done on the pipe until a client establishes a connection on the pipe instance. To determine when the completion is completed, the application can register callbacks on the channel using the Tcl fileevent command. Alternatively, the application can poll the channel by attempting to read or write from it. This is not however recommended.

For consistency with the Tcl socket command, the channel is configured with the default system encoding with line ending translation enabled. Use the fconfigure command to change this. Note the encoding and line ending options must match those the server side else data might appear to be corrupted.

The following options may be specified with the command:

-access ACCESS | Unlike sockets, named pipes may be opened in read-only or write-only mode. This is configured through the -access option. ACCESS is a list consisting one or both of read and write depending on the access desired. By default, the pipe is opened for both read and write access. Subsequent calls to create new instances of the pipe must also specify the same access mode else the call will fail.
-denyremote | If specified, connections from remote clients are not accepted. This option requires Windows Vista or newer Windows versions. The command will raise an error if this option is specified on older versions of Windows.
-maxinstances MAXINSTANCES | Specifies the maximum number of instances of the named pipe that can exist. This only has effect for the call that creates the first instance of the pipe in the system. Subsequent calls must also specify the same value for MAXINSTANCES else the call will fail. and only checks that the pipe creation call will not cause the number of pipe instances to exceed the MAXINSTANCES value specified in the first call.
-secd BOOLEAN | Allows specifying a security descriptor that restricts access to the named pipe to specific Windows accounts. If unspecified, the security descriptor defaults to on that allows full access to the LocalSystem account, the Administrators group and to the creator owner, and read access to the Everyone group and anonymous account.

COPYRIGHT

Copyright © 2010, Ashok P. Nadkarni


Security and access control - Security commands

Security and access control

Commands related to authentication and access control

SYNOPSIS

package require twapi_security

append_acl_aces ACL ACELIST
check_enabled_privileges PRIVILEGES ?-any?
close_token TOKEN
credentials ?TARGETPATTERN?
disable_all_token_privileges TOKEN
disable_privileges PRIVLIST
disable_token_privileges TOKEN PRIVLIST
enable_privileges PRIVLIST
enable_token_privileges TOKEN PRIVLIST
eval_with_privileges SCRIPT PRIVLIST
find_logon_sessions ?options?
get_ace_inheritance ACE
get_ace_rights ACE ?-resourcetype RESOURCETYPE? ?-raw?
get_ace_sid ACE
get_ace_text ACE ?-resourcetype RESOURCETYPE?
get_ace_type ACE
get_acl_aces ACL
get_acl_rev ACL
get_current_user ?FORMATOPTION?
get_logon_session_info SESSIONLUID ?options?
get_privilege_description PRIVILEGE
get_resource_integrity RESTYPE NAME ?options?
get_resource_security_descriptor RESTYPE NAME ?options?
get_security_descriptor_control SECD
get_security_descriptor_dacl SECD
get_security_descriptor_group SECD
get_security_descriptor_integrity SECD ?-label|-raw?
get_security_descriptor_owner SECD
get_security_descriptor_sacl SECD
get_security_descriptor_text SECD ?-resourcetype RESOURCETYPE?
get_token_elevation TOKEN
get_token_groups TOKEN ?-name?
get_token_groups_and_attrs TOKEN
get_token_impersonation_level TOKEN
get_token_info TOKEN ?options?
get_token_integrity TOKEN ?-raw | -label?
get_token_integrity_policy TOKEN
get_token_linked_token TOKEN
get_token_owner TOKEN ?-name?
get_token_primary_group TOKEN ?-name?
get_token_privileges TOKEN ?-all?
get_token_privileges_and_attrs TOKEN
get_token_restricted_groups_and_attrs TOKEN
get_token_source TOKEN
get_token_statistics TOKEN
get_token_type TOKEN
get_token_user TOKEN ?-name?
get_token_virtualization TOKEN
impersonate_self IMPERSONATIONLEVEL
impersonate_token TOKEN
impersonate_user USERNAME PASSWORD ?options?
is_valid_luid_syntax LUID
map_luid_to_privilege LUID ?-system SYSTEMNAME? ?-mapunknown?
map_privilege_to_luid PRIVILEGE ?-system SYSTEMNAME? ?-mapunknown?
new_ace ACETYPE ACCOUNT ACCESSRIGHTS ?options?
new_acl ?ACELIST?
new_luid
new_restricted_dacl ACCOUNTS RIGHTS
new_security_descriptor ?options?
open_process_token ?-pid PID | -hprocess HPROCESS? ?-access DESIREDACCESS?
open_thread_token ?-tid TID | -hthread HTHREAD? ?-access DESIREDACCESS? ?-self BOOLEAN?
open_user_token USERNAME PASSWORD ?options?
prepend_acl_aces ACL ACELIST
reset_thread_token
revert_to_self
sddl_to_security_descriptor SECD
security_descriptor_to_sddl SECD
set_ace_inheritance ACE ?options?
set_ace_rights ACE ACCESSRIGHTS
set_ace_sid ACE ACCOUNT
set_ace_type ACE ACETYPE
set_acl_aces ACL ACELIST
set_resource_integrity RESTYPE NAME INTEGRITYLEVEL INTEGRITYPOLICY ?options?
set_resource_security_descriptor RESTYPE NAME SECD ?options?
set_security_descriptor_dacl SECD ACL
set_security_descriptor_group SECD ACCOUNT
set_security_descriptor_integrity SECD INTEGRITYLEVEL INTEGRITYPOLICY ?options?
set_security_descriptor_owner SECD ACCOUNT
set_security_descriptor_sacl SECD ACL
set_thread_token TOKEN
set_token_integrity TOKEN INTEGRITYLEVEL
set_token_integrity_policy TOKEN ?no_write_up? ?new_process_min?
set_token_virtualization TOKEN ENABLE
sort_aces ACELIST
sort_acl_aces ACL

DESCRIPTION

This module provides procedures related to access control in Windows operating systems.

Locally Unique Identifiers

A Locally Unique Identifier (LUID) is a string generated by the command new_luid that is guaranteed to be unique on that system for that boot session. Unique means it will not be generated by some other call to that command.

Access Tokens and Privileges

An access token is associated with a process or a thread and contains various elements that determine the security context for the process or thread.

The commands open_process_token and open_thread_token retrieve the access tokens associated with a process and thread respectively. An access token for a specific user account may be obtained using open_user_token. The returned tokens can be passed to other functions to retrieve or set information for the process or thread's privileges and other security related information. When no longer required, the tokens must be passed to close_token in order to release resources.

The command get_token_info retrieves information from a token. Individual pieces of the token can also be retrieved via commands get_token_user, get_token_groups, get_token_primary_group, get_token_owner, get_token_groups_and_attrs and get_token_restricted_groups_and_attrs.

The commands get_token_privileges, check_enabled_token_privileges and get_token_privileges_and_attrs retrieve information related to the privileges associated with a token. The commands enable_token_privileges, disable_token_privileges and disable_all_token_privileges allow manipulation of the same. Similarly, enable_privileges and disable_privileges can be used to enable and disable privileges for the current process. eval_with_privileges evaluates a script after enabling specified privileges.

The command get_privilege_description returns a description of a privilege. An empty string is returned if the specified privilege is not a known privilege.

The commands get_token_type and get_token_impersonation_level return information related to impersonation.

get_token_source returns the source of a token. get_token_statistics returns various other pieces of information, such as expiration, memory usage etc.

The commands map_luid_to_privilege and map_privilge_to_luid map LUID's to privilege names. The command is_valid_luid_syntax can be used to check the syntactic validity of a LUID.

Impersonation

Windows allows a thread or process to impersonate a user different from the account in which it was started (given the proper privileges). The functions for impersonation and reverting back are impersonate_token, impersonate_user, impersonate_self, set_thread_token and revert_to_self. For impersonating named pipe clients, use the impersonate_namedpipe_client command from the twapi_namedpipe package.

The command get_current_user returns the user account for the thread taking into consideration any ongoing impersonation.

Impersonation may be done at several levels. These levels control the degree to which the impersonator takes on the identity of the impersonated client. The following constants define the different levels:

anonymous | The impersonating process cannot obtain identification information about the client or impersonate it.
identification | The impersonating process cannot impersonate the client (ie. access resources using the client's credentials) but can obtain identity and privilege information about the client. This can be used for controlling access to its own objects (as opposed to operating system resources).
impersonation | The impersonating process can impersonate the client only on the local system. The client credentials cannot be used to access other resources on the network.
delegation | The impersonating process can use the client's credentials for accessing network resources.

Access Rights

Access rights in the Windows API take the form of a bit mask with each bit signifying a specific desired or granted right. Access rights may be specified to TWAPI functions in the form of a single element or list of elements, each of which is an integer or a symbolic constant. The access rights bit mask passed to the underlying function is formed by OR'ing together the individual elements in the list. In the case of a symbolic constant, the access right is mapped to the appropriate bits before being OR'ed with the other elements.

The following symbolic constants define generic access rights that are mapped by each object type into its own specific rights: generic_read, generic_write, generic_execute and generic_all.

The following symbolic constants define access rights that are common to all securable object types: delete, read_control, write_dac, write_owner, synchronize, standard_rights_read, standard_rights_write, standard_rights_execute, standard_rights_required and standard_rights_all. Refer to the Windows SDK for a definition of these access rights.

In addition to the standard rights, specific object types may have other access rights associated with them as described in the following table.

Desktops | desktop_readobjects, desktop_createwindow, desktop_createmenu, desktop_hookcontrol, desktop_journalrecord, desktop_journalplayback, desktop_enumerate, desktop_writeobjects, desktop_switchdesktop.
Events | event_all_access, event_modify_state.
Files | file_all_access, file_generic_read, file_generic_write, file_generic_execute, file_read_data, file_write_data, file_append_data, file_read_ea, file_write_ea, file_execute, file_delete_child, file_read_attributes, file_write_attributes
Mutexes | mutex_all_access, mutex_modify_state
Named pipes | file_all_access, file_read_data, file_write_data, file_create_pipe_instance, file_read_attributes, file_write_attributes
Processes | process_all_access, process_terminate, process_create_thread, process_set_sessionid, process_vm_operation, process_vm_read, process_vm_write, process_dup_handle, process_create_process, process_set_quota, process_set_information, process_query_information, process_suspend_resume
Registry | key_all_access, key_read, key_write, key_execute, key_query_value, key_set_value, key_create_sub_key, key_enumerate_sub_keys, key_notify, key_create_link, key_wow64_32key, key_wow64_64key, key_wow64_res
Semaphores | semaphore_all_access, semaphore_modify_state
Services | service_all_access, service_query_config, service_change_config, service_query_status, service_enumerate_dependents, service_start, service_stop, service_pause_continue, service_interrogate, service_user_defined_control
Threads | thread_all_access, thread_terminate, thread_suspend_resume, thread_get_context, thread_set_context, thread_set_information, thread_query_information, thread_set_thread_token, thread_impersonate, thread_direct_impersonation
Timers | timer_all_access, timer_query_state, timer_modify_state.
Tokens | token_all_access, token_assign_primary, token_duplicate, token_impersonate, token_query, token_query_source, token_adjust_privileges, token_adjust_groups, token_adjust_default, token_adjust_sessionid.
Window stations | winsta_enumdesktops, winsta_readattributes, winsta_accessclipboard, winsta_createdesktop, winsta_writeattributes, winsta_accessglobalatoms, winsta_exitwindows, winsta_enumerate, winsta_readscreen, winsta_all.

Note that some of the symbolic access rights are a combination of other access rights. For example, file_all_access includes all other rights associated with a file object. When an access rights list is returned from a command, it includes both the individual symbolic rights as well as all valid symbols for combined rights.

Access Control Entries

Several functions deal with access control entries (ACE) either directly or as part of the more complex structures. A new ACE may be created through the new_ace command. The structure of an ACE should be treated as opaque and the fields should be manipulated only through the access control entry functions. An access control entry contains the fields described below.

The type of an ACE may be one of the following values: allow, deny, audit, alarm, allow_compound, allow_object, deny_object, audit_object, alarm_object, allow_callback, deny_callback, allow_callback_object, deny_callback_object, audit_callback, alarm_callback, audit_callback_object, alarm_callback_object, mandatory_label. Currently, only the allow, deny and audit type ACE's are supported. The type of an ACE may be manipulated through the get_ace_type and set_ace_type commands.

Each ACE has an SID associated with it that indicates the user or group that the ACE applies to. This may be retrieved or set using the get_ace_sid and set_ace_sid functions.

The access rights granted or restricted by an ACE can be manipulated through the get_ace_rights and set_ace_rights functions.

An ACE may be recursively applied to objects within a container. This is controlled through the get_ace_inheritance and set_ace_inheritance commands.

The command sort_aces may be used to sort a list of ACE elements into the order recommended by Windows.

The command get_ace_text returns a textual description of an ACE.

Access Control List

An access control list (ACL) is an ordered list of access control entries that is applied to a resource. The command new_acl creates a new ACL with an optional set of ACE elements. For the common case of granting access only specific accounts, new_restricted_dacl provides a simpler and more convenient interface.

The commands get_acl_aces and set_acl_aces may be used to retrieve or set the access control entries in the ACL. Alternatively, the commands prepend_acl_aces and append_acl_aces may be used to place additional ACEs in front of or after, respectively, of the current entries in an ACL.

Access control lists are of two types - a discretionary access control list (DACL) controls the operations that may be invoked on a resource based on the identity of the accessor, while a system access control list (SACL) controls the audit events that are generated when the resource is accessed. A SACL should contain only ACE elements of types prefixed with audit or mandatory_label while a DACL should only contain ACE elements of other types.

The list of ACE elements in an ACL may be resorted to conform to the Windows recommended order through the sort_acl_aces command.

Security Descriptors

A security descriptor is associated with a resource and ties together various information that controls access to the resource including the SID of the owner of the resource, the SID of the primary group, a discretionary access control list (DACL) and a system access control list (SACL).

A new security descriptor may be created through the command new_security_descriptor.

The commands get_security_descriptor_owner, get_security_descriptor_group, set_security_descriptor_owner and set_security_descriptor_group retrieve and set the owner and group attributes of a security descriptor.

The commands get_security_descriptor_dacl, get_security_descriptor_sacl, set_security_descriptor_dacl and set_security_descriptor_sacl retrieve and set the DACL and SACL fields of a security descriptor. It is important to distinguish between the absence of a DACL (or SACL) in a security descriptor and an empty DACL (or SACL). The former results in everyone being allowed to access the object whereas the latter results in no one being allowed to access the object. When modifying or creating a security descriptor, pass the literal string null to indicate that the security descriptor has no DACL (or SACL). An empty DACL (or SACL) on the other hand is indicated simply by passing an ACL that does not contain any ACEs.

The command get_security_descriptor_control returns the control flags associated with the security descriptor.

Note that not all fields in a security descriptor need to be initialized. For example, to change the owner of a resource, you only need to create a descriptor with the owner field initialized either at creation time or through a subsequent call to set_security_descriptor_owner. Then this can be passed to the appropriate function to set a resource's security with an option indicating that only the owner field should be changed.

The security information associated with each resource type can be retrieved and modified through functions get_resource_security_descriptor and set_resource_security_descriptor.

The command get_security_descriptor_text returns a textual description of a security descriptor. Commands security_descriptor_to_sddl and sddl_to_security_descriptor can be used to convert security descriptors to SDDL format.

Logon Sessions

A logon session is identified by an LUID and provides the context for a particular instance of an authenticated security principal where the principal may be a user, a computer, a service etc. A single principal, for example a user, may have multiple logon sessions concurrently present at any time. The command find_logon_sessions allows enumeration of logon sessions. The details associated with each can be obtained through the get_logon_session_info command.

Windows Credentials

The Windows credentials manager maintains a cache of credentials for a user account or logon session. The twapi_security package provides some additional commands to those already present in the twapi_base package.

The credentials returns a list of credentials for the calling process.

User Account Control

Windows Vista and later versions include the User Account Control (UAC) feature that runs even adminstrator account processes with reduced privileges unless explicitly elevated by the user. The command get_token_elevation checks whether a particular process token is elevated or not. The command get_token_linked_token returns the token handle for the token that is linked to an elevated or limited token.

Similarly, the Windows Integrity mechanism attempts to distinguish between applications at different levels of trust and control access to resources accordingly. The commands get_token_integrity and set_token_integrity allow retrieving and setting the integrity level associated with a process token. Alternatively, the higher level commands get_process_integrity and set_process_integrity can also be used for this purpose.

The associated policy for maintaining integrity levels can be read and modified using get_token_integrity_policy and set_token_integrity_policy.

The integrity level associated with a resource can be retrieved and set using the commands get_resource_integrity and set_resource_integrity respectively. The integrity level stored in a security descriptor can be retrieved and set using get_security_descriptor_integrity and set_security_descriptor_integrity.

The above security mechanims also introduced compatibility issues for applications written for older versions of Windows which expected to be able to write to resources at higher integrity levels, such as the system directory, that were now restricted. To allow these applications to run, Windows silently virtualizes protected resources and redirects reads and writes to these resources from such applications. The get_token_virtualization can be used to detect if a process is virtualized in this fashion and set_token_virtualization can be used to enable or disable the state.

For a tutorial and discussion of these issues, refer to the MSDN article.

Commands

append_acl_aces ACL ACELIST
Appends the list of ACEs in ACELIST to the entries in the given ACL. Returns the modified ACL.
check_enabled_privileges PRIVILEGES ?-any?
Without the -any option, the command returns 1 if the given list of privileges is enabled in the token, and 0 otherwise. If the option -any is specified, the command returns 1 if at least one of the privileges is enabled, and 0 otherwise. PRIVLIST is a list of privilege names or LUIDs.
close_token TOKEN
Frees resources associated with an access token.
credentials ?TARGETPATTERN?
Returns a list of current credentials from the user's credential set. If TARGETPATTERN is not specified, all credentials are returned. Otherwise, only those with targets matching TARGETPATTERN are returned. TARGETPATERN is a name prefix optionally terminating in a wildcard * character.

The returned list elements are dictionaries with the following keys:

comment | Any associated descriptive comment for the credential that might be added by the user.
lastwritten | The last time the credentials were written as the number of 100ns since Jan 1, 1601 (see large_system_time_to_secs_since_1970).
persist | One of the values session, local_machine or enterprise depending on whether the credentials are persisted for the current logon session only, or are persisted on the local system and are visible to future logon session for the user on that system, or are persisted on the local system and are visible to logon session for that user from other systems.
target | The name of the target for which the credential is applicable.
targetalias | An alias for the target.
type | The credential type which is one of generic, domain_password, domain_certificate, domain_visible_password generic_certificate, domain_extended.
username | The user name associated with the target credential.
The dictionary may contain other elements. These should be ignored and are liable to change.

For more information, see the description of the CREDENTIALS structure in the Windows SDK.

disable_all_token_privileges TOKEN
This command disables all privileges in the token. An error will be raised if the privilege does not exist or cannot be disabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously disabled. This list can be passed to enable_token_privileges to undo the privilege modifications made by this call.
disable_privileges PRIVLIST
This command disables one or more privileges in the current process. PRIVLIST is a list of privileges each of which may be either a symbolic privilege such as SeLoadDriverPrivilege or a LUID corresponding to a privilege.

An error will be raised if the privilege does not exist or cannot be disabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously disabled. This list can be passed to enable_privileges to undo the privilege modifications made by this call.
disable_token_privileges TOKEN PRIVLIST
This command disables one or more privileges in the token. PRIVLIST is a list of privileges each of which may be either a symbolic privilege such as SeLoadDriverPrivilege or a LUID corresponding to a privilege.

An error will be raised if the privilege does not exist or cannot be disabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously disabled. This list can be passed to enable_token_privileges to restore the token privileges to their original value.
enable_privileges PRIVLIST
This command enables one or more privileges in the current process. PRIVLIST is a list of privileges each of which may be either a symbolic privilege such as SeLoadDriverPrivilege or a LUID corresponding to a privilege.

An error will be raised if a privilege does not exist or cannot be enabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously enabled. This list can be passed to disable_privileges to undo the privilege modifications made by this call.
enable_token_privileges TOKEN PRIVLIST
This command enables one or more privileges in the token. PRIVLIST is a list of privileges each of which may be either a symbolic privilege such as SeLoadDriverPrivilege or a LUID corresponding to a privilege.

An error will be raised if a privilege does not exist or cannot be enabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously enabled. This list can be passed to disable_token_privileges to undo the privilege modifications made by this call.
eval_with_privileges SCRIPT PRIVLIST
The command enables the privileges specified in PRIVLIST, if they were not already enabled, and then evaluates SCRIPT in the caller's context. The command returns the result of SCRIPT after restoring the privileges in effect when the command was called.
find_logon_sessions ?options?
Returns a list of LUID values that identify the logon sessions on the system. By default, all logon sessions are returned. One or more of the following options may be specified to restrict the set of logon sessions that are returned.

-user ACCOUNT | Only returns logon sessions for the specified user. ACCOUNT may be either the account name or the SID for the user.
-type SESSIONTYPELIST | Only returns logon sessions that match one of the specified types. SESSIONTYPELIST is a list of integer logon session types defined in the Windows SDK or the following equivalent tokens: interactive, network, batch, service, proxy, unlockworkstation, networkclear, newcredentials, remoteinteractive, cachedinteractive, cachedremoteinteractive or cachedunlockworkstation.
-tssession TSSESSION | Only returns those logon sessions belonging to the terminal services session identified by TSSESSION.

get_ace_inheritance ACE
Returns a flat list of "option value" pairs that indicate the inheritance characteristics of the ACE. The option elements are -self, -recursecontainers, -recurseobjects and -recurseonelevelonly as described in the documentation for new_ace. In addition, the read-only option -inherited indicates whether the ACE has been inherited from an ancestor or not.
get_ace_rights ACE ?-resourcetype RESOURCETYPE? ?-raw?
Returns a list of access rights contained within an ACE. This is a list of symbolic constants and bit masks as described in Access Rights. The option -resourcetype may be used to map the access rights to symbolic constants for a specific type of resource. RESOURCETYPE must be one of file, pipe, service, registry, process, thread or token.

If the -raw option is specified, the access rights are returned as a single hex bitmask.
get_ace_sid ACE
Returns the SID of the given ACE.
get_ace_text ACE ?-resourcetype RESOURCETYPE?
Returns a textual description of the specified ACE. The option -resourcetype may be specified to indicate that the ACE is for a particular resource type. RESOURCETYPE must be one of the resource type values defined for the get_ace_rights command. This command is primarily useful for debugging and troubleshooting purposes.
get_ace_type ACE
Returns the type of the given ACE. See Access Control Entries for the possible types.
get_acl_aces ACL
Returns the ordered list of ACE elements in the given ACL.
get_acl_rev ACL
Returns the revision level of an ACL. Note that this is controlled by the ACEs in the ACL and cannot be set directly.
get_current_user ?FORMATOPTION?
Returns the user account for the current thread. If the thread is impersonating, this command returns the account being impersonated. Note this is not the same as the $::env(USERNAME) variable as the latter does not take impersonation into account. By default, the command returns the name of the user account in NT 4.0 SAM-compatible format. One of the following options may be specified to return the name in a different format:

-fullyqualifieddn | Fully qualified Active Directory distinguished name.
-samcompatible | NT 4.0 SAM account name (default).
-display | Active Directory human-friendly display name.
-uniqueid | Active Directory GUID format name. This is NOT the same as the SID.
-canonical | Active Directory canonical format.
-userprincipal | User principal format.
-canonicalex | Active Directory canonical format except that the rightmost / is replaced by a newline.
-serviceprincipal | Generalized service principal name.
-dnsdomain | DNS domain followed by the SAM user name.
-sid | User SID instead of name.

Note that all options except -samcompatible and -sid require that the system be part of a Active Directory domain, else an error is raised that no mapping to that format exists.

get_logon_session_info SESSIONLUID ?options?
Returns details for the logon session identified by SESSIONLUID. The information is returned as a flat list of option value pairs and depends on the specified options:

-all | Returns the values for all options.
-authpackage | Returns the name of the package that authenticated the session.
-dnsdomain | Returns the DNS name for the owner of the logon session. This is always empty on Windows 2000.
-logondomain | Returns the name of the domain used to authenticate the session.
-logonid | Returns the LUID for the session (same as SESSIONLUID).
-logonserver | Returns the name of the server used to authenticate the session. This is always an empty string on Windows 2000.
-logontime | Returns the time session owner logged on.
-type | Returns the logon session type (see find_logon_sessions).
-sid | Returns the SID for the session owner.
-tssession | Returns the terminal session identifier for the logon session.
-user | Returns the user name for the session owner.
-userprincipal | Returns the user principal name for the session owner. This is always an empty string on Windows 2000.

get_privilege_description PRIVILEGE
Returns a string description of the specified privilege.
get_resource_integrity RESTYPE NAME ?options?
Retrieves the integrity level associated with a resource. RESTYPE specifies the resource type and if option -handle is not specified, must be one of file, service (Windows service), printer, registry, share (Network shares) or kernelobj (kernel objects such as mutexes, semaphores and events). If option -handle is specified, then RESTYPE may also be one of windowstation, directoryservice, directoryserviceall, providerdefined, wmiguid or registrywow6432key but not share.

NAME specifies the name of the resource, for example, the path of a file unless option -handle is specified in which case it is the handle to the resource.

On systems that do not support integrity levels, the command returns an empty list. Otherwise, a list with two elements is returned. The first element of the list is the integrity value associated with the resource, by default represented as an integer value between 0 and 65535. If the option -raw is specified, the integrity level is returned as the raw SID value as stored internally by Windows in the token. Alternatively, if the -label option is specified the corresponding integrity level range label is returned which is one of untrusted (0-4095), low (4096-8191), medium (8192-12287, high (12288-16383) or system (anything higher).

The second element of the returned list is a list containing zero or or more of the following values: system_mandatory_label_no_write_up, system_mandatory_label_no_read_up, system_mandatory_label_no_execute_up. These control the operations allowed on the resource by processes with lower integrity levels. Refer to the Windows SDK for more details.
get_resource_security_descriptor RESTYPE NAME ?options?
Retrieves the security descriptor attached to a operating system resource. RESTYPE specifies the resource type and if option -handle is not specified, must be one of file, service (Windows service), printer, registry, share (Network shares) or kernelobj (kernel objects such as mutexes, semaphores and events). If option -handle is specified, then RESTYPE may also be one of windowstation, directoryservice, directoryserviceall, providerdefined, wmiguid or registrywow6432key but not share.

NAME specifies the name of the resource, for example, the path of a file unless option -handle is specified in which case it is the handle to the resource.

Without any options being specified, the returned security descriptor will contain only the owner, group and DACL fields. The SACL field will not contain valid data. The following options may be specified to control which fields are returned in the security descriptor:

-all | Includes all fields in the security descriptor. This requires the caller to have the SeSecurityPrivilege privilege enabled.
-dacl | Includes the DACL in the returned security descriptor.
-group | Includes the group information in the returned security descriptor.
-owner | Includes the owner information in the returned security descriptor.
-sacl | Includes the SACL in the returned security descriptor. This requires the caller to have the SeSecurityPrivilege privilege enabled.

get_security_descriptor_control SECD
Returns the control flags contained in the given security descriptor SECD. The flags are returned as a list of zero or more tokens from the following: owner_defaulted, group_defaulted, dacl_present, dacl_defaulted, sacl_present, sacl_defaulted, dacl_auto_inherit_req, sacl_auto_inherit_req, dacl_auto_inherited, sacl_auto_inherited, dacl_protected, sacl_protected, rm_control_valid, self_relative. Refer to the Windows Platform SDK for details.
get_security_descriptor_dacl SECD
Returns the DACL contained in the given security descriptor SECD.
get_security_descriptor_group SECD
Returns the group SID for the given security descriptor SECD.
get_security_descriptor_integrity SECD ?-label|-raw?
Returns the integrity level stored in the given security descriptor SECD. Refer to get_resource_integrity for the option description and format of the returned value.
get_security_descriptor_owner SECD
Returns the owner SID for the given security descriptor SECD.
get_security_descriptor_sacl SECD
Returns the SACL contained in the given security descriptor SECD.
get_security_descriptor_text SECD ?-resourcetype RESOURCETYPE?
Returns a textual description of the specified security descriptor SECD. The option -resourcetype may be specified to indicate that the security descriptor is for a particular resource type. RESOURCETYPE must be one of the resource type values defined for the get_ace_rights command. This command is primarily useful for debugging and troubleshooting purposes.
get_token_elevation TOKEN
On systems that support Windows UAC, this command returns one of default, full or limited depending on whether the token corresponds to a process is running with default privileges for the account, full (elevated) privileges for the account or limited (filtered) privileges. On systems that do not support UAC, the command always returns default.

To directly access the elevation level of a process, you can also use the get_process_elevation command or the -elevation option of the get_process_info command.
get_token_groups TOKEN ?-name?
Returns the list of group SID's for the token. If -name is specified, returns the group names instead of the SID's.
get_token_groups_and_attrs TOKEN
Returns the list of group SID's for the token together with the attributes for each group. The returned list is of the form SID ATTRIBUTELIST SID ATTRIBUTELIST... where ATTRIBUTELIST is a list of zero or more of the following attributes: enabled, enabled_by_default, logon_id, mandatory, owner, resource, integrity, integrity_enabled and use_for_deny_only. Refer to the Windows Platform SDK for details.
get_token_impersonation_level TOKEN
Gets the current impersonation level for the token. This may have one of the following values: anonymous, identification, impersonation, or delegation. See Impersonation for details.
get_token_info TOKEN ?options?
Returns a dictionary containing the token fields specified in options. The following fields may be requested:

-disabledprivileges | Returns the list of privileges in the token that are currently disabled.
-elevation | Returns the elevation level for the token (see get_process_elevation).
-enabledprivileges | Returns the list of privileges that are enabled in the token.
-groupattrs | Returns a dictionary whose keys are group SID's contained in the token, with the corresponding value being a list of attributes for the group.
-groups | Returns the list of groups included in the token. For domain accounts, an error is raised if the domain is unreachable. Use -groupattrs to avoid this.
-integrity | Returns the numeric integrity level associated with the token (see get_process_integrity).
-integritylabel | Returns the label for the range for the integrity level associated with the token (see get_process_integrity).
-linkedtoken | If TOKEN is an elevated or limited token, this command returns the corresponding limited or elevated token linked to it.
-logonsession | Returns the LUID of the logon session for the associated with the token.
-primarygroup | Returns the primary group for the token. For domain accounts, an error is raised if the domain is unreachable. Use -primarygroupsid to avoid this.
-primarygroupsid | Returns the SID of primary group for the token.
-privileges | Returns the list of enabled and disabled process privileges in the same format as get_token_privileges. Deprecated, use -enabledprivileges and -disabledprivileges instead.
-restrictedgroupattrs | Returns a dictionary whose keys are SID's for the restricted groups contained in the token, with the corresponding value being a list of attributes for the group. See get_token_groups_and_attrs for details.
-restrictedgroups | Returns the list of restricted groups in the token. For domain accounts, an error is raised if the domain is unreachable. Use -restrictedgroupattrs to avoid this.
-usersid | Returns the SID of the user account associated with the token.
-virtualized | Returns true if the process associated with the token is virtualized and false otherwise. See virtualized_process.

get_token_integrity TOKEN ?-raw | -label?
On systems that support Windows UAC, this command returns the integrity level associated with the token. The integrity value is an integer value between 0 and 65535. If the option -raw is specified, the integrity level is returned as the raw SID value as stored internally by Windows in the token. Alternatively, if the -label is specified the corresponding integrity level range label is returned which is one of untrusted (0-4095), low (4096-8191), medium (8192-12287, high (12288-16383) or system (anything higher).

On systems that do not support integrity levels, this command always returns an appropriately formatted value corresponding to the medium integrity level.

To directly access the integrity level of a process, you can also use the get_process_integrity command or the -integrity option of the get_process_info command.
get_token_integrity_policy TOKEN
On systems that support Windows UAC, this command returns the integrity policy associated with the token. The integrity policy is a list containing zero or more values from table below.

no_write_up | If present, writes to objects at a higher integrity level are denied.
new_process_min | If present, new processes will be created at an integrity level that is the minimum of the integrity level of the token and the integrity level associated with the executable file of the new process.

On systems that do not support integrity levels, this command always returns an empty list indicating no integrity policy is in effect.

get_token_linked_token TOKEN
If TOKEN is an elevated or limited token, this command returns the corresponding limited or elevated token linked to it.
get_token_owner TOKEN ?-name?
Returns the SID of the entity (user, group, etc.) that will be used as the owner for objects created using this token. If -name is specified, the name of the entity is returned instead of the SID.
get_token_primary_group TOKEN ?-name?
Returns the SID of the group that will be used as the primary group for objects created using this token. If -name is specified, the name of the group is returned instead of the SID.
get_token_privileges TOKEN ?-all?
Returns the list of enabled privileges in the token. If the option -all is specified, returns a list of two sublists. The first containing the enabled privileges and the second the disabled privileges.
get_token_privileges_and_attrs TOKEN
Returns the list of privileges in the token together with the attributes for each. The returned list is of the form PRIVILEGE ATTRIBUTELIST PRIVILEGE ATTRIBUTELIST... where ATTRIBUTELIST is a list of zero or more of the following attributes: enabled, enabled_by_default and used_for_access.
get_token_restricted_groups_and_attrs TOKEN
Returns the list of restricted group SID's for the token together with the attributes for each group. The returned list is of the form SID ATTRIBUTELIST SID ATTRIBUTELIST... where ATTRIBUTELIST is a list of zero or more of the following attributes: enabled, enabled_by_default, logon_id, mandatory, owner, resource, integrity, integrity_enabled and use_for_deny_only. Refer to the Windows Platform SDK for details.
get_token_source TOKEN
Returns the source of an access token.
get_token_statistics TOKEN
Returns various token statistics as a list of field value pairs. The following fields are returned:

authluid | The LUID for the session represented by the token.
expiration | Expiration time for the token. Windows does not currently support expiration for access tokens.
dynamicavailable | Number of free bytes available for storing default protection and primary group identifier for the token.
dynamiccharged | Number of bytes allocated for storing default protection and primary group identifier for the token.
groupcount | Number of group SID's included in the token.
impersonationlevel | The impersonation level of the token. This value is only valid if the field type has the value impersonation.
luid | An LUID that identifies the instance of the token.
modificationluid | An LUID that changes every time the token is modified.
privilegecount | The number of privileges (including disabled ones) that are included in the token.
type | The type of the token - primary or impersonation.

get_token_type TOKEN
Returns the type of the token: either primary, or impersonation.
get_token_user TOKEN ?-name?
Returns the SID of the user account associated with the token. If -name is specified, returns the name of the account instead of its SID.
get_token_virtualization TOKEN
Returns true if the token indicates a virtualized process where the system redirects writes to protected file and registry locations and false otherwise. On systems that do not support UAC, the command will always return false.

To directly retrieve the virtualization status of a process, you can also use the virtualized_process command or the -virtualized option of the get_process_info command.
impersonate_self IMPERSONATIONLEVEL
Assigns an impersonation token to the current thread based on the security context of the process. The security characteristics of the thread can then be changed (for example by modifying the privileges of its token) without impacting the security context of the remaining threads in the process.

IMPERSONATIONLEVEL may have any of the values allowed for impersonation levels (see Impersonation).
impersonate_token TOKEN
Changes the security context of the calling thread to that of the user account associated with the specified token. TOKEN is a token returned from a command such as open_user_token, open_process_token or open_thread_token.

The caller must be careful that exceptions raised by this command are handled correctly. It should not continue with normal processing as though the security context was changed to that of the token.
impersonate_user USERNAME PASSWORD ?options?
Changes the security context of the calling thread to that of the specified user account. This is essentially a wrapper around open_user_token and impersonate_token. Refer to the documentation of open_user_token for a description of the arguments.

The caller must be careful that exceptions raised by this command are handled correctly. It should not continue with normal processing as though the security context was changed to that of the user.
is_valid_luid_syntax LUID
Returns if LUID is a syntactically valid LUID, else 0.
map_luid_to_privilege LUID ?-system SYSTEMNAME? ?-mapunknown?
Returns the privilege name corresponding to the given LUID. If LUID does not correspond to a system defined privilege, an exception is raised unless the -mapunknown option is specified. In this case, the command will return a string of the form Privilege-LUID. As a special case, if LUID is a privilege name (and not a LUID), returns it as is. The option -system may be used to specify a system as described in Standard Options.
map_privilege_to_luid PRIVILEGE ?-system SYSTEMNAME? ?-mapunknown?
Returns the LUID corresponding to the given privilege name. If PRIVILEGE does not correspond to a system defined privilege name or a constructed privilege name of the form Privilege-LUID, an exception is raised. As a special case, if PRIVILEGE is itself a LUID, it is returned. The option -system may be used to specify a system as described in Standard Options.
new_ace ACETYPE ACCOUNT ACCESSRIGHTS ?options?
Creates and returns a new ACE. ACETYPE is the type of the ACE and should be one of supported values described in Access Control Entries. The user or group that the ACE pertains to is given by ACCOUNT which may be either a name or a SID. ACCESSRIGHTS determines the rights to be granted or denied by the ACE and should be a list of one or more constants described in Access Rights.

The following options may be specified when creating an ACE:

-self BOOLEAN | If the specified value is 1 (default), the ACE applies to the object to which it is attached. If the specified value is 0, then the created ACE does not apply to the object with which it is attached. In this case, it only applies to the descendents of that object as indicated by the other options.
-recursecontainers BOOLEAN | If the specified value is 1, the ACE is also applied to all descendents of the object to which the ACE is attached that are themselves containers. For example, in the case of a file ACE, this would indicate that the ACE also apply to all subdirectories. If 0 (default), the ACE does not apply to descendents that are containers.
-recurseobjects BOOLEAN | If the specified value is 1, the ACE is also applied to all descendents of the object to which the ACE is attached that are not themselves containers. For example, in the case of a file ACE, this would indicate that the ACE also apply to all files under all subdirectories below a directory but not to the subdirectories themselves. If 0 (default), the ACE does not apply to descendents that are not containers.
-recurseonelevelonly BOOLEAN | If the specified value is 0 (default), the -recursecontainers and -recurseobjects options have effect at all levels below the container object to which the ACE is applied. If the value is 1, the ACE is only applied to the immediate children of the container object. This option has no effect if neither -recurseobjects nor -recursecontainers is specified.

new_acl ?ACELIST?
Returns a new ACL initialized. ACELIST may be optionally specified to prepopulate the ACL with a list of ACE elements.
new_luid
Returns a LUID.
new_restricted_dacl ACCOUNTS RIGHTS
Returns a new DACL where the access rights specified by RIGHTS are granted to the accounts included in ACCOUNTS. Other accounts are implicitly denied. Accounts may be specified using either the account names or SID's. RIGHTS is a list of symbolic constants and bit masks as described in Access Rights.
new_security_descriptor ?options?
Returns a new security descriptor. The following options may be specified to initialize various fields of the security descriptor:

-owner ACCOUNT | The owner field of the security descriptor is set to the SID for the specified account. ACCOUNT may be the SID itself or the name of the user or group account.
-group ACCOUNT | The primary group field of the security descriptor is set to the SID for the specified account. ACCOUNT may be the SID itself or the name of the group.
-dacl ACL | The DACL field of the security descriptor is set to ACL. If ACL is the string "null", no DACL will be present in the security descriptor.
-sacl ACL | The SACL field of the security descriptor is set to ACL. If ACL is the string "null", no SACL will be present in the security descriptor.

open_process_token ?-pid PID | -hprocess HPROCESS? ?-access DESIREDACCESS?
Returns a process token that can passed to other functions for querying and modifying security related data for a process. By default, the current process is assumed. The options -hprocess or -pid options may be used to retrieve the token for another process by passing a handle to it or its PID.

The -access option may be used to specify a list of desired access rights. If this option is not specified, access rights default to token_query. See Access Rights for a description of the format of this list and for a description of standard access rights.

In addition, the following symbols may be specified in the list: token_adjust_default, token_adjust_groups, token_adjust_privileges, token_adjust_sessionid, token_assign_primary, token_duplicate, token_execute, token_impersonate, token_query, token_query_source, token_read, token_write and token_all_access. See the documentation of OpenProcessToken in the Windows SDK for a description of each of these.

When no longer required, this token must be passed to close_token.
open_thread_token ?-tid TID | -hthread HTHREAD? ?-access DESIREDACCESS? ?-self BOOLEAN?
Returns a thread access token that can passed to other functions for querying and modifying security related data for a thread. By default, the current thread is assumed. The options -hthread or -tid options may be used to retrieve the token for another thread by passing a handle to it or its TID.

Note that the command will generate an error if the thread does not have a token. In this case, ::errorCode facility and code are set to WINDOWS and 1008 respectively. The caller can retrieve the process token instead.

The -access option specifies the desired access mode. See open_process_token for more details.

The -self option controls whether the access check is to be made against the security context of the thread or against the security context of the process. If specified as false, the security context of the thread is used, else that of the process.

When no longer required, this token must be passed to close_token.
open_user_token USERNAME PASSWORD ?options?
Returns a token corresponding to a logon session for the USERNAME account. This token may be used for impersonation or starting processes under a different account. When no longer required, this token must be passed to close_token.

USERNAME is the name of the account and may be specified either as just the account name, or in UPN format as user@DNS_domain_name.

The following options may be specified:

-domain DOMAIN | Specifies the domain for the user. This option must not be specified if USERNAME is in UPN format user@DNS_domain_name which includes a domain name. If USERNAME is not in UPN format and -domain is not specified, the account validation is done only using the local account database.
-type LOGONTYPE | Indicates the logon type. LOGONTYPE must be one of batch, interactive, network, network_cleartext, new_credentials, service or unlock. Refer to the Windows SDK documentation of LogonUser for details.
-provider PROVIDER | Selects a logon provider. PROVIDER must be one of winnt50, winnt40 or winnt35. If this option is not specified, the operating system picks the standard (version dependent) logon provider for the system. Specify winnt40 to select the NTLM provider and winnt50 (only valid for Windows 2000 and up) for the negotiate logon provider.

prepend_acl_aces ACL ACELIST
Prepends the list of ACEs in ACELIST to the entries in the given ACL. Returns the modified ACL.
reset_thread_token
Ends the current thread's impersonation state.
revert_to_self
Calling this function will restore the original security context for the process thereby ending any impersonation initiated by prior impersonation commands such as impersonate_user.

Any exceptions raised by this command will result in the process continuing to run in the impersonation context. This is dangerous from a security perspective and the caller should normally immediately exit.
sddl_to_security_descriptor SECD
Parses a SDDL string and returns the corresponding security descriptor.
security_descriptor_to_sddl SECD
Returns the specified security descriptor in SDDL string format.
set_ace_inheritance ACE ?options?
Returns a new ACE constructed from ACE with inheritance attributes defined by options. These may be one or more of -self, -recursecontainers, -recurseobjects and -recurseonelevelonly as described in the documentation for new_ace.
set_ace_rights ACE ACCESSRIGHTS
Returns a new ACE containing the access rights specified in ACCESSRIGHTS. This should be a list of symbolic constants and bit masks as described in Access Rights.
set_ace_sid ACE ACCOUNT
Returns a new ACE constructed from ACE but with its SID field set to be the SID for account ACCOUNT. ACCOUNT may be either the name or the SID of a user or group account.
set_ace_type ACE ACETYPE
Returns a new ACE constructed from ACE but with the type ACETYPE. See Access Control Entries for valid values of ACETYPE.
set_acl_aces ACL ACELIST
Sets the list of ACEs within an ACL to those given in ACELIST. Returns the modified ACL.
set_resource_integrity RESTYPE NAME INTEGRITYLEVEL INTEGRITYPOLICY ?options?
Sets the integrity level associated with a resource. See set_security_descriptor_integrity for a description of the INTEGRITYLEVEL and INTEGRITYPOLICY parameters and the options -recurseobjects and -recursecontainers. See set_resource_security_descriptor for description of RESTYPE, NAME and the -handle option.
set_resource_security_descriptor RESTYPE NAME SECD ?options?
Modifies the security descriptor attached to a operating system resource. RESTYPE specifies the resource type and if option -handle is not specified, must be one of file, service (Windows service), printer, registry, share (Network shares) or kernelobj (kernel objects such as mutexes, semaphores and events). If option -handle is specified, then RESTYPE may also be one of windowstation, directoryservice, directoryserviceall, providerdefined, wmiguid or registrywow6432key but must not be share.

NAME specifies the name of the resource, for example, the path of a file unless option -handle is specified in which case it is the handle to the resource.

The fields of the resource's security descriptor are modified based on the contents of SECD. At lease one of the options -all, -owner, -group, -dacl, -sacl or -mandatory_label must be specified. The specific fields modified depend on the options specified:

-all | All fields in the security descriptor are modified. This requires the caller to have the SeSecurityPrivilege privilege enabled.
-owner | The resource's owner is modified.
-group | The resource's group is modified.
-dacl | Changes the DACL attached to the resource.
-sacl | Changes the SACL attached to the resource. This requires the caller to have the SeSecurityPrivilege privilege enabled.
-protect_dacl | If this option is specified, the resource will not inherit any DACL's from its parent. Otherwise, the parent's DACL's flow down to the resource. This option only has effect if the -dacl option is specified. This option cannot be specified with -unprotect_dacl. If neither is specified, the current DACL inherit settings are preserved.
-protect_sacl | If this option is specified, the resource will not inherit any SACL's from its parent. Otherwise, the parent's SACL's flow down to the resource. This option only has effect if the -sacl option is specified. This option cannot be specified with -unprotect_sacl. If neither is specified, the current SACL inherit settings are preserved.
-unprotect_dacl | If this option is specified, the resource will inherit any DACL's from its parent. This option only has effect if the -dacl option is specified. This option cannot be specified with -protect_dacl. If neither is specified, the current DACL inherit settings are preserved.
-unprotect_sacl | If this option is specified, the resource will inherit any SACL's from its parent. This option only has effect if the -sacl option is specified. This option cannot be specified with -protect_sacl. If neither is specified, the current SACL inherit settings are preserved.

set_security_descriptor_dacl SECD ACL
Returns a security descriptor identical to SECD except for the DACL field which is set to ACL. If ACL is the string "null", the security descriptor is set to have no DACL. If ACL is an empty list, the security descriptor has an empty DACL, which is not the same not having a DACL.
set_security_descriptor_group SECD ACCOUNT
Returns a security descriptor identical to SECD except for the group field which is set to the SID for account ACCOUNT. ACCOUNT may be the SID itself or the name of the group.
set_security_descriptor_integrity SECD INTEGRITYLEVEL INTEGRITYPOLICY ?options?
Returns a new security descriptor based on SECD with the specified integrity. INTEGRITYLEVEL may be specified in one of the forms described in get_resource_integrity. INTEGRITYPOLICY is a list of one or more of the following: system_mandatory_label_no_write_up, system_mandatory_label_no_read_up, system_mandatory_label_no_execute_up. These control the operations allowed on the resource by processes with lower integrity levels. Refer to the Windows SDK for more details.

The following options may also be specified with the command:

-recursecontainers BOOLEAN | If the specified value is 1, the integrity is also applied to all descendents of the object to which the security descriptor is attached that are themselves containers. If 0 (default), the integrity is not inherited by descendents that are containers.
-recurseobjects BOOLEAN | If the specified value is 1, the integrity is also applied to all descendents of the object to which the security descriptor is attached that are not themselves containers. If 0 (default), the integrity does not apply to descendents that are not containers.

set_security_descriptor_owner SECD ACCOUNT
Returns a security descriptor identical to SECD except for the owner field which is set to the SID for account ACCOUNT. ACCOUNT may be the SID itself or the name of the user or group.
set_security_descriptor_sacl SECD ACL
Returns a security descriptor identical to SECD except for the SACL field which is set to ACL. If ACL is the string "null", the security descriptor is set to have no SACL.
set_thread_token TOKEN
Changes the security context of the current thread by associating it with the given token. This is generally used in combination with open_thread_token to implement an impersonation stack.
set_token_integrity TOKEN INTEGRITYLEVEL
On systems that support Windows UAC, this command sets the integrity level for a token. INTEGRITYLEVEL must be an integer value between 0 and 65535, a a SID value defined for a integrity level by Windows, or one of untrusted (0), low (4096), medium (8192, high (12288) or system.

On systems that do not support integrity levels, this command will raise an error unless the integrity level specified corresponds to medium integrity 8192, medium or S-1-16-8192. To directly set the integrity level of a process, you can also set_process_integrity command.
set_token_integrity_policy TOKEN ?no_write_up? ?new_process_min?
On systems that support Windows UAC, this command sets the integrity policy associated with the token. See get_token_integrity_policy for the meaning of no_write_up and new_process_min.
set_token_virtualization TOKEN ENABLE
Enables or disables virtualization of file and registry accesses depending on the boolean value of ENABLE. If this call is made on a system that does not support UAC, ENABLE must be false else an exception will be generated. The token must have been opened with token_adjust_default access.
sort_aces ACELIST
Although not enforced by the operating system, Windows has a recommended order in which multiple ACEs should be applied. The sort_aces command takes a list of ACE elements and returns a list that has been sorted as per the Windows recommendation. This sort order places all inherited ACEs after all non-inherited ACEs. Within each group, deny ACEs are placed before allow ACEs.
sort_acl_aces ACL
Rearranges the ACEs in the given ACL to conform to the Windows recommended order. Returns the modified ACL.

COPYRIGHT

Copyright © 2003-2010, Ashok P. Nadkarni


Event log - Event Log

Event log

Commands relating to reading and writing the Windows event log

SYNOPSIS

package require twapi_eventlog

eventlog_backup EVENTLOGHANDLE FILENAME
eventlog_clear EVENTLOGHANDLE ?-backup FILENAME?
eventlog_close EVENTLOGHANDLE
eventlog_count EVENTLOGHANDLE
eventlog_format_category EVENT_RECORD ?options?
eventlog_format_message EVENT_RECORD ?options?
eventlog_is_full EVENTLOGHANDLE
eventlog_log MESSAGE ?options?
eventlog_monitor_start EVENTLOGHANDLE SCRIPT
eventlog_monitor_stop EVENTNOTIFICATIONID
eventlog_oldest EVENTLOGHANDLE
eventlog_open ?options?
eventlog_read EVENTLOGHANDLE ?options?
eventlog_subscribe EVENTSOURCE
eventlog_write EVENTLOGHANDLE EVENTID ?options?
evt_channels
evt_clear_log CHANNELNAME ?-backup BACKUPFILE?
evt_close ?EVTHANDLE EVTHANDLE...?
evt_decode_event HEVENT ?options?
evt_decode_events HEVENTLIST
evt_export_log OUTFILE ?options?
evt_next HEVTRESULTSET ?options?
evt_publishers
evt_query ?options?
evt_subscribe CHANNELPATH ?options?
winlog_backup NAME BACKUPFILE
winlog_clear NAME ?-backup BACKUPFILE?
winlog_close WINLOGHANDLE
winlog_event_count ?options?
winlog_open ?options?
winlog_read WINLOGHANDLE ?-lcid LCID?
winlog_subscribe CHANNEL_OR_SOURCE

DESCRIPTION

This module provides commands for reading and writing the Windows event log. The following commands, although described here, are available in the twapi_base package itself and do not require this module to be loaded: eventlog_open, eventlog_log, eventlog_write and eventlog_close. This allows applications to write to the event log without this module being loaded.

Overview

The Windows event log provides a common application-independent mechanism for applications to log messages for diagnostic and informational purposes. The infrastructure and API's supporting this mechanism changed starting with Windows Vista. Although the older Windows API's will also work on Vista and later versions, they are limited in their support for events logged by applications using the newer API's.

TWAPI follows the Windows model by providing two sets of commands corresponding to the two Windows API sets and in addition also provides a set of unified commands:

  • Commands prefixed with eventlog are layered on top of the older pre-Vista API's. These will work on all Windows systems but reflect the inability of the underlying Windows API to fully format messages for events logged by applications using the new APIs.
  • Commands prefixed with evt are layered on top of the newer API's. These can deal with events logged by applications using either API version but can only be used on Windows Vista and later. They will raise an error on earlier versions of Windows.
  • Commands prefixed with winlog present a unified interface and direct calls to the appropriate Windows API depending on operating system version. They also present a single interface to the application irrespective of the operating system. However, they do not cover features that are unique to a specific Windows API and have a slight performance penalty.

For reading the event log, use of the winlog set of commands is recommended as those will use the underlying API that is most appropriate for that OS version. Alternatively, if platform-specific features not available through those commands are required, applications can call the eventlog or evt commands as appropriate after checking the operating system version.

Using eventlog Commands

This section describes the use of the older pre-Vista event log commands. Most access to the event log using this API requires a handle returned by the eventlog_open command. A handle allows either read or write access, but never both. Returned handles must be closed when no longer required by calling eventlog_close.

Events can be written using the eventlog_write command. The eventlog_log command provides an alternate, simpler but less flexible, interface for writing events.

Events can be read from an event log through the eventlog_read command. The returned event record can be formatted using eventlog_format_message and eventlog_format_category.

The command eventlog_count returns the number of records in the event log. eventlog_oldest returns the record number of the oldest record. The command eventlog_is_full indicates whether the event log is full.

To monitor the event log in real time, an application can poll at regular intervals. However, a more efficient way is to set up notifications through the eventlog_subscribe command.

Event logs can be backed up using eventlog_backup or as a side effect of clearing the log through eventlog_clear. The backup file can be read using the standard eventlog_open and eventlog_read commands.

Using evt Commands

This section describes the use of the newer event log commands available in Windows Vista and later Windows version. The corresponding Windows API functions are prefixed with Evt in the Windows SDK. TWAPI does not support writing events using the new API. Only reading of events is supported.

The new event logging subsystem in Windows Vista is considerably more flexible (and complex) than what was available in earlier Windows versions. The description below assumes the reader is familiar with the terms and concepts described in the Windows SDK.

In the Vista event logging system, channels implement a event stream to which event publishers can write events. The commands evt_channels and evt_publishers return the names of the channels and publishers on a system respectively.

Event consumers can consume events from channels in real time or from a saved event file using the the evt_query command. This command returns a handle to a result set containing matching events. These can then be retrieved and processed using the evt_next and evt_decode_events or evt_decode_event.

All handles returned by the evt_* commands, such as those returned from evt_next and evt_query must be closed by passing them to evt_close.

To monitor the event log in real time, use the evt_subscribe command.

Using winlog Commands

This section describes the use of the TWAPI's common interface to the old and new versions of Windows event log APIs. This is the recommended interface for consuming events but does not provide a command to write events.

The common access commands require a handle to the event log which can be obtained via the winlog_open command. The returned handle must be closed when no longer required by calling winlog_close.

Events can be read from an event log through the winlog_read command which returns a list of dictionaries containing the fields of each event. winlog_event_count returns the number of events in an event log.

Events can be written to a backup file using winlog_backup and cleared with winlog_clear.

To monitor the event log in real time, use the winlog_subscribe command.

Commands

eventlog_backup EVENTLOGHANDLE FILENAME
Backs up the specified event log to the file FILENAME. The file may be opened for reading using the eventlog_open command. EVENTLOGHANDLE must be a read handle.
eventlog_clear EVENTLOGHANDLE ?-backup FILENAME?
Clears the specified event log. If the -backup option is specified, the event log is first backed to the file FILENAME. EVENTLOGHANDLE must be a read handle (even though the command actually modifies the event log).
eventlog_close EVENTLOGHANDLE
Closes a handle previously returned by eventlog_open and frees any associated resources.
eventlog_count EVENTLOGHANDLE
Returns the number of records in the specified event log. EVENTLOGHANDLE must be a read handle.
eventlog_format_category EVENT_RECORD ?options?
Returns the text corresponding to the numeric category field in EVENT_RECORD by looking up the appropriate resources. EVENT_RECORD must be an element of the event record list returned from the eventlog_read command.

The following options may be specified with the command:

-langid LANGID | Passed to the format_message command for formatting. See the description of that function for details.
-width MAXLINEWIDTH | Passed to the format_message command for formatting. See the description of that function for details.

eventlog_format_message EVENT_RECORD ?options?
Returns the text corresponding to the message in EVENT_RECORD by looking up the appropriate resources. EVENT_RECORD must be an element of the event record list returned from the eventlog_read command.

The following options may be specified with the command:

-langid LANGID | Passed to the format_message command for formatting. See the description of that function for details.
-width MAXLINEWIDTH | Passed to the format_message command for formatting. See the description of that function for details.

eventlog_is_full EVENTLOGHANDLE
Returns 1 if the specified event log is full, and 0 otherwise. EVENTLOGHANDLE may be either a read or a write handle.
eventlog_log MESSAGE ?options?
Writes a record into the specified event log. This is a wrapper around eventlog_open, eventlog_write, eventlog_close for simple logging needs and should be used for applications that do not have a message file.

The following options may be specified to control the values of the various fields in the event log record:

-system SYSTEMNAME | Specifies the system on which the event log resides. By default, this is the local system.
-source SOURCENAME | Specifies a event log source. The returned handle will refer to the event log to which events from SOURCENAME are logged. This defaults to the filename portion (without the path or extension) of the executable file.
-type EVENTTYPE | Indicates the type or severity of the event. EVENTTYPE should be one of success, error, warning, information (default), auditsuccess or auditfailure.
-category CATEGORY | This should be a integer corresponding to a category id in the event source's category or message file. This value defaults to 0.

eventlog_monitor_start EVENTLOGHANDLE SCRIPT
Deprecated Registers SCRIPT to be invoked whenever the event log specified by EVENTLOGHANDLE receives a new event. EVENTLOGHANDLE must be a read handle to an event log on the local system. Windows will invoke SCRIPT only when new events are written to the event log but no more than once every 5 seconds. Note that EVENTLOGHANDLE must not be closed in order for the notifications to be sent.

The command returns an id for the notification. When the application is no longer interested in receiving notifications, it should release the associated resources by passing the id to eventlog_monitor_stop. This is required even if EVENTLOGHANDLE is closed.
eventlog_monitor_stop EVENTNOTIFICATIONID
Deprecated Stops notifications from the event log. EVENTNOTIFICATIONID is the id returned from a previous call to eventlog_monitor_start.
eventlog_oldest EVENTLOGHANDLE
Returns the record number of the oldest record in the specified event log. EVENTLOGHANDLE must be a read handle.
eventlog_open ?options?
Returns a handle to the specified event log. When no longer required, it should be closed by passing it to eventlog_close. Various options specify the event log to be opened and the read-write mode.

-file EVENTLOGBACKUPFILE | Specifies the name of a backed up event log file. This option may not be used with the -source or -system options.
-source SOURCENAME | Specifies a event log source. The returned handle will refer to the event log to which events from SOURCENAME are logged. This defaults to the filename portion (without the path or extension) of the executable file. This option may not be used with the -file option.
-system SYSTEMNAME | Specifies the system on which the event log resides. By default, this is the local system. This option cannot be used with the -file option.
-write | Returns a handle used for writing to the event log. By default, a read handle is returned. Note that event log handles are never read-write. Applications wishing to do both need to open two separate handles. This option may not be used with the -file option as event log backup files cannot be written to.

eventlog_read EVENTLOGHANDLE ?options?
Returns a list of event records read from the specified event log. EVENTLOGHANDLE must be a read handle. The number of records returned may vary depending on the number of records in the event log as well as internal buffering limits. Returns an empty list when no more records can be read. Each eventlog_read command moves the event log read pointer.

The following options may be specified to control the read operation:

-seek RECORDNUMBER | Normally the command returns event log records starting from current read pointer. If this option is specified, the command will return records starting with the one with record number RECORDNUMBER.
-direction backward|forward | Controls the direction in which the read pointer moves. By default, the commands will return records reading forwards from the current read pointer.
Each element in the returned list corresponds to an event log record and is a list of the form field value .... The following fields are returned in each event record:

-category | This is an integer corresponding to a category id in the event source's category or message file.
-data | Raw binary data stored as part of the event record.
-eventid | The event id that identifies the event type. See eventlog_write for how this may be used.
-params | A list of strings corresponding to the positional %N format specifiers in the format string for the event in the message file.
-sid | The SID of the user account of the thread that logged the event. This may be a null string if this information was not included in the record.
-recordnum | The record number for this record. This may be used with the -seek option to locate a record.
-source | The event source that logged the event.
-system | The name of the system on which the event was generated.
-timegenerated | Contains the time that the event was generated (UTC) expressed as an offset in seconds since 00:00:00 Jan 1, 1970. This can be passed to the clock format command to convert to an absolute time.
-timewritten | Contains the time (UTC) that the event was written into the event log expressed as an offset in seconds since 00:00:00 Jan 1, 1970. This can be passed to the clock format command to convert to an absolute time.
-type | Indicates the type or severity of the event. The value is one of success, error, warning, information, auditsuccess or auditfailure.

eventlog_subscribe EVENTSOURCE
Registers for notifications when events are logged to the specified event log. Returns a pair of two handles, the first is a handle that can be passed to eventlog_read to retrieve logged events. The second is a handle that is signalled when events are available to be read on the channel. It can be used in either synchronous or asynchronous mode with wait_on_handle.

When notifications are no longer desired, the two handles in the returned pair must be released via eventlog_close and close_handle respectively.

This command is internally identical to winlog_subscribe on Windows version before Vista. On Vista and later, this command translates to the older Windows event log API while winlog_subscribe will invoke the new Vista APIs.
eventlog_write EVENTLOGHANDLE EVENTID ?options?
Writes a record into the specified event log. EVENTLOGHANDLE must be a write handle for an event log. EVENTID is a integer that identifies the specific event. If the event source is configured in the registry, this is the message id for the event in the message file for the source. If no message file has been configured, this event id is irrelevant.

The following options may be specified to control the values of the various fields in the event log record:

-type EVENTTYPE | Indicates the type or severity of the event. EVENTTYPE should be one of success, error, warning, information (default), auditsuccess or auditfailure. Note that the last two may only be used when writing to the Security event log.
-category CATEGORY | This should be a integer corresponding to a category id in the event source's category or message file. This value defaults to 1.
-loguser | Specifying this will cause the SID of the user account for this thread to be included in the event record.
-params PARAMLIST | Specifies a list of strings corresponding to the positional %N format specifiers in the format string for the event in the message file. If the source has not been configured with a message file in the registry, event viewers will generally display this as a list of strings.
-data DATA | Raw binary data that should be stored as part of the event record.

evt_channels
Returns a list of names of the channels on the system.
evt_clear_log CHANNELNAME ?-backup BACKUPFILE?
Clears the specified event channel of all events. If -backup is specified, the events are written to the specified backup file before the channel is cleared.
evt_close ?EVTHANDLE EVTHANDLE...?
Close handles returned by various EVT commands such as evt_query or evt_next.
evt_decode_event HEVENT ?options?
Returns information about an event. HEVENT is a handle to an event such as an element of the list returned from evt_next.

The returned information is in the form of a dictionary. The keys in the dictionary are the same as the fields of the record array returned by evt_decode_events. See the documentation of that command for fields and options.

Besides the options for evt_decode_events, the following additional options may also be specified:

-hpublisher HPUBLISHER | A handle to the event publisher metadata. If not specified, the publisher metadata for the event is extracted from the event itself.
-values HVALUES | By default, the command will pick any values to be inserted into the formatted event string from the event itself. If this option is specified, the values will instead be picked from HVALUES which must be a handle to a render values block.

evt_decode_events HEVENTLIST
Returns a record array containing decoded events. HEVENTLIST is a list of handles to events as returned from evt_next.

The returned record array always contains the following system fields which are present in all events:

-activityid | GUID containing the activity id associated with the event.
-channel | The channel to which the event was logged.
-computer | The name of the system on which the event was logged.
-eventid | The event id for the event's definition.
-eventrecordid | The id of this event record.
-keywordmask | An integer mask with bits corresponding to the event's keywords.
-level | The numeric level for the event.
-opcode | The numeric opcode for the event.
-pid | The process id of the process that logged the event.
-providerguid | The GUID of the logging event provider.
-providername | The name of the logging event provider.
-qualifiers
-relatedactivityid | GUID containing the relative activity id associated with the event.
-task | The numeric task for the event.
-tid | The thread id of the logging thread.
-timecreated | The time the event was logged in 100ns units since January 1, 1601 UTC.
-sid | The SID of the account under which the logging thread was running.
-version | The version of the event definition.
In addition, the returned record array will include the following keys if they are specified as options to the command:

-keywords | Contains a list of keywords with which the event is tagged.
-levelname | Contains the string associated by the publisher with the numeric level.
-message | Contains the formatted message corresponding to the event.
-opcodename | Contains the string associated by the publisher with the numeric opcode field.
-taskname | Contains the string associated by the publisher with the numeric task field.
-xml | Contains an XML fragment describing the event.

The following additional options may also be specified with the command:

-ignorestring STRING | If specified, STRING is returned for any field that cannot be obtained. Without this option, errors retrieving fields will generate a Tcl exception.
-lcid LCID | Specifies the language in which the message is to be formatted. Defaults to the locale of the calling thread. This option is ignored if the -hpublisher option is specified.
-logfile PATH | Specifies the path to the logfile containing archived publisher metadata for the event. This option is ignored if the -hpublisher option is specified.
-session HSESSION | Specifies the session to the event logging subsystem for the event. By default the local event logging subsystem is used.

evt_export_log OUTFILE ?options?
Exports events, optionally matching a query, from a channel or a previously exported log file to a target log file.

The following options may be specified to select which events are included in the result set.

-channel CHANNELNAME | Specifies the event channel from which events are to be read. Cannot be used with the -file option.
-file PATH | Specifies the event file from which events are to be read. Cannot be used with the -channel option.
-ignorequeryerrors | Normally, if retrieving a specific event results in an error, Windows will fail the query and a Tcl exception will be raised. If -ignorequeryerrors is specified, such events are simply skipped and any further events are returned.
-query QUERYSTRING | Specifies the selection criteria for events that should be included in the returned result set. QUERYSTRING should be * (for all events, default), an XPATH expression or a structured XML query. See the Windows SDK for details.

evt_next HEVTRESULTSET ?options?
Returns a list containing events from a event query result set. HEVTRESULTSET is a handle to a result set as returned by evt_query. The returned list elements are event handles which can be passed to evt_decode_event. These event handles must be closed via evt_close.

The command returns an empty list if no more events are available. The behaviour of further calls depends on whether HEVTRESULTSET was returned from evt_query or evt_subscribe. In the former case, an empty list will continue to be returned even if additional events are logged to a channel. In the latter case, the command will return those events.

The cursor in the event result set is moved past the returned events so each evt_next returns events from the result set in sequence.

The following options can be specified:

-count COUNT | Returns COUNT events from the result set. The actual number of events returned may be less if the end of the result set is reached. If unspecified, the number of returned events depends on various internal tuning factors and applications must not rely on a specific number being returned.
-status VARNAME | The name of a variable in which to return status. If there is an error when reading the next event, the command will normally generate an Tcl exception. If this option is specified, the command will instead return an empty list and store the error code in the specified variable.
-timeout MILLISECONDS | Specifies the number of milliseconds to wait for events. A value of -1 (default) indicates call should not time out.

evt_publishers
Returns a list of names of the publishers registered on the system.
evt_query ?options?
Returns a handle to a result set containing events matching the specified criteria. Events from the result set are read using the evt_next command. Note that once the end of the result set returned by evt_query is reached, further events that are logged will not be returned.

After processing events, the handle must be closed using the evt_close command.

The following options may be specified to select which events are included in the result set.

-channel CHANNELNAME | Specifies the event channel from which events are to be read. Cannot be used with the -file option.
-direction DIRECTION | If DIRECTION is forward events are returned oldest first. If DIRECTION is backward, events are returned newest first.
-file PATH | Specifies the event file from which events are to be read. Cannot be used with the -channel option.
-ignorequeryerrors | Normally, if retrieving a specific event results in an error, Windows will fail the query and a Tcl exception will be raised. If -ignorequeryerrors is specified, such events are simply skipped and any further events are returned.
-query QUERYSTRING | Specifies the selection criteria for events that should be included in the returned result set. QUERYSTRING should be * (for all events, default), an XPATH expression or a structured XML query. See the Windows SDK for details.

evt_subscribe CHANNELPATH ?options?
Registers for notifications when events are logged to the event channel CHANNELPATH. Returns a pair of two handles, the first is a handle that can be passed to evt_next to retrieve logged events. The second is a handle that is signalled when events are available to be read on the channel. It can be used in either synchronous or asynchronous mode with wait_on_handle.

Note that Windows will not signal the handle unless a call to evt_next fails and a new event arrives. The mere presence of unread events is not sufficient.

When notifications are no longer desired, the two handles in the returned pair must be released via evt_close and close_handle respectively.

The following options may be specified:

-ignorequeryerrors | Normally, if retrieving a specific event results in an error, Windows will fail the query and a Tcl exception will be raised. If this option is specified, such events are simply skipped and any further events are returned.
-includeexisting | By default the command will only subscribe to new events. If this option is specified, notification is sent for existing events as well.
-query QUERYSTRING | Specifies the selection criteria for events that should be included in the returned result set. QUERYSTRING should be * (for all events, default), an XPATH expression or a structured XML query. See the Windows SDK for details.

winlog_backup NAME BACKUPFILE
Writes events from the specified event channel or source to a backup file. NAME is the name of an event log source (pre-Vista) or channel (Vista and later).
winlog_clear NAME ?-backup BACKUPFILE?
Clears the specified event channel or source of all events. NAME is the name of an event log source (pre-Vista) or channel (Vista and later).

If -backup is specified, the events are written to the specified backup file before the channel is cleared.
winlog_close WINLOGHANDLE
Closes the handle WINLOGHANDLE which must have been previously returned by winlog_open and frees any associated resources.
winlog_event_count ?options?
Returns the number of events in the specified event log using the API appropriate for the Windows version. The following options may be specified with the command.

-channel NAME | Specifies a event log source (pre-Vista) or channel (Vista and later) from which events are to be read. This option may not be used with the -file option.
-file EVENTLOGBACKUPFILE | Specifies the name of a backed up event log file. This option may not be used with the -channel or -system options.
-system SYSTEMNAME | Specifies the system on which the event log resides. By default, this is the local system. This option cannot be used with the -file option.

winlog_open ?options?
Returns a handle to the specified event log using the API appropriate for the Windows version. When no longer required, it should be closed by passing it to winlog_close. The following options may be specified with the command.

-channel NAME | Specifies a event log source (pre-Vista) or channel (Vista and later) from which events are to be read. This option may not be used with the -file option.
-direction DIRECTION | If DIRECTION is forward events are returned oldest first. If DIRECTION is backward, events are returned newest first.
-file EVENTLOGBACKUPFILE | Specifies the name of a backed up event log file. This option may not be used with the -channel or -system options.
-system SYSTEMNAME | Specifies the system on which the event log resides. By default, this is the local system. This option cannot be used with the -file option.

winlog_read WINLOGHANDLE ?-lcid LCID?
Returns a record array containing events read from the specified event log. The handle WINLOGHANDLE must have been previously returned by winlog_open. LCID is the identifies the language in which messages are to be formatted.

The number of events returned may vary. Returns an empty record array when no more records can be read. Each winlog_read command moves the event log read pointer.

The returned record array contains the following fields describing the event : -channel, -taskname, -message, -providername, -eventid, -level, -levelname, -eventrecordid, -computer, -sid and -timecreated. Refer to evt_decode_events for details.

The record array may also contain additional fields that should be ignored.
winlog_subscribe CHANNEL_OR_SOURCE
Registers for notifications when events are logged to the specified event source or channel. Returns a pair of two handles, the first is a event log handle that can be passed to winlog_read to retrieve logged events. The second is a handle that is signalled when events are available to be read on the channel. It can be used in either synchronous or asynchronous mode with wait_on_handle.

Note that Windows will not signal the handle unless a call to winlog_read fails and a new event arrives. The mere presence of unread events is not sufficient.

When notifications are no longer desired, call winlog_close passing in the event log handle which is the first element in the returned list. This will also release the signal handle which need not be closed explicitly.

COPYRIGHT

Copyright © 2004-2014, Ashok P. Nadkarni


Event Tracing - Event Tracing for Windows

Event Tracing

Commands for generating, reading and controlling Event Tracing for Windows

SYNOPSIS

package require twapi_etw

etw_disable_provider TRACEHANDLE PROVIDER
etw_enable_provider TRACEHANDLE PROVIDER ENABLEFLAGS LEVEL
etw_flush_trace TRACE ?options?
etw_get_provider_guid PROVIDERNAME
etw_get_providers ?-detail?
etw_get_traces ?-detail?
etw_query_trace TRACE
etw_start_kernel_trace EVENTCLASSES ?options?
etw_start_trace TRACENAME ?options?
etw_stop_trace TRACE
etw_update_trace TRACE ?options?
etw_command_tracker HPROVIDER OLDNAME NEWNAME OP
etw_execution_tracker HPROVIDER ARGS...
etw_install_twapi_mof
etw_log_message HPROVIDER MESSAGE ?LEVEL?
etw_twapi_provider_register
etw_twapi_eventclass_name
etw_twapi_eventclass_guid
etw_twapi_provider_guid
etw_twapi_provider_name
etw_variable_tracker HPROVIDER NAME1 NAME2 OP
etw_uninstall_twapi_mof
etw_unregister_provider PROVIDERHANDLE
etw_close_formatter FORMATTER
etw_dump_to_list LOGSOURCE ?LOGSOURCE ...?
etw_dump_to_file ?options? ?LOGSOURCE LOGSOURCE ...?
etw_close_session HTRACE
etw_format_event_message FORMATSTRING EVENTPROPERTIES
etw_format_events FORMATTER ?BUFDESC EVENTLIST...?
etw_open_file PATH
etw_open_formatter
etw_open_session SESSIONNAME
etw_process_events ?-callback CALLBACK? ?-start STARTTIME? ?-end ENDTIME? HTRACE ?HTRACE...?

DESCRIPTION

Windows includes a facility, Event Tracing for Windows (ETW), that allows the kernel and applications to log events that can either be written to a file or consumed in real time. This module provides access to this facility.

Overview

In ETW, events are written to an event trace by event providers under the control of event controllers which manage the mapping between the two. Event consumers read events from one or more such event traces for display to the user or any other purpose. TWAPI provides support for implementing all of the above.

There are two different technologies on which ETW is based. All modern (post-Windows XP up to Windows 7) versions of Windows support ETW based on Managed Object Format (MOF) event definitions. Windows Vista and later versions also implement a newer version of ETW based on XML manifests. TWAPI currently supports only MOF based event tracing.

Event trace

An event trace consists of a set of buffers, and optionally an associated file, to which events are written. The trace has other associated parameters such as the time stamping granularity, access control information and buffer limits. These are configured through event controllers.

Event controllers

An event controller manages event traces and their association with event providers. The following TWAPI commands can be used to implement an event controller:

  • To create a new event trace, use the command etw_start_trace which creates a new trace with configurable parameters.
  • To create and remove associations between event providers and traces, use the etw_enable_provider command. This command can also be used to communicate to the event providers what events are to be logged.
  • Use etw_query_trace and etw_update_trace to query and change the parameters of an existing trace.
  • To stop a trace, use the etw_stop_trace command. To flush the event trace buffers without terminating the trace, use etw_flush_trace command.
  • Use etw_get_traces to get a list of all current traces.

Note that the above commands can be used with any trace, not just those created using etw_start_trace. For example, traces created with the Windows logman or tracelog command can be controlled with the above command and vice versa.

Note that only processes running with elevated administrative privileges, or under accounts in the Performance Log Users group, and services running as LocalSystem, LocalService, NetworkService can start or control event traces.

Event providers

Event providers are components that write events to an event trace. Association with a specific trace is not under the control of the provider; that is a controller function. Of course, a single application may host both an event provider as well as an event controller. The list of providers on a system can be retrieved through the etw_get_providers command. The command etw_get_provider_guid can be used to map the provider name to its GUID.

Controllers send configuration information to providers in the form of enable flags and the enable level. The interpretation of these is entirely to the discretion of the event provider. Neither Windows, nor TWAPI, interpret these in any way. The TWAPI commands etw_provider_enable_flags and etw_provider_enable_level can be used to obtain the current values.

By convention, applications treat the enable flags as a bit mask that indicates the class(es) of events to log. For example, each bit might correspond to a specific subsystem. Note that a value of 0 does not mean the provider is disabled. It is up to the application as to how a value of 0 is interpreted. To determine whether a provider is actually enabled in the sense of being attached to an event trace, use the etw_trace_enabled command.

Similarly, the enable level is generally treated as a severity level, but again, this is not mandated.

Before any controller can add a provider to an event trace, the provider has to register itself. TWAPI includes a predefined provider that can be registered through the etw_twapi_provider_register call. Correspondingly, the command etw_unregister_provider unregisters the provider. Note that this must be done after the provider is detached from any event traces else Windows exhibits anomalous but harmless behaviour where the provider's calls to write events to the event trace still work but the provider is not notified of changes in the enable flags and level or when the trace is stopped.

Once the TWAPI provider is registered and attached to an event trace, events can be logged to the trace with the etw_log_message command.

Event consumers

ETW event consumers read events from event traces in real time or from a log file. An example of an event consumers is the command line program tracerpt which comes with Windows. The ETW interface allows a consumer to read events from multiple traces and merges them as needed.

TWAPI provides the high-level etw_dump and etw_dump_to_file commands which can read and format events.

For more control over the processing, call etw_open_file or etw_open_session to open each log file or real time event trace of interest. Then invoke the commands etw_process_events and etw_format_events to process the events.

event traces opened with etw_open_session should be closed with etw_close_session after processing.

Event definitions

Events written via ETW can have arbitrary binary formats. In order for consumers to be able to parse and extract data, they need to know the event definition. Providers use either Managed Object Format or XML manifests (Vista and later) to provide consumers with this information. When reading events, TWAPI will automatically look up event definitions as needed.

In order for event consumers to correctly parse events, TWAPI also has to make the MOF definitions for its ETW events available. This is done by calling the etw_install_twapi_mof command. This must be done on the system where the event consumer runs. It is not required on the system where the events are generated.

Tracing kernel events

There is a special event trace associated with the Windows kernel. The kernel logs events such as network events, process events, disk I/O etc. to this trace when enabled. This trace can be started and configured through the etw_start_kernel_trace command. The specific events to be logged are also specified as options to this command as the etw_enable_provider cannot be used with kernel traces.

See MSDN for the structure and description of the various events logged by the Windows kernel. The corresponding field names are returned by etw_format_events.

Tcl ETW traces

TWAPI includes commands etw_variable_tracker, etw_command_tracker and etw_execution_tracker that aid in logging Tcl variable, command and execution traces, respectively, to an ETW event trace.

set hprovider [etw_twapi_provider_register]
# Assume provider is added to event trace by some other means

# Add an execution trace to proc p
trace add execution p {enter leave enterstep leavestep} [list twapi::etw_execution_tracker $hprovider]

ETW Controller Commands

This section describes the commands that allow implementation of an ETW controller.

etw_disable_provider TRACEHANDLE PROVIDER
Disables the specified provider from logging to the event trace specified by TRACEHANDLE (as returned by etw_start_trace). PROVIDER can be the name or the GUID of the provider.
etw_enable_provider TRACEHANDLE PROVIDER ENABLEFLAGS LEVEL
Enables a provider to log to the event trace specified by TRACEHANDLE (as returned by etw_start_trace). PROVIDER can be the name or the GUID of the provider.

ENABLEFLAGS is an integer bitmask that indicates to the provider which classes of events are to be logged. The specific bits depend on the provider. Use the Windows command wevtutil gp PROVIDERNAME to list the event classes and the corresponding bitmask for a specific provider.

LEVEL is an integer between 0 and 255 that indicates the severity level at which events should be logged. The provider will log all events at LEVEL and below. Levels 1 through 5 can also be denoted as fatal, error, warning, informational and verbose respectively.
etw_flush_trace TRACE ?options?
Flushes the buffers belonging to an event trace. The trace TRACE may be specified either by its name or by its handle (as returned by etw_start_trace).
etw_get_provider_guid PROVIDERNAME
Returns the GUID of specified provider.
etw_get_providers ?-detail?
If -detail is not specified, returns a list containing the names of all providers registered on the system. If -detail is specified, returns a list each element of which is a dictionary with keys guid containing the GUID (same as the key), name containing the name of the provider and type which is one of mof or xml depending on whether the provider events are defined using WMI MOF or XML manifests.
etw_get_traces ?-detail?
If -detail is not specified, returns a list of the names of all traces currently running to which the calling process has access. If the -detail option is specified, returns a list each element of which is a dictionary in the same format as returned by etw_query_trace.
etw_query_trace TRACE
Returns a dictionary containing an event trace's settings and status. The trace TRACE may be specified either by its name or by its handle (as returned by etw_start_trace). The returned dictionary has the following keys (any additional keys should be ignored and not relied on being present):

buffer_size | Size of the buffers for the event trace.
buffers_written | Number of buffers flushed.
clock_resolution | One of qpc, system or cpucycle as described in etw_start_trace.
enable_flags | The provider enable mask for the event trace. This is valid only for kernel traces in which case it contains the enable mask for the kernel components.
events_lost | Number of events lost in the event trace that were not recorded.
flush_timer | Number of seconds after which buffers are automatically flushed.
free_buffers | Number of free buffers in the event trace.
log_buffers_lost | Number of buffers lost without being consumed.
logfile | The log file associated with the event trace.
logfile_mode | Bit flags indicating logging mode for the event trace.
logger_tid | Thread id of thread doing the logging for the event trace.
max_buffers | Maximum number of buffers that can be allocated for the event trace.
max_file_size | Maximum size specified for the file in megabytes.
min_buffers | Minimum number of buffers that can be allocated for the event trace.
buffer_count | Number of buffers in use.
real_time_buffers_lost | Number of buffers used for real time tracing that could not be written to the log file.
trace_guid | The GUID associated with the event trace.
trace_name | The name of the event trace.

etw_start_kernel_trace EVENTCLASSES ?options?
Starts an event trace with the Windows kernel provider. Returns a pair consisting of a event trace handle and a dictionary containing the event trace properties. Windows only supports one such event trace so an error is generated if another application already has a kernel trace open. In addition, the process must be running under an account with administrative privileges or as a service running as LocalSystem.

EVENTCLASSES specifies the kernel events that are to be captured and should be a list containing elements from the table below. Note that the captured events may include other events that are not included in EVENTCLASSES.

alpc | Advanced local procedure calls (Vista and later)
contextswitch | Thread context switches (Vista and later)
dbgprint | Kernel DbgPrint calls
diskfileio | File I/O
diskio | Disk I/O
dispatcher | Thread transitions to ready state (Windows 7 and later)
dpc | Device deferred procedure calls (Vista and later)
driver | Device driver requests (Vista and later)
hardfault | Hard page faults
imageload | Image loading
interrupt | Interrupt service routines (Vista and later)
pagefault | Page faults
process | Processes events
processcounter | Process counters (Vista and later)
profile | Processor profiling samples (Vista and later)
registry | Registry access
splitio | Split I/O events (Vista and later)
sysconfig | Includes events describing system configuration. These are collected when the trace is stopped.
systemcall | System calls (Vista and later)
tcpip | TCP and UDP events
thread | Thread events
vamap | Virtual address map and unmap events (Windows 8/Windows Server 2012 and later)
virtualalloc | Virtual memory allocation (Windows 7/Windows Server 2008 R2 and later)
See etw_start_trace for a description of the options that may be specified. However, note rotate is not a valid value for -filemode for kernel traces and the -usepagedmemory option must not be specified.

etw_start_trace TRACENAME ?options?
Starts a new ETW trace with the name TRACENAME and returns a handle to it.

The following options may be specified:

-buffersize BUFFERSIZE | Specifies the size in kilobytes of the buffers used in the event trace. This is only an requested size and will be adjusted by ETW.
-clockresolution RESOLUTION | The clock resolution to use when timestamping events in the event trace. Specify RESOLUTION as qpc to use the query performance counter. This is the highest resolution but is relatively expensive. Specify system to use system time. This is lower resolution but is cheaper in run time cost and is the default. Specify cpucycle to use the CPU cycle counter. This has the highest resolution and is the cheapest to obtain. However it can be very inaccurate as it is affected by power and temperature management features of the CPU.
-flushtimer SECONDS | Normally, ETW buffers are flushed as they become full. Use this option to force flushing of buffers every SECONDS seconds even when they are not full. However note that ETW flushes entire buffers to log files so flushing half empty buffers can greatly increase the log file size. Generally, use this option only for real time event traces.
-filemode FILEMODE Specifies the file logging mode. FILEMODE must be one of the following values:

append | Events are written sequentially to a log file. Unlike sequential mode, existing log files are appended to instead of being overwritten. The -clockresolution option must be system and options -realtime, -private or -privateinproc must be false. Moreover, various configuration parameters like buffer size must be the same as those of the existing log file.
circular | This is the default mode. Events are written to the log file in circular fashion with newer events overwriting older events once the maximum file size is reached. If option -maxfilesize is not specified, it is defaulted to 1MB.
rotate | Sequentially writes to the log file and automatically creates a new file when the maximum file size is reached. The path specified with the -logfile option must contain the string %d which is replaced with a incremented counter every time a new file is created. If option -maxfilesize is not specified, it is defaulted to 1MB. On Windows versions prior to Windows 7 and Windows 2008 R2, the -private and -privateinproc options are not compatible with this mode.
sequential | Writes events sequentially to a log file. Existing log files are overwritten. If option -maxfilesize is specified, logging stops when the maximum size is reached. Otherwise, the file will grow as needed except for some system defined limits if it resides on the system drive.

-logfile FILEPATH | The name of the log file in which to write events. This option need not be specified if the event trace is only a real time trace. FILEPATH may be relative or absolute but should have the .etl extension. Depending on the other options specified, the actual file name may be modified.
-maxbuffers MINBUFS | Specifies the minimum number of buffers to allocate.
-minbuffers MAXBUFS | Specifies the maximum number of buffers to allocate.
-maxfilesize MAXMB | The maximum size of the log file in megabytes.
-paged BOOLEAN | If true, paged memory is used for the event trace buffers. If false (default), non-paged memory is used. Kernel-mode providers cannot log to paged buffers. If these are not used in the trace, it is recommended to set this option to true as non-paged memory is a limited resource.
-preallocate BOOLEAN | If true, any required file space is preallocated. Default is false.
-private BOOLEAN | If true, creates a private event trace to which only threads within the provider's process can log events. There can be only one private event trace per process. On Windows Vista and later, only processes running as LocalSystem and elevated processes can create private event traces. On earlier versions of Windows, processes in the Performance Log Users group could also create private traces. When multiple processes register the provider, any log files created are appended with the PID of the process except for the one created by the first process. This option cannot be used with -realtime. On Windows versions prior to Windows 7, this option cannot be used if -filemode is specified as rotate.
-privateinproc BOOLEAN | If true, creates an in-process event trace and enforces that only the process that registered a provider guid can start a trace with that guid. Unlike the -private option, processes need not be running in privileges accounts and up to three traces can be created. Default is false. Requires Vista or later.
-realtime BOOLEAN | If true, events are delivered to any subscribed consumers in real time when event buffers are flushed. Certain guidelines have to be followed when real time mode is requested. Please refer to Windows SDK ETW documentation. This option cannot be used with -private and -privateinproc. Default is false.
-secure BOOLEAN | If true, logging to the event trace requires the TRACELOG_LOG_EVENT permission. Default is false.Requires Vista or later.
-sequence SEQUENCETYPE | Events logged with the TraceMessage Windows API can contain a sequence number. If SEQUENCETYPE is none (default), no sequence number is added to the event. If SEQUENCETYPE is global, the added sequence number is global across multiple event traces and if local, it is unique to a trace.
-traceguid GUID | The GUID to assign to the event trace. If not specified, Windows will internally generate the GUID for the trace. The primary purpose for specifying this is to allow for setting access control on the trace.
For more details on the options, refer to the Windows SDK ETW documentation.

etw_stop_trace TRACE
Stops an event trace. The trace TRACE may be specified either by its name or by its handle (as returned by etw_start_trace).

The command returns a dictionary containing the stopped trace's status in the same format as etw_query_trace.
etw_update_trace TRACE ?options?
Updates the attributes associated with an event trace. If the trace is inactive (e.g. from a log files without an associated active trace), the command has no effect. The trace TRACE may be specified either by its name or by its handle (as returned by etw_start_trace). The command returns a dictionary containing a trace's settings and status in the same format as etw_query_trace. The following event trace attributes may be updated:

-enableflags FLAGS | Changes the enable flags for the event trace. Only applies if the trace is a "NT Kernel Logger" trace.
-flushtimer TIMERVAL | If non-0, changes the number of seconds after which buffers are automatically flushed.
-logfile FILEPATH | If specified, changes the log file associated with the trace.
-maxbuffers COUNT | If non-0, changes the maximum number of buffers that can be allocated for the trace.
-realtime BOOLEAN | If true, turns on realtime mode, else turns it off. Note if the command is called to update other options, and this option is not specified, it results in the real time mode being turned off.

ETW Provider Commands

This section describes the commands that allow implementation of an ETW provider.

etw_command_tracker HPROVIDER OLDNAME NEWNAME OP
Writes a CommandTrace event to the event trace associated with the provider handle HPROVIDER returned by etw_twapi_provider_register. The remaining arguments correspond to those passed to the callback function by Tcl's trace add command command. etw_command_tracker can be used as the callback similar to the example in Tcl ETW traces.
etw_execution_tracker HPROVIDER ARGS...
Writes a ExecutionTrace event to the event trace associated with the provider handle HPROVIDER returned by etw_twapi_provider_register. The remaining arguments correspond to those passed to the callback function by Tcl's trace add execution command. etw_execution_tracker can be used as the callback similar to the example in Tcl ETW traces.
etw_install_twapi_mof
Installs the TWAPI Managed Object Format (MOF) definition for the event trace formats used by TWAPI. This command needs to be called on the system where a ETW consumer will be parsing TWAPI logged events. The definition can be removed by calling etw_uninstall_twapi_mof.
etw_log_message HPROVIDER MESSAGE ?LEVEL?
Writes an event containing the MESSAGE string to the event trace attached to the provider handle HPROVIDER returned by etw_twapi_provider_register. LEVEL indicates the severity level at which the message is to be logged. LEVEL must be an integer or one of the following constants verbose (5), informational (4), warning (3), error (2) or fatal (1). By default, the message is logged at level 4 (informational).
etw_twapi_provider_register
Registers the TWAPI ETW provider so that it can be added to an event trace. The name and GUID corresponding to the provider can be retrieved through etw_twapi_provider_name and etw_twapi_provider_guid. These can then be passed to etw_enable_provider or any ETW controller program to add the TWAPI provider to a trace. Returns a handle to the registered provider.

The provider can be unregistered by calling the etw_unregister_provider command.
etw_twapi_eventclass_name
Returns the human readable name of the ETW event class used by etw_log_message.
etw_twapi_eventclass_guid
Returns the GUID of the ETW event class used by etw_log_message.
etw_twapi_provider_guid
Returns the GUID for the TWAPI ETW provider. This can be passed to etw_enable_provider or any ETW controller program to add the TWAPI provider to an event trace.
etw_twapi_provider_name
Returns the TWAPI ETW provider name.
etw_variable_tracker HPROVIDER NAME1 NAME2 OP
Writes a VariableTrace event to the event trace associated with the provider handle HPROVIDER returned by etw_twapi_provider_register. The remaining arguments correspond to those passed to the callback function by Tcl's trace add variable command and this command can be used as the callback as in the example in Tcl ETW traces.
etw_uninstall_twapi_mof
Uninstalls the TWAPI Managed Object Format (MOF) definition for the event trace formats used by TWAPI.
etw_unregister_provider PROVIDERHANDLE
Unregisters a previously registered provider. PROVIDERHANDLE is a handle returned by a previous call to etw_twapi_provider_register command.

ETW Consumer Commands

This section describes the commands that deal with consuming events from ETW.

etw_close_formatter FORMATTER
Closes and releases resources associated with a ETW formatter handle returned by a previous call to etw_open_formatter.
etw_dump_to_list LOGSOURCE ?LOGSOURCE ...?
Extracts events from one or more ETW log files or real time trace, returning them as a record array. Each LOGSOURCE argument must be the path to a ETW log file or the name of a ETW real time trace. At most one real time trace can be specified.
etw_dump_to_file ?options? ?LOGSOURCE LOGSOURCE ...?
Extracts events from one or more ETW log files or real time trace and writes them out in human readable form. Each LOGSOURCE argument must be the path to a ETW log file or the name of a ETW real time trace. At most one real time trace can be specified.

The command takes the following options:

-format FORMAT | Specifies the output format. FORMAT must be list or csv. The CSV format requires that the Tcl package csv be available.
-limit LIMIT | Stops after LIMIT events are written.
-output OUTPUT | Specifies where to write the events. OUTPUT may be a channel or a file path. If the latter, the file must not exist. The default is standard output.
-separator SEPARATOR | Specifies the separator character to use. Only used for CSV format. Defaults to the comma character.
Each record written consists of a fixed number of fields followed by event-specific data. The fixed fields include the time stamp, the thread id, the process id, the event's MOF class and the event name. The remaining fields are varying in number and consist of alternating pairs of the field name from the event's MOF definition and the corresponding value. If the MOF definition is not available, the field name is MofData and the corresponding value is a hexadecimal representation of the binary data.

etw_close_session HTRACE
Closes an event trace previously opened by a call to etw_open_file or etw_open_session.
etw_format_event_message FORMATSTRING EVENTPROPERTIES
Returns the message string constructed from FORMATSTRING by replacing the insert placeholders with the corresponding values from EVENTPROPERTIES. Normally, FORMATSTRING and EVENTPROPERTIES come from the message and properties fields returned by the etw_event command.
etw_format_events FORMATTER ?BUFDESC EVENTLIST...?
Processes the list of raw ETW events and returns a record array of formatted events. BUFDESC and EVENTLIST are the event buffer descriptor and the list of raw events for the event buffer as returned by etw_process_events or as passed to the -callback option of that command.

FORMATTER should be the handle to a formatter as returned by etw_open_formatter.

The command returns a recordarray with the fields in the table below. The recordarray commands can be used to access or transform the returned events. The value of a field may be the empty string if the logging application did not set it or if the field is not supported by the provider type.

-channel | The numeric identifier for the event log channel to which the event was logged.
-channelname | The name of the event log channel to which the event was logged.
-eventguid | The GUID identifying the event. For manifest based events, this is empty.
-eventid | The event identifier.
-kerneltime | The elapsed execution time for kernel-mode instructions in 100ns units. If the event was logged from a private trace, this will be 0 as all time will be counted towards -usertime.
-keywordmask | A bit mask corresponding to the keywords associated with the event.
-keywords | The list of keywords associated with the event.
-level | The numeric level at which the event was logged. Higher numeric levels are lower priority events.
-levelname | The name of the logging level at which the event was logged. Since this is localized, -level should be used for comparing event logging levels.
-message | The message associated with the event. This may contain string inserts for event parameters. Use the etw_format_event_message to retrieve the fully constructed message.
-opcode | The numeric opcode for the event, generally identifying one step in a sequence of operations.
-opcodename | The string name for the numeric opcode. For MOF based events, this is the event type.
-pid | The process identifier of the process that logged the event. This will be -1 if the event was not associated with any process.
-properties | A dictionary containing additional event parameters. The keys of the dictionary are dependent on the specific event type.
-providerguid | The GUID identifying the provider.
-providername | The name of the provider. For classical MOF based provider, this is the name of the MOF class.
-sid | The SID of the logging process or an empty string if not available.
-task | The numeric task identifying the general area within the application.
-taskname | The string name associated with task.
-tid | The thread identifier of the process that logged the event. This will be -1 if the event was not associated with any thread.
-timecreated | The time that the event was logged in system time format. Use large_system_time_to_secs_since_1970 to convert this to Tcl clock format.
-usertime | The elapsed execution time for user-mode instructions in 100ns units.
-version | The version of the event. Together with id, this identifies a specific event within a provider.

etw_open_file PATH
Opens a log file containing ETW events and returns a trace handle to it which can be passed to etw_process_events. The handle must be closed later by passing it to etw_close_session.
etw_open_formatter
Returns a handle to a ETW event formatter that can be passed to etw_format_events for formatting events. When no longer needed, the returned handle must be passed to etw_close_formatter so that associated resources may be released.
etw_open_session SESSIONNAME
Opens a real time ETW trace and returns a session handle to it which can be passed to etw_process_events. The handle must be closed later by passing it to etw_close_session.
etw_process_events ?-callback CALLBACK? ?-start STARTTIME? ?-end ENDTIME? HTRACE ?HTRACE...?
Processes events recorded in one or more event traces. The handles HTRACE are handles returned by etw_open_file or etw_open_session.

If -callback is not specified, the command returns a list consisting of alternative buffer descriptors and a raw event list. Each pair should be passed to etw_format_events which will in turn return a list of formatted events. If -callback is specified, the events are passed to the CALLBACK command prefix.

When ETW begins processing events, the callback is invoked repeatedly until there are no more unread events in the trace. On each invocation, two additional arguments are appended to the callback command prefix - the event buffer descriptor, and a list of raw event records. The callback should pass both these arguments to etw_format_events which in turn will return a record array of formatted events.

To terminate processing of events before all events from the traces are consumed, the callback can execute

return -code break

The options -start and -end can be specified to limit the time interval for which events are processed. Both STARTTIME and ENDTIME must be specified in the same format as get_system_time. You can use secs_since_1970_to_large_system_time to convert the format used by Tcl's clock command to this format.

COPYRIGHT

Copyright © 2012 Ashok P. Nadkarni


Application utilities - Application utilities

Application utilities

Commands for various Windows application utilities

SYNOPSIS

package require twapi_apputil

delete_inifile_key SECTION KEY ?-inifile FILENAME?
delete_inifile_section SECTION ?-inifile FILENAME?
get_command_line
get_command_line_args COMMANDLINE
read_inifile_key SECTION KEY ?options?
read_inifile_section SECTION ?-inifile FILENAME?
read_inifile_section_names ?-inifile FILENAME?
write_inifile_key SECTION KEY VALUE ?-inifile FILENAME?

DESCRIPTION

This module provides commands commonly required in Windows applications.

Application command line

get_command_line retrieves the command line passed to the process. get_command_line_args parses a command line using Windows conventions. The difference over Tcl's built-in ::argv variables is that these commands handle Unicode command lines and use Windows conventions for argument parsing.

INI files

The commands read_inifile_key, write_inifile_key and delete_inifile_key can be used for manipulating individual entries.

The commands read_inifile_section_names, read_inifile_section and delete_inifile_section may be used for manipulating entire sections of INI files.

Note these commands take into account INI file mappings set up in the HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\IniFileMapping registry key.

A cross-platform package that provides similar functionality is available in the available in the tcllib standard library. However, that does not take into account the registry mappings on Windows platforms.

Commands

delete_inifile_key SECTION KEY ?-inifile FILENAME?
Deletes the key KEY from the INI file section SECTION. By default, the command writes to the win.ini file in the system directory. The -inifile option may be used to specify different INI file.
delete_inifile_section SECTION ?-inifile FILENAME?
Deletes the entire section SECTION from an INI file. By default, the command writes to the win.ini file in the system directory. The -inifile option may be used to specify a different INI file.
get_command_line
Returns the command line of the current process. This may be passed to the get_command_line_args function to split the line into arguments.
get_command_line_args COMMANDLINE
Parses COMMANDLINE as per Windows command line conventions and returns a list of the parsed arguments. The main advantage of this over using the argv and argv0 variables in tclsh and wish is that this call will correctly handle Unicode arguments.
read_inifile_key SECTION KEY ?options?
Returns the value of the key KEY in the INI file section SECTION. If the key is not found, an empty string is returned unless the -default option is specified. The following options may be specified:

-default DEFAULTVALUE | If the key is not found in the section, the command returns DEFAULTVALUE instead of an empty string.
-inifile FILENAME | By default, the command looks up the win.ini file in the system directory. This option may be used to look up a different INI file instead.

read_inifile_section SECTION ?-inifile FILENAME?
Returns all the entries in section SECTION of an INI file as a list of key value pairs. By default, the command reads the win.ini file in the system directory. The -inifile option may be used to specify a different INI file.
read_inifile_section_names ?-inifile FILENAME?
Returns the names of all sections in an INI file. By default, the command reads the win.ini file in the system directory. The -inifile option may be used to specify a different INI file.
write_inifile_key SECTION KEY VALUE ?-inifile FILENAME?
Writes VALUE as the value of the key KEY in the INI file section SECTION. The section and key are created if they did not already exist. By default, the command writes to the win.ini file in the system directory. The -inifile option may be used to look up a different INI file instead.

COPYRIGHT

Copyright © 2004-2012, Ashok P. Nadkarni


CryptoAPI - Cryptographic and Certificate API

CryptoAPI

Commands related to cryptographical operations

SYNOPSIS

package require twapi_crypto

cert_blob_to_name ENCODEDBLOB ?options?
cert_create SUBJECT PUBKEY ISSUERCERT ?options?
cert_create_self_signed SUBJECT ?options?
cert_create_self_signed_from_crypt_context SUBJECT HCRYPT ?options?
cert_duplicate HCERT
cert_enhkey_usage HCERT ?SOURCE?
cert_enum_properties HCERT ?-names?
cert_export HCERT ?-encoding ENCODING?
cert_extension HCERT EXTENSION
cert_file_store_open PATH ?options?
cert_import ENCODEDCERT ?-encoding encoding?
cert_info HCERT
cert_issuer_name HCERT ?options?
cert_key_usage HCERT
cert_locate_private_key HCERT ?options?
cert_name_to_blob NAME ?options?
cert_physical_store_open NAME LOCATION ?options?
cert_physical_store_delete NAME LOCATION
cert_property HCERT PROPERTY
cert_property_delete HCERT PROPERTY
cert_property_set HCERT PROPERTY PROPVAL
cert_release HCERT
cert_request_create SUBJECT HCRYPT KEYSPEC ?options?
cert_request_parse CSR ?-encoding ENCODING?
cert_set_key_prov HCERT ?options?
cert_store_add_certificate HSTORE HCERT ?-disposition DISPOSITION?
cert_store_add_encoded_certificate HSTORE ENCODEDCERT ?options?
cert_store_commit HSTORE ?-force BOOLEAN?
cert_delete_from_store HCERT
cert_store_enum_contents HSTORE ?HCERT?
cert_store_export_pfx HSTORE PASSWORD ?options?
cert_store_export_pkcs12 HSTORE PASSWORD ?options?
cert_store_export_pkcs7 HSTORE ?-encoding ENCODING?
cert_store_find_certificate HSTORE ?SEARCHTYPE? ?SEARCHTERM? ?HCERT?
cert_store_release HSTORE
cert_store_serialize HSTORE
cert_subject_name HCERT ?options?
cert_system_store_open NAME ?LOCATION? ?options?
cert_system_store_delete NAME LOCATION
cert_system_store_locations LOCATION
cert_system_stores LOCATION
cert_temporary_store ?options?
cert_thumbprint HCERT
cert_tls_verify HCERT ?options?
crypt_acquire KEYCONTAINER ?options?
crypt_csp HCRYPT
crypt_csps
crypt_csptype HCRYPT
crypt_csptypes
crypt_free HCRYPT
crypt_get_security_descriptor HCRYPT
crypt_key_container_delete KEYCONTAINER ?options?
crypt_key_container_name HCRYPT
crypt_key_container_names HCRYPT
crypt_key_free HCRYPTKEY
crypt_key_generate HCRYPT ALGORITHM ?options?
crypt_keypair HCRYPT keytype
crypt_keyset_type HCRYPT
crypt_set_security_descriptor HCRYPT ?SECD?
crypt_session_key_size HCRYPT
crypt_symmetric_key_size HCRYPT
protect_data BINDATA ?options?
unprotect_data BINDATA ?options?

DESCRIPTION

This module is still experimental and liable to change.

This package provides procedures related to cryptographic services provided by the Windows platforms.

Overview

This page describes the commands related to the Win32 CryptoAPI which includes functions related to encryption, decryption, signatures and ancillary services for certificate and key management.

The Win32 CryptoAPI includes the Security Support Provider Interface (SSPI) related to secure communication protocols. Those commands are documented separately on the SSPI page.

This documentation expects the reader is familiar with the use of cryptography. An overview of the concepts in the CryptoAPI is provided but the API itself is fairly complex and the reader may wish to refer to the Windows SDK CryptoAPI documentation for detailed guides and reference documentation.

Cryptographic Service Providers

A Cryptographic Service Providers (CSP) on Windows is a software module that implements a set of cryptographical functions such as encryption or key storage. There may be multiple such modules on a system, each implementing one of more cryptographic algorithms for one or more cryptographic functions. Applications implement cryptographic operations by calling a standard interface defined by Windows and implemented by the CSPs.

Some CSP's come with the Windows operating system while others are implemented by third parties. The feature set implemented by each CSP is different and can depend on factors such as the operating system version, and because of US export restrictions, the country. Based on the supported features, CSP's have an associated CSP type. For example, a CSP of type PROV_RSA_FULL supports digital signatures and encryption using the RSA public key algorithm. On the other hand, a CSP of type PROV_DSS uses the DSA algorithm and only supports hashes and signatures. When creating a Cryptographic contexts, an application needs to specify a CSP type that supports the desired operations. The following types are recognized: prov_rsa_full, prov_rsa_sig, prov_dss, prov_fortezza, prov_ms_exchange, prov_ssl, prov_rsa_schannel, prov_dss_dh, prov_ec_ecdsa_sig, prov_ec_ecnra_sig, prov_ec_ecdsa_full, prov_ec_ecnra_full, prov_dh_schannel, prov_spyrus_lynks, prov_rng, prov_intel_sec, prov_replace_owf, prov_rsa_aes. Refer to the Windows SDK for details about the features provided by each. For most applications, the default prov_rsa_full is sufficient.

Two standard providers shipped as part of Windows are Microsoft Base Cryptographic Provider and the Microsoft Strong Cryptographic Provider. On most systems, the latter is the default when no specific CSP is selected and is sufficient in most cases unless some special functionality like hardware based cryptography is desired.

The commands crypt_csps and crypt_csptypes return the list of CSP's and CSP types on the system.

Keys and key containers

The keys used for cryptographic operations are stored in key containers within a CSP's control. The keys are not generally exposed directly to an application but rather the CSP carries out the operations using the keys on the application's behalf.

A CSP may be associated with multiple key containers, each identified by a name. The specific key container and the keys within that container that are used for an operation depends on the Cryptographic contexts is bound at the time the context is created via the crypt_acquire command. This command also allows creation of new key containers within a CSP if they do not exist.

Depending on the options specified and the account under which they are created, key containers are created with restricted access. The exact access depends on the account group membership (e.g. whether an adminitrator or not) and operating system version. Applications can set specific access rules by setting a DACL on the container using crypt_set_security_descriptor.

To delete key containers, use the crypt_key_container_delete command.

Depending on the CSP chosen, key containers may be empty when created. The command crypt_key_generate adds keys to the container. The algorithm with which the key will be used and the purpose (encryption, signing etc.) can be specified so the appropriate type of key is generated. The container may contain multiple keys and appropriate key must be chosen when cryptographic operations are invoked.

A key container may be created as a user key set or a computer key set. These are distinguished based on where they are stored and who has access to them. Refer to the Windows SDK CryptoAPI documentation for details. It is possible to change the default access permissions for a key container. The crypt_get_security_descriptor and crypt_set_security_descriptor commands can be used retrieve and change the security descriptor for a key container.

Cryptographic contexts

In order to perform cryptographic operations, an application must choose a CSP, the algorithms to use and their parameters including keys. The command crypt_acquire takes these are parameters and returns a handle to a cryptographic context that binds the desired combination together. This handle can then be used in further cryptographic operation.

Once a context is created, the various parameters associated with it can be retrieved.

  • crypt_csp returns the name of the owning CSP.
  • crypt_csptype returns the type of the CSP.
  • crypt_key_container_name returns the name of key container currently associated with the context.
  • crypt_key_container_names returns the names of the other key containers owned by the CSP.
  • crypt_keypair returns a handle to one of the key pairs in the container.
  • crypt_keyset_type returns whether the key set in the container is per-user or per-machine. crypt_session_key_size and crypt_symmetric_key_size return the size of the keys in the container.
When no longer needed, cryptographic contexts must be freed with the crypt_free command.

Certificate stores

The CryptoAPI interface provides functions for handling and storage of X.509 digital certificates. A certificate store is a container for certificates. The container may be a physical store, for example on disk, or a logical store which is a collection of physical stores presented to the application as a single store. Certificate stores may also be created as in-memory temporary stores which are not persisted.

Certain certificate stores, called system stores are predefined by Windows. These include the stores MY, ROOT, Trust and CA. Most applications should store certificates in either the MY store, or in their own custom store.

Note that the system stores are relative to a system store location which must be specified when opening the store. To enumerate the locations of the system stores, use cert_system_store_locations. Optionally, the following predefined values may be used to specify a system store location:

user | Certificates associated with the current user account.
users | Certificates shared among all user accounts on the system.
service | Certificates associated with the current service account.
services | Certificates shared among all services on the system.
localmachine | Certificates associated with the system.
localmachineenterprise | Certificates downloaded from the global enterprise directory.
localmachinegrouppolicy | Certificates associated with the group policy for the system.
usergrouppolicy | Certificates associated with the group policy for the current user.
To enumerate system stores at a location, use the cert_system_stores.

Most certificate store operations require the store to be first opened or created. Persistent stores are opened or created using the one of the commands cert_system_store_open, cert_physical_store_open or cert_file_store_open as appropriate. Non-persistent stores are created using cert_temporary_store which includes various options for populating the store, for example with the contents of PFX/PKCS #12 or PKCS #7 packets.

The handle returned from these commands must be passed to any commands that operate on stores and released by calling cert_store_release when no longer required.

The returned handle from these commands refers to a cached copy of the store. Any changes made via this handle are made to the cached copy and must be explicitly saved if they need to persist. This can be done either via the -commitenable option when the store is opened, or by calling cert_store_commit.

Commands cert_store_export_pfx, cert_store_export_pkcs12, cert_store_export_pkcs7, and cert_store_serialize can be used to export certificate stores in various formats.

Existing certificate stores can be deleted using the commands cert_system_store_delete, cert_physical_store_delete and cert_file_store_delete. A in-memory certificate store is deleted when its handle is closed.

Certificate properties

When a certificate is placed in a store, it is associated with additional properties that are not part of the certificate itself, for example a private key associated with the certificate. These properties can be enumerated with cert_enum_properties and manipulated with the cert_property, cert_property_set and cert_property_delete commands.

Certificate contexts

Operating on a certificate requires a certificate context which encapsulates all information about the certificate. Most often, the certificate of interest is an existing certificate that is located in a certificate store. The commands for finding certificates in a store return a handle to a suitable certificate context. Similarly, commands that create new certificates or add certificates to a store return handles to certificate contexts as well.

When no longer needed, certificate contexts must be freed by calling cert_release.

Getting certificate contents

The cert_info command returns the fields in a certificate context. The cert_extension command retrieves specific extensions. Two extensions, Intended Key Usage and Enhanced Key Usage, can be also be retrieved with the cert_key_usage and cert_enhkey_usage command. These look up certificate context properties in addition to multiple related extensions in the certificate itself.

The encoded certificate associated with a certificate context can be retrieved with the cert_export command. This can be written to a file or otherwise distributed.

set fd [open MyCert.cer w]
chan configure $fd -translation binary
puts -nonewline $fd [cert_export $hcert]
close $fd

The cert_locate_private_key command locates the private key corresponding to the public key in a certificate.

Finding a certificate in a store

An existing certificate in a store can be retrieved in one of two ways:

  • Enumerate each certificate in the store using cert_store_enum_contents and looking for a match using cert_subject_name or cert_property.
  • Searching for a match on the subject name using cert_store_find_certificate.
Both these commands return a handle to a certificate context that can be used for further operations on the certificate.

Creating a new certificate

New certificates can be created by commands such as cert_create_self_signed, cert_create_signed_from_crypt_context and cert_create. These return handles to certificate contexts that are not associated with any store. The certificates must be explicitly placed in a certificate store if desired.

Creating a new certificate involves several steps. As always, first a cryptographic context is needed that defines the algorithms, keys etc. that will be used to create the certificate.

set crypt [crypt_acquire twapi_test_container -csp {Microsoft Strong Cryptographic Provider} -csptype prov_rsa_full -create 1]

This assumes a key container called twapi_test_container does not exist. All the options specified above happen to be the defaults if unspecified.

The key container is created without any keys so we need to generate public/private key pairs. As we will use the certificate for both signing and key exchange, we generate two key pairs for the container.

crypt_key_free [crypt_key_generate $crypt signature -exportable 1]
crypt_key_free [crypt_key_generate $crypt keyexchange -exportable 1]

Note we immediately release the key handles as they are not needed. This does not destroy the underlying keys. Also, because we want to write the certificate out to a file with the private keys, we mark the keys exportable.

Next, we create a self signed certificate from the cryptographic context we created. This will use the keys we just added.

set cert [cert_create_self_signed_from_crypt_context "CN=TwapiTestCA" $crypt]

We now have a certificate context for a new self signed certificate. In most cases, we will want to either store it in a certificate store for future use or export it to a file. This is illustrated in succeeding sections of this document.

The cryptographic context is not needed any more and can be released.

crypt_free $crypt

Certificates that are not self-signed are created through cert_create. The private key for the signing certificate must be accessible to the application. The data for the new certificate, such as the subject name, the certificate public key, extensions etc. may be provided by the application itself but more often come from a certificate signing request which is generated elsewhere, possibly even on a different system. The command cert_request_parse can be used to parse such a request and the extracted fields passed to cert_create. The request itself can be created by cert_request_create.

On the requester's side, assuming the key container for the requestor has been already created as in the example above,

set crypt [crypt_acquire twapi_requestor_container -csp {Microsoft Strong Cryptographic Provider} -csptype prov_rsa_full]
set req [cert_request_create "CN=My Subject Name" $crypt keyexchange -keyusage {key_agreement key_encipherment} -enhkeyusage client_auth]
crypt_free $crypt

The above will create a binary which can be sent to the remote signing authority where the certificate request contents can be retrieved:

set parsed_req [cert_request_parse $req]

After verifying the validity of the request (how this is done is entirely up to the application), a certificate for the requestor can be created:

# Assume cissuer is certificate context of signing certificate
set subject [dict get $parsed_req subject]
set pubkey [dict get $parsed_req pubkey]
set opts {}
foreach optname {-basicconstraints -keyusage -enhkeyusage} {
    if {[dict exists $parsed_req extensions $optname]} {
        lappend opts $optname [dict get $parsed_req extensions $optname]
    }
}
set reqcert [cert_create $subject $pubkey $cissuer {*}$opts]

The encoded new certificate returned can be sent back to the requesting client.

Adding and deleting certificates from a store

Certificates can be added and deleted from certificate stores with the commands cert_store_add_certificate and cert_store_delete_certificate respectively. These commands take a certificate context. A certificate that is in encoded form can be added to a store with cert_store_add_encoded_certificate.

Note that adding a certificate to a store creates a copy of the certificate. The original certificate (context) is unmodified.

The sample code below adds the certificate we created in the previous section to a temporary in-memory store. First we create the memory store.

set store [cert_temporary_open]

Then we add the certificate to it.

set mcert [cert_store_add_certificate $store $cert]

This creates a copy of the certificate we created earlier. Since we no longer need the original, we need to free it.

cert_release $cert

There is now one crucial additional step. The association between a certificate and its private key is maintained by the store and is not part of the certificate. We therefore have to explicitly make the association between the CSP key container and the new certificate context for the temporary store.

cert_set_key_prov $mcert -csp {Microsoft Strong Cryptographic Provider} -keycontainer twapi_test_container -csptype prov_rsa_full

Notice we have specified exactly the key container we had created earlier.

The certificate is now stored in the temporary store and will be available as long as the volatile temporary store is not closed. As a final step we will export the certificate and the private keys to a file. This step is only necessary if we want to move the certificate elsewhere. (Note if we only wanted to export the certificate without private keys, we would follow the procedure in Getting certificate contents.

set fd [open MyCert.pfx w]
chan configure $fd -translation binary
puts -nonewline $fd [cert_store_export_pfx $store [password] -exportprivate]
close $fd

Note that because we are exporting private keys, a password is required to protect the exported file.

Finally, assuming we have no need to hold on to the certificate, we can free up the resources.

cert_release $mcert
cert_store_release $store

Certificate validation

There are several aspects to validating a certificate. At the very least, the following must be checked:

  • the certificate must have a complete chain to a trusted root certificate authority,
  • the current time must lie in the certificate validity period,
  • none of the certificates in the chain have been revoked,
  • the intended use of the certificate matches that in the certificate
  • the identity specified in the certificate is what is expected
The cert_tls_verify command can be used for this purpose. Currently, TWAPI only supports certificate verification for use in SSL connections.

ASN.1 object identifiers

An ASN.1 object identifier (OID) is a dotted decimal string such as 1.2.3.4 that represents a ASN.1 class or attribute. Many CryptoAPI command arguments use OID's to represent types and values such as algorithm identifiers. OID's can be passed in their dotted decimal form, or, for some commonly used ones, a mnemonic identifer. The list of mnemonic identifiers can be obtained through the oids command. Mapping to and from a specific mnemonic can be done through the oidname and oid commands.

X.509 alternative names

The X.509 certificate extensions allow for a list of alternative names to be specified for both the certificate subject and issuer. When passed to commands, this list is formatted as a list of alternating name format and name value elements. The allowed name formats and corresponding values are specified in the following table:

other | The value is a pair of elements, the first being an OID and the second a binary.
email | The value is a RFC 822 email address string.
dns | The value is a DNS name string.
directory | The value is directory name in binary format.
url | The value is a URL string.
ip | The value is a binary octet string containing an IP address.
registered | The value is a registered OID in string format.

Data protection

Windows provides facilities to encrypt and protect data based on the user credentials such that it can only be retrieved on the same system with the same credentials. The The protect_data and unprotect_data commands provide access to this facility.

Commands

cert_blob_to_name ENCODEDBLOB ?options?
Converts the encoded X.509 ASN encoded name in ENCODEDBLOB to a string. The following options control how the returned name is formatted.

-format FORMAT | Specifies how the output is to be formatted. FORMAT must be one of x500 (default), oid or simple.
-noplus BOOLEAN | If true, the plus sign in names is replaced with a single space. Default is false.
-noquote BOOLEAN | If true, quoting of special characters in RDN names is disabled. Default is false.
-reverse BOOLEAN | If true, order of RDN components is reversed. Default is false.
-separator SEPARATOR | Specifies the separator to use between RDN components. SEPARATOR must be one of comma (default), semicolon or newline.
See cert_name_to_blob for the reverse operation.

cert_create SUBJECT PUBKEY ISSUERCERT ?options?
Creates a certificate and returns it in ASN.1 DER-encoded or PEM base-64 encoded format (not as a certificate context). SUBJECT is the name of the subject in X.500 format. PUBKEY is the public key for the certificate subject. ISSUERCERT is the certificate context that will be used to sign the created certificate. The private key associated with this certificate must be accessible to the current process context. The subject name, and alternate name extension if present, from ISSUERCERT will be stored as the issuer name and issuer alternate name extension in the generated certificate.

The following options can be specified for the command:

-altnames ALTNAMES | Specifies X.509 Alternative Name values to include in the certificate. ALTNAMES is a pair of one or two elements. The first is a list of pairs containing the name type and name value as described in X.509 alternative names. The second element, which is optional and defaults to false, is a boolean indicating whether the corresponding certificate extension should be marked critical or not.
-basicconstraints BASICCONSTRAINTS | Specifies a basic constraints extension to be included in the certificate. BASICCONSTRAINTS is a pair of one or two elements. The first is a triplet consisting of a boolean which should be true if the certificate is to be used for a certificate authority, a boolean that indicates whether the path length value is to be enforced, and a non-negative integer which is the path length value itself. These last are only relevant if the first is true. The second element of BASICCONSTRAINTS, which is optional and defaults to true, is a boolean indicating whether the corresponding certificate extension should be marked critical or not. This element cannot be specified if the -purpose option is specified and contains the value ca.
-capathlen CAPATHLENGTH | Specifies the limit on the certificate chain path length during verification. Ignored unless the -purpose option includes ca.
-end ENDTIME | Specifies the end of the certificate validity period. ENDTIME must be of the form Year-Month-Day Hour:Minutes:Seconds. Defaults to one year beyond the start time.
-enhkeyusage ENHKEYUSAGE | Specifies values to use for the X.509 enhanced key usage extension. ENHKEYUSAGE is a pair of one or two elements, the first of which is a list containing one or more values from client_auth, code_signing, email_protection, ipsec_endsystem, ipsec_tunnel, ipsec_user, server_auth, ocsp_signing, timestamp_signing or a valid OID. The second element, which is optional and defaults to false, is a boolean indicating whether the corresponding certificate extension should be marked critical or not.
-encoding ENCODING | Specifies the encoding in which the encoded certificate is returned. ENCODING may be der (default) or pem for DER- and PEM-encoding respectively.
-keyspec KEYSPEC | KEYSPEC must be one of signature (default) or keyexchange and specifies the public/private key pair in the container for which the certificate is being created.
-keyusage KEYUSAGE | Specifies values to use for the X.509 key usage extension. KEYUSAGE is a pair of one or two elements, the first of which is a list containing one or more values from crl_sign, data_encipherment, decipher_only digital_signature, encipher_only, key_agreement, key_cert_sign, key_encipherment and non_repudiation. The second element, which is optional and defaults to false, is a boolean indicating whether the corresponding certificate extension should be marked critical or not.
-purpose PURPOSELIST Specifies the purposes for which the certificate is to be used. This is a more convenient method of specifying common extensions. Use of this adds appropriate extensions but does not preclude caller from specifying other extension-based options. PURPOSELIST must be a list containing zero or more items from the following:

ca | Indicates that the certificate may be used to sign other certificates as a certificate authority. Sets the basic_constraints extension and the key_cert_sign and crl_sign bits of the keyusage extension. The -basicconstraints option can be specified in this case.
client | Indicates the certificate will be used for a SSL/TLS client. Sets digital_signature, key_encipherment and key_agreement in the key usage extension and oid_pkix_kp_client_auth in the enhanced key extension.
server | Indicates the certificate will be used for a SSL/TLS server. Sets digital_signature, key_encipherment and key_agreement in the key usage extension and oid_pkix_kp_server_auth in the enhanced key extension.

-signaturealgorithm SIGLAGORITHM | Specifies the signature algorithm to use for signing the certificate.
-start STARTTIME | Specifies the start of the certificate validity period. STARTTIME must be of the form Year-Month-Day Hour:Minutes:Seconds. Defaults to the current time.

cert_create_self_signed SUBJECT ?options?
Creates a new certificate context for a self-signed certificate and returns a handle to it. The certificate is signed using a cryptographic context based on the specified options. Alternatively, the cert_create_self_signed_from_crypt_context may be used instead if a handle to a cryptographic context is already available.

SUBJECT is the name of the subject (and issuer) in X.500 format.

The following options may be specified:

-altnames ALTNAMES | See cert_create
-capathlen CAPATHLENGTH | See cert_create
-csp CSP | Specifies the name of the CSP to be used. If unspecified, the default Microsoft CSP for the system is used.
-csptype CSPTYPE | Indicates the type of CSP. Defaults to prov_rsa_full. See Cryptographic Service Providers for all possible types.
-end ENDTIME | See cert_create
-enhkeyusage ENHKEYUSAGE | See cert_create
-keycontainer CONTAINERNAME | Specifies the name of the key container to use. If unspecified, the default container for the CSP is used.
-keysettype KEYSETTYPE | KEYSETTYPE type must be user (default) or machine depending on whether the key container is user-specific or not.
-keyspec KEYSPEC | See cert_create
-keyusage KEYUSAGE | See cert_create
-purpose PURPOSELIST | See cert_create
-silent BOOLEAN | Normally, the CSP may prompt the user for any information that may be required to retrieve the keys. If this option is specified as true, the user is never prompted. Instead the command will raise an error if a user prompt would have been required.
-signaturealgorithm SIGLAGORITHM | Specifies the signature algorithm to use for signing the certificate. SIGLAGORITHM is the OID (see ASN.1 Object Identifiers) corresponding to a signature algorithm. Defaults to the SHA1RSA algorithm if unspecified.
-start STARTTIME | See cert_create
The returned certificate handle must be freed by calling cert_release.

cert_create_self_signed_from_crypt_context SUBJECT HCRYPT ?options?
Creates a new certificate context for a self-signed certificate and returns a handle to it. The certificate is signed using the cryptographic context referenced by HCRYPT. Alternatively, the cert_create_self_signed may be used instead to explicitly specify the CSP and key container.

SUBJECT is the name of the subject (and issuer) in X.500 format.

The following options may be specified:

-altnames ALTNAMES | See cert_create
-capathlen CAPATHLENGTH | See cert_create
-end ENDTIME | See cert_create
-enhkeyusage ENHKEYUSAGE | See cert_create
-keyusage KEYUSAGE | See cert_create
-purpose PURPOSES | See cert_create
-silent BOOLEAN | See cert_create_self_signed.
-signaturealgorithm SIGLAGORITHM | See cert_create_self_signed.
-start STARTTIME | See cert_create
The returned certificate handle must be freed by calling cert_release.

cert_duplicate HCERT
Duplicates a certificate context and returns a handle to it. The returned certificate context handle may be the same as HCERT with its reference count increased.

The returned certificate context must be freed by calling cert_release.
cert_enhkey_usage HCERT ?SOURCE?
Returns a list of OID's based on the Enhanced Key Usage (EKU) certificate extension content and/or the EKU certificate property. If SOURCE is not specified or is both, the OID's present in both the extension and the property are returned. If SOURCE is extension or property only those corresponding values are returned, the other is not considered. In the case where neither the extension nor the property is present, the string * is returned indicating the certificate is considered valid for all uses. If the returned list is empty, the certificate is considered invalid for any use.
cert_enum_properties HCERT ?-names?
Returns a list of properties defined for the certificate context HCERT. By default, the returned list contains integer property ids. If -names is specified, the returned list contains the mnenomic for the property id (see cert_property) if defined, and the integer value otherwise.
cert_export HCERT ?-encoding ENCODING?
Returns the certificate content for the specified certificate context. The -encoding option controls the encoding of the returned content. ENCODING may be der (default) or pem for DER- and PEM-encoding respectively.
cert_extension HCERT EXTENSION
Returns a certificate extension as a two element list. The first element is a boolean indicating whether the extension is marked critical. The second element is the value of the extension. EXTENSION is the OID for the extension, either in dotted decimal or mnemonic form.
cert_file_store_open PATH ?options?
Opens a certificate store from a file PATH and returns a handle to a cached copy of it. The following options may be specified:

-backupprivilege BOOLEAN | If true, specifies that the thread's SE_BACKUP_NAME and SE_RESTORE_NAME privileges must be used to open the store. Default is false.
-commitenable BOOLEAN | If true, any changes made to the store are persisted to PATH when the store is closed. Default is false.
-create BOOLEAN | If true, a new store is opened only if it did not exist. An error is raised if the store already existed. Default is false so no error is raised in the latter case.
-deferclose BOOLEAN | Normally changes to any certificate contexts made after the associated store is closed are not persisted. Setting this option to true will defer the closing of the store until all associated certificate contexts have been released. Default is false.
-existing BOOLEAN | If true, when PATH does not already exist, it is not created. An exception is raised instead. Default is false.
-includearchived BOOLEAN | By default, enumeration of certificates in a store will not include any that are marked as archived. Setting this option to true will cause those certificates to be included. Default is false.
-maxpermissions BOOLEAN | If true, the store is opened with the maximum set of access permissions possible. Default is false.
-readonly BOOLEAN | If true, the underlying file is opened in read-only mode. However, changes can still be made to the in-memory cache. Default is false.

The certificate store is written to the file in PKCS #7 format if the file name extension is .p7c or .spc, or if the file was empty. Otherwise the file is written as a serialized certificate store.

The store must be closed with cert_store_release when no longer needed.

cert_import ENCODEDCERT ?-encoding encoding?
Creates and returns a certificate context from encoded data in ENCODEDCERT. ENCODING should be der (default) or pem depending on whether ENCODEDCERT uses DER- or PEM-encoding.
cert_info HCERT
Returns the following fields from a certificate context as a dictionary.

-end | The end of the certificate's validity period in the format Year-Month-Day Hour:Minutes:Seconds
-extensions | A list of extensions in the certificate. Each element is a triplet containing the OID of the extension, a boolean indicating whether the extension is marked critical or not, and the extension value.
-issuer | The name of the certificate issuer.
-issuerid | A binary containing unique id for the certificate issuer. This is generally not used and should not be relied on.
-publickey | The public key of the subject. This is a pair consisting of the algorithm identifier (in the same format as -signaturealgorithm) and a binary containing the public key.
-serialnumber | A binary containing the serial number of the certificate.
-signaturealgorithm | A pair consisting of the OID for the algorithm used to sign the certificate and a binary containing any associated parameters.
-start | The start of the certificate's validity period in the format Year-Month-Day Hour:Minutes:Seconds.
-subject | The name of the certificate subject.
-subjectid | A binary containing unique id for the certificate subject. This is generally not used and should not be relied on.
-version | The X.509 version of the certificate. Note this is 0-based on V3 certificates will have a value of 2.

cert_issuer_name HCERT ?options?
Returns an issuer name field from the certificate context HCERT. The field may be from the certificate itself or a certificate property in the context. The command returns an empty string if the specified name field does not exist in the certificate.

Refer to cert_subject_name for a list of options.
cert_key_usage HCERT
Returns a list of the Intended Key Usage values in a certificate. The command looks for both the extensions 2.5.29.2 and 2.5.29.15. In the case where the extension is not present, the string * is returned indicating the certificate may be used for any purpose.
cert_locate_private_key HCERT ?options?
Searches key containers to locate the private key corresponding to the public key in the certificate context HCERT. Returns a boolean indicating if it was found. In addition, the located key is associated as a property of the certificate and can be retrieved as the key_prov_info property using the cert_property command.

The following options may be specified:

-keysettype any|user|machine | Specifies which key sets are to be searched for the private key. If user or machine, the search is restricted to the containers for the current user or the machine respectively. If any (default), both user and machine containers are searched.
-silent BOOLEAN | Normally, the CSP may prompt the user for any information that may be required to access key containers. If this option is specified as true, the user is never prompted. Instead the command will return 0 indicating no key could be found.

cert_name_to_blob NAME ?options?
Converts the string NAME to an X.509 ASN encoded binary. The following options control the allowed format for NAME.

-format FORMAT | Specifies how NAME is formatted. FORMAT must be one of x500 (default), oid or simple.
-noplus BOOLEAN | If true, the plus sign in NAME is not treated as a value separator. Default is false.
-noquote BOOLEAN | If true, quoting is not supported in NAME. Default is false.
-reverse BOOLEAN | If true, order of RDN components in NAME is reversed before encoding. Default is false.
-separator SEPARATOR | If unspecified, commans and semicolons are parsed as separators. If specified, only SEPARATOR is treated as a separator. SEPARATOR must be one of comma (default), semicolon or newline. In the case of newline, carriage return and linefeed characters are treated as separators.
See cert_blob_to_name for the reverse operation.

cert_physical_store_open NAME LOCATION ?options?
Opens a certificate physical store that is part of a logical system store and returns a handle to a cached copy. NAME is the name of the physical store including the system store component, e.g. Root\.Default. LOCATION specifies the location of the system store and must be one of the values listed in Certificate stores.

Refer to the documentation of cert_system_store_open of a description of options.

The store must be closed with cert_store_release when no longer needed.
cert_physical_store_delete NAME LOCATION
Deletes a certificate physical store that is part of a logical system store. NAME is the name of the physical store including the system store component, e.g. Root\.Default. LOCATION specifies the location of the system store and must be one of the values listed in Certificate stores.
cert_property HCERT PROPERTY
Returns the value of a certificate property in the certificate context referenced by HCERT. Raises an error if the property does not exist in the certificate context. PROPERTY must be one of the following:

access_state | A non-0 integer if write operations to the certificate context are persisted and 0 if they are not.
archived | If this property exists, the certificate is an archived certificate.
auto_enroll | The certificate type for which this certificate has been auto-enrolled.
date_stamp | The date and time that the certificate was added to the store.
description | The description associated with the certificate for display purposes.
enhkey_usage | A list of enhanced key usage OID's.
extended_error_info | Any extended error information for the certificate context.
friendly_name | The display name for the certificate.
issuer_public_key_md5_hash | The MD5 hash of the issuer's public key used to sign the certificate.
issuer_serial_number_md5_hash | The MD5 hash of the issuer name and serial number.
key_context | A list of two elements containing a handle to the cryptographic context for the certificate and the key type.
key_identifier | A binary containing the Subject Key Identifier value if it exists else the SHA1 hash on the certificate Subject Public Key.
key_prov_handle | A handle to the associated cryptographic context.
key_prov_info | A list containing the following elements: the name of the key container, the name of the CSP, the CSP type, attributes, key container parameters and the key type.
key_spec | Specifies the private key.
md5_hash | Binary containing the MD5 hash of the certificate.
pvk_file | File path of the private key file corresponding to the certificate's public key.
sha1_hash | Binary containing the SHA1 hash of the certificate. This can also be retrieved as a hexadecimal string with cert_thumbprint.
signature_hash | Signature hash.
subject_name_md5_hash | Binary containing the MD5 hash of the encoded subject name.
subject_public_key_md5_hash | Binary containing the MD5 hash of the certificate public key.

cert_property_delete HCERT PROPERTY
Deletes a certificate property in the certificate context referenced by HCERT. No error is raised if the property does not exist. PROPERTY must be one of the property names listed in the documentation for cert_property.
cert_property_set HCERT PROPERTY PROPVAL
Sets the value of a certificate property in the certificate context referenced by HCERT. PROPERTY must be one of description, friendly_name or pvk_file (see cert_property).
cert_release HCERT
Decreases the reference count for a certificate context and frees it if the result is 0.
cert_request_create SUBJECT HCRYPT KEYSPEC ?options?
SUBJECT is the name of the subject in X.500 format. Returns an encoded certificate signing request (CSR) that can be sent to a certificate authority. HCRYPT and KEYSPEC together select the public/private key pair for which a certificate is to be requested. HCRYPT is a handle to a cryptographic context and KEYSPEC must be signature or keyexhange to select the appropriate key pair in the context.

The following options may be specified:

-altnames ALTNAMES | See cert_create
-capathlen CAPATHLENGTH | See cert_create
-encoding ENCODING | Specifies the encoding of the returned CSR. ENCODING may be der (default) or pem for DER- and PEM-encoding respectively.
-enhkeyusage ENHKEYUSAGE | See cert_create
-keyusage KEYUSAGE | See cert_create
-purpose PURPOSES | See cert_create

cert_request_parse CSR ?-encoding ENCODING?
Parses a certificate signing request CSR and returns a dictionary with its contents. ENCODING should be der (default) or pem depending on whether ENCODEDCERT uses DER- or PEM-encoding.

The returned dictionary has the following keys:

attributes | The attribute field in the CSR. This is a list each element of which is a pair consisting of an OID and a list of corresponding values.
extensions | A subset of the attributes key, formatted for easier processing. See the discussion below. This key may be absent if the attributes do not contain any extensions.
pubkey | The public key of the requestor. This should be passed to cert_create as the public key argument.
subject | The subject name of the requestor. This should be passed to cert_create as the subject argument.
version | The CSR format version number.
One of the potential attribute fields in a CSR is OID 1.2.840.113549.1.9.14 through which the requestor can indicate certain certificate extensions to be included in the returned certificate. This specific attribute is parsed and returned as the value of the extensions dictionary element above. This value is itself a dictionary which may contain zero or more of the keys -basicconstraints, -keyusage and -enhkeyusage. The corresponding values have the same format as the corresponding options to the cert_create command.

cert_set_key_prov HCERT ?options?
Associates the certificate context HCERT with a CSP key container. The following options specify the container:

-csp CSP | Specifies the name of the CSP for the container. If unspecified, the default Microsoft CSP for the system is used.
-csptype CSPTYPE | Indicates the type of CSP. Defaults to prov_rsa_full. See Cryptographic Service Providers for all possible types.
-keycontainer CONTAINERNAME | Specifies the name of the key container. If unspecified, the default container is used.
-keysettype KEYSETTYPE | KEYSETTYPE must be user (default) or machine.
-keyspec KEYSPEC | KEYSPEC must be one of keyexchange (default) or signature.
-silent BOOLEAN | Normally, the CSP may prompt the user for any information that may be required to create the context. If this option is specified as true, the user is never prompted. Instead the command will raise an error if a user prompt was required.

cert_store_add_certificate HSTORE HCERT ?-disposition DISPOSITION?
Adds a new certificate to a certificate store. HSTORE is the handle to the store and HCERT is a handle to a certificate context. The new certificate is a copy of HCERT. The command returns a handle to the new certificate context which must be freed with cert_release when no longer needed. Note that the new certificate is not persisted until the store is saved.

Any properties associated with HCERT are also copied to the new certificate context with the exception of any key associations. These must be explicitly added to the new context if desired using cert_set_key_prov.

The -disposition option controls what happens if a matching certificate already exists in the store. DISPOSITION may take one of the following values:

duplicate | Creates the new certificate while keeping the existing one. This will create duplicates in the store.
overwrite | Overwrites the existing certificate with the new one.
preserve | (default) If a matching certificate exists, it is preserved and a error raised. Otherwise, the new certificate is added.
update | The new certificate is added if there is no matching certificate or the matching certificate's validity period start time is less than that of the new certificate. Otherwise an error is raised.

cert_store_add_encoded_certificate HSTORE ENCODEDCERT ?options?
Adds a new certificate to a certificate store. HSTORE is the handle to the store. ENCODEDCERT is a binary value containing the certificate encoded in X.509 ASN.1 format. The command returns a handle to the new certificate context which must be freed with cert_release when no longer needed. Note that the new certificate is not persisted until the store is saved.

Supported options are:

-disposition DISPOSITION Controls what happens if a matching certificate already exists in the store. DISPOSITION may take one of the following values:

duplicate | Creates the new certificate while keeping the existing one. This will create duplicates in the store.
overwrite | Overwrites the existing certificate with the new one.
preserve | (default) If a matching certificate exists, it is preserved and a error raised. Otherwise, the new certificate is added.
update | The new certificate is added if there is no matching certificate or the matching certificate's validity period start time is less than that of the new certificate. Otherwise an error is raised.

-encoding ENCODING Specifies the encoding of ENCODEDCERT. ENCODING should be der (default) or pem depending on whether ENCODEDCERT uses DER- or PEM-encoding.

cert_store_commit HSTORE ?-force BOOLEAN?
Commits any changes made to a certificate store. If -force is specified as true, the store is written out even if no changes have been made to the in-memory copy.
cert_delete_from_store HCERT
Deletes the specified certificate context from its containing store. Also decreases the reference count on the certificate context.
cert_store_enum_contents HSTORE ?HCERT?
The command returns a handle to a certificate context for the next certificate in the store specified by the handle HSTORE. When HCERT is not specified or is specified as NULL, the enumeration starts from the first certificate in the store. If HCERT is specified, it must be a handle to a certificate context returned by a previous call to the command. The command then returns the next certificate in the store. The command also frees HCERT (even in case of errors) so caller must not access it after the command returns. If HCERT needs to be accessed later, use the cert_duplicate command to make a copy first.

A certificate context handle returned by the command that is not passed back in as HCERT in a subsequent call, must be released by calling cert_release.

The command returns an empty string when there are no more certificates in the store.

The command cert_store_find_certificate offers another means for retrieving certificates from a store.
cert_store_export_pfx HSTORE PASSWORD ?options?
Returns a binary containing all the certificates in a certificate store in PFX (PKCS #12) format. HSTORE is a handle to the store and PASSWORD is the password to be used for encrypting the returned content. PASSWORD itself must be an empty string (if the returned data is not to be encrypted), or the encryption password in encrypted form as returned by the read_credentials or conceal commands.

The following options may be specified with the command:

-exportprivatekeys BOOLEAN | If true, any private keys associated with the exported certificates are included in the returned binary. Default is false.
-failonmissingkey BOOLEAN | If true, the command raises an error if any certificate claims to have an associated private key but does actually have one. Default is false.
-failonunexportablekey BOOLEAN | If true, the command raises an error if any certificate claims to have an associated private key but does actually have one that is exportable. Default is false.

cert_store_export_pkcs12 HSTORE PASSWORD ?options?
Alias for cert_store_export_pfx.
cert_store_export_pkcs7 HSTORE ?-encoding ENCODING?
Returns a binary in PKCS #7 format containing all the certificates in a certificate store. HSTORE is a handle to the store. External properties associated with certificate are not exported. The -encoding option specifies the encoding for the returned certificate. ENCODING should be der (default) or pem for DER- and PEM-encoding respectively.
cert_store_find_certificate HSTORE ?SEARCHTYPE? ?SEARCHTERM? ?HCERT?
The command returns a handle to a certificate context for the next matching certificate in the store specified by the handle HSTORE. When HCERT is not specified or is specified as NULL, the search starts from the first certificate in the store. If HCERT is specified, it must be a handle to a certificate context returned by a previous call to the command. The search then begins with the next certificate in the store. The command also frees HCERT (even in case of errors) so caller must not access it after the command returns. If HCERT needs to be accessed later, use the cert_duplicate command to make a copy first.

A certificate context handle returned by the command that is not passed back in as HCERT in a subsequent call, must be released by calling cert_release.

The command returns an empty string when there are no more certificates in the store.

The criteria for matching are specified by the SEARCHTYPE and SEARCHTERM arguments as in the table below where the first column specifies possible values of SEARCHTYPE.

any | Returns every certificate in the store. SEARCHTERM is ignored.
certificate | Returns certificates that exactly match the certificate context whose handle is specified as SEARCHTERM.
issuer_name | Returns certificates whose issuer exactly matches SEARCHTERM. SEARCHTERM is a X.509 name in encoded form as returned by cert_name_to_blob.
issuer_substring | Returns certificates whose issuer contains the string SEARCHTERM. Note SEARCHTERM is a string, not in X.509 encoded form.
key_identifier | Returns certificates with a matching value for the subject key identifier (OID 2.5.29.14) extension.
md5_hash | Returns certificates that have a MD5 hash which matches the binary SEARCHTERM.
property | Returns certificates that have a property with id SEARCHTERM (see cert_property).
pubkey_md5_hash | Returns certificates whose MD5-hashed public key matches the binary SEARCHTERM.
public_key | Returns certificates containint the specified public key SEARCHTERM. This is a pair consisting of the algorithm identifier (in the same format as -signaturealgorithm) and a binary containing the public key.
sha1_hash | Returns certificates that have a SHA1 hash which matches the binary SEARCHTERM.
signature_hash | Returns certificates that have a signature hash which matches the binary SEARCHTERM.
subject_name | Returns certificates whose subject exactly matches SEARCHTERM. SEARCHTERM is a X.509 name in encoded form as returned by cert_name_to_blob.
subject_substring | Returns certificates whose subject contains the string SEARCHTERM. Note SEARCHTERM is a string, not in X.509 encoded form.

cert_store_release HSTORE
Decreases the reference count for the specified handle to a certificate store and releases associated resources when it reaches 0.
cert_store_serialize HSTORE
Returns a binary containing all the certificates in a certificate store along with their external properties. HSTORE is a handle to the store to be serialized. The returned data may be stored in a file that can be opened with cert_file_store_open.
cert_subject_name HCERT ?options?
Returns a subject name field from the certificate context HCERT. The field may be from the certificate itself or a certificate property in the context.

By default the common name in the certificate is returned. The -name option can be specified to retrieve a different field. The value of the option can be a OID string identifying a certificate name attribute or one of the values in the table below:

dns | Returns the DNSName choice in the Alternative Name extension if there is one, or the the CN OID 2.5.4.3 from the Subject Name field. If neither is found returns an empty string.
email | Returns the first rfc822Name choice in the Alternative Name extension. If not found, returns the name field for the Email OID. Otherwise returns an empty string.
friendlydisplay | Returns the CERT_FRIENDLY_NAME_PROP_ID property if there is one. Otherwise behaves as simpledisplay.
simpledisplay | Returns the first attribute suitable for display purposes from Name or Alternative Name extension.
oid_common_name | Returns the Common Name (Default).
rdn | Returns the Subject Name RDN if there is one. If not found, returns the first Directory Name choice from the Alternative Name extension if there is one. Otherwise returns an empty string. The format for this option can be further controlled as described later.
upn | Returns the UPN from the OID 1.3.6.1.4.1.311.20.2.3 in the OtherName choices from the Alternative Name extension and an empty string if not found.
url | Returns the URL choice in the Alternative Name extension if there is one. If not found, returns an empty string.
When the -name option is rdn, the following options may be further specified to control the returned format.

-format FORMAT | Specifies how the output is to be formatted. FORMAT must be one of x500 (default), oid or simple.
-noplus BOOLEAN | If true, the plus sign in names is replaced with a single space. Default is false.
-noquote BOOLEAN | If true, quoting of special characters in RDN names is disabled. Default is false.
-reverse BOOLEAN | If true, order of RDN components is reversed. Default is false.
-separator SEPARATOR | Specifies the separator to use between RDN components. SEPARATOR must be one of comma (default), semicolon or newline.
The command returns an empty string if the specified name does not exist in the certificate.

cert_system_store_open NAME ?LOCATION? ?options?
Opens a logical system store and returns a handle to a cached copy. NAME is the name of the logical store such as Root or My. LOCATION specifies the location of the system store and must be one of the values listed in Certificate stores.

The following options may be specified:

-backupprivilege BOOLEAN | If true, specifies that the thread's SE_BACKUP_NAME and SE_RESTORE_NAME privileges must be used to open the store. Default is false.
-create BOOLEAN | If true, a new store is opened only if it did not exist. An error is raised if the store already existed. Default is false so no error is raised in the latter case.
-deferclose BOOLEAN | Normally changes to any certificate contexts made after the associated store is closed are not persisted. Setting this option to true will defer the closing of the store until all associated certificate contexts have been released. Default is false.
-existing BOOLEAN | If true, when PATH does not already exist, it is not created. An exception is raised instead. Default is false.
-includearchived BOOLEAN | By default, enumeration of certificates in a store will not include any that are marked as archived. Setting this option to true will cause those certificates to be included. Default is false.
-maxpermissions BOOLEAN | If true, the store is opened with the maximum set of access permissions possible. Default is false.
-readonly BOOLEAN | If true, the store is opened in read-only mode. Depending on the provider, the effect may be to either disallow all changes to the store, or to allow changes to the in-memory cache but not persisting them. Default is false.
The store must be closed with cert_store_release when no longer needed.

cert_system_store_delete NAME LOCATION
Deletes a certificate system store. NAME is the name of the store and LOCATION specifies its location which must be one of the values listed in Certificate stores.
cert_system_store_locations LOCATION
Returns a list of system store locations. See Certificate stores.
cert_system_stores LOCATION
Returns a list of system stores at the system store location LOCATION. LOCATION specifies the location of the system store and must be one of the values listed in Certificate stores.
cert_temporary_store ?options?
Creates a temporary, non-persistent certificate store in memory and returns a handle to it. The store must be closed with cert_store_release when no longer needed. All contents of the store are deleted when it is closed. The cert_store_save command can be used to save the contents to a persistent store if desired.

By default, the created store is empty. The following mutually exclusive options may be specified to initialize the store with certificates.

-pfx PFXBLOB Initializes the temporary store with certificates imported from a PFX (also known as PKCS #12) formatted packet. In addition to the certificates, any private keys present are also imported into the system. Unlike the store itself, these keys are persisted. The following additional options may be used with -pfx and -pkcs12:

-exportableprivatekeys BOOLEAN | If specified as true, private keys in the created certificate store may be exported. Default is false.
-keysettype user|machine | Without this option, keys are imported as per-user or per-machine as specified in the PFX blob. This option can be used to override this.
-password PASSWORD | Specifies the password used to decrypt PFXBLOB. If the option is not specified, or if PASSWORD is the empty string, the command assumes PFXBLOB is in unencrypted form. If not the empty string, PASSWORD must be in encrypted form as returned by by the read_credentials or conceal commands.
-userprotected BOOLEAN | If specified as true, the private keys are protected such that the user is notified on operations that use that key. The specific operations that will trigger notifications depend on the CSP being used.

-pkcs12 PKCS12BLOB | This an alias for the -pfx option.
-pkcs7 PKCS7BLOB | PKCS7BLOB is a PKCS #7 packet containing certificates. The additional option "-encoding ENCODING" may be used with -pkcs7 where ENCODING must be der (default), or pem to indicate the packet is DER- or PEM-encoded.
-serialized SERIALIZEDBLOB | SERIALIZEDBLOB is a serialized certificate store, such as returned from cert_store_serialize.

The temporary store must be closed with cert_store_release when no longer needed.

cert_thumbprint HCERT
Returns a SHA-1 based thumbprint for the specified certificate. This is returned as a hexadecimal string and can be used for a quick comparison to check if two certificates are identical.
cert_tls_verify HCERT ?options?
Verifies a certificate context HCERT for use in an SSL/TLS connection. The following options may be specified:

-cacheendcert BOOLEAN | If BOOLEAN is true, the end (leaf) certificate is cached. Default is false.
-disableauthrootautoupdate BOOLEAN | If BOOLEAN is true, auto-update of third party roots from the Windows update server is disabled. Default is false.
-engine ENGINE | Specifies the chain engine to be used for verification. ENGINE must be user (default) or machine. The engine indicates the namespace and cache to be used for building the verification chain.
-hstore HSTORE | Allows specification of another certificate store to be searched for supporting certificates. HSTORE is a handle to a certificate store as returned by commands like cert_system_store_open.
-ignoreerrors ERRORLIST | Specifies that certain errors in verification are to be ignored. See description later.
-revocationcheck REVOCATIONSPEC | Specifies which certificates in the chain are checked for revocation. REVOCATIONSPEC must be one of all (default) indicating all certificates are to be checked, leaf indicating only the leaf certificate is to be checked, none which disables revocation checks, and excluderoot which indicates all certificates other than the root are to be checked.
-revocationcheckcacheonly BOOLEAN | If BOOLEAN is true, only cached revocation lists are checked when verifying revocation. Default is false.
-server SERVER Specifies that the certificate being verified is for a server with name SERVER. If this option is not specified, the verification is done assuming the certificate represents a client. In the former case, it also verifies that the name in the certificate matches SERVER. The command does not verify names in the case of client certificates.

If neither of the options -usageall or -usageany is explicitly specified, they default to server_auth and client_auth respectively depending on whether -server is specified or not.
-trustedroots HCERTLIST | Windows requires the root of the certificate verification chain belong to one the Windows' trusted stores. Under some circumstances, such as use of a private certificate authority whose root certificate is not in the Windows trusted store list, the command will return a status of untrustedroot. Instead of ignoring this error through the -ignoreerrors unknownca option, the caller can provide a list of certificate contexts HCERTLIST that are acceptable as trusted root certificates in addition to those in the Windows trusted store.
-urlretrievalcacheonly BOOLEAN | If BOOLEAN is true, only cached URLs are used in building the certificate chain without searching the network. Default is false.
-usageall USAGELIST | Specifies that the certificate enhanced key usage field must include all the values for USAGELIST. USAGELIST is a list containing OID's or the following values: server_auth, client_auth, code_signing, email_protection, ipsec_end_system, ipsec_tunnel, ipsec_user, timestamp_signing or ipsec_ike_intermediate.
-usageany USAGELIST | Specifies that the certificate enhanced key usage field must include any of the values for USAGELIST. USAGELIST is as described for the -usageall option above.
The -ignoreerrors option allows the caller to specify certain error types that are to be ignored in the verification process. This option must be used with great care and only in special circumstances. The argument to the option is a list with one or more of the following values:

basicconstraints | Ignore errors in basic constraints.
criticalextensions | Ignore errors pertaining to extensions marked as critical that are not understood by CryptoAPI.
name | Ignore errors in name validation.
policy | Ignore invalid policy errors.
revocation | Ignore errors related to certificate revocation.
time | Ignore errors in validity period checks.
unknownca | Allow the root certificate to not be in the trusted roots list.
usage | Ignore errors related to the -usageall and -usageany options.
The command returns ok if the certificate was verified successfully. If the certificate verification process could not be executed, a Tcl exception is raised. If the verification process completed but the certificate did not successfully pass, the command does not raise an exception but returns a Win32 error code or one of the following values:

signature | Signature verification failed
revoked | Certificate has been revoked
untrustedroot | The root certificate is not in the Windows trusted root list
chaining | Invalid certificate chain
wrongusage | Certificate usage extension did not match specified usage.
expired | Certificate has expired.
name | Name does not match
policy | Certificate did not match policy conditions
basicconstraints | Basic constraints check failed
criticalextension | Certificate includes an unsupported extension marked as critical
validityperiodnesting | Time periods for certificates in the chain are not nested.
norevocationcheck | Revocation checks could not be made because of errors.
revocationoffline | Revocation checks could not be done because the revocation server was offline.
cnmatch | Common name does not match -server option.
purpose | The specified purpose is different from the one specified by the issuing CA.
carole | The certificate that can be marked for use as a CA is being used as a leaf or vice-versa.

crypt_acquire KEYCONTAINER ?options?
Returns a handle to a cryptographic context for the specified key container in a CSP. If KEYCONTAINER is the empty string, the default container for the CSP is used.

The handle must be freed when no longer required by calling crypt_free.

-create BOOLEAN | If specified as true, the key container is created if it does not exist. If false (default) an error is generated if the key container does not exist.
-csp CSP | Specifies the name of the CSP to be used. If unspecified, the default Microsoft CSP for the system is used.
-csptype CSPTYPE | Indicates the type of CSP. Defaults to prov_rsa_full. See Cryptographic Service Providers for all possible types.
-keysettype KEYSETTYPE | KEYSETTYPE must be user (default) or machine. Normally the key container is stored in the user's profile. If KEYSETTYPE is machine, the key container is treated as a computer container. This is needed when an application must access the keys from a process where the user profile is not loaded.
-silent BOOLEAN | Normally, the CSP may prompt the user for any information that may be required to create the context. If this option is specified as true, the user is never prompted. Instead the command will raise an error if a user prompt was required.
-verifycontext BOOLEAN | If specified as true, the context is intended for use with ephemeral keys which are not persisted. Default is false. When true, -keycontainer must not be specified if the CSP is file-based. If specified as false, the returned context provides access to persisted private keys in the container. Specifying this option as true results in a key container being created in memory and deleted when the cryptographic context is released. See the Microsoft knowledgebase article for more details.

crypt_csp HCRYPT
Returns the name of the CSP owning the cryptographic context HCRYPT.
crypt_csps
Returns a list of pairs, each representing a CSP on the system. The first element of each pair is a CSP type and the second is the name of the CSP.
crypt_csptype HCRYPT
Returns the type of the CSP owning the cryptographic context HCRYPT.
crypt_csptypes
Returns a list of pairs, each representing a CSP type on the system. The first element of each pair is a CSP type and the second is the name of the CSP.
crypt_free HCRYPT
Frees a cryptographic context returned by crypt_free.
crypt_get_security_descriptor HCRYPT
Returns the security descriptor associated with a CSP key container whose handle is HCRYPT.
crypt_key_container_delete KEYCONTAINER ?options?
Deletes the key container identified by the specified options. KEYCONTAINER specifies the name of the key container to be deleted in the CSP. If the empty string, the default container is deleted. Since this can impact other applications, the -force option must be specified when deleting the default container.

-csp CSP | Specifies the name of the CSP for the key container. If unspecified, the default Microsoft CSP for the system is used.
-csptype CSPTYPE | Indicates the type of CSP. Defaults to prov_rsa_full. See Cryptographic Service Providers for all possible types.
-force | Must be specified when deleting the default container.
-keysettype KEYSETTYPE | KEYSETTYPE must be user (default) or machine. Normally the key container is stored in the user's profile. If KEYSETTYPE is machine, the key container is treated as a computer container.

crypt_key_container_name HCRYPT
Returns the name of key container for the cryptographic context.
crypt_key_container_names HCRYPT
Returns the names of the other key containers owned by the CSP other than the one current one.
crypt_key_free HCRYPTKEY
Frees a handle to a cryptographic key.
crypt_key_generate HCRYPT ALGORITHM ?options?
Generates a new key or public/private key pair in the cryptographic context HCRYPT and returns a handle to it. ALGORITHM specifies the algorithm with which the keys will be used and must be one of keyexchange, signature, or the OID of an algorithm in either dotted decimal or mnemonic form.

The following options may be specified with the command:

-archivable BOOLEAN | If true, the key can be exported until its handle is freed after which it is no longer exportable.
-exportable BOOLEAN | If true, the key is exportable. If false, session keys and private keys are not exportable.
-pregen BOOLEAN | If true, specifies an initial Diffie-Hellman or DSS key generation. Not applicable for other algorithms.
-userprotected BOOLEAN | If true, the user is notified by some CSP-specific means for some uses of the key.
-size KEYSIZE | Specifies the key size to override the default key size. Since default key sizes are platform dependent, Microsoft recommends key size be explicitly set.

The returned handle must be freed by calling crypt_key_free.

crypt_keypair HCRYPT keytype
Returns a handle to one of two public/private key pairs in a key container. HCRYPT is a handle to the CSP key container. keytype must be either keyexchange or signature and specifies which of the two key pairs in the container.

The returned handle must be freed by calling crypt_key_free.
crypt_keyset_type HCRYPT
Returns user or machine depending on whether the key set in the container is per-user or per-machine.
crypt_set_security_descriptor HCRYPT ?SECD?
Sets the security descriptor associated with a CSP key container whose handle is HCRYPT.
crypt_session_key_size HCRYPT
Returns the size of the session key in the container.
crypt_symmetric_key_size HCRYPT
Returns the size of the symmetric key in the container.
protect_data BINDATA ?options?
Encrypts and signs the binary data BINDATA so that it can only be recovered by a process running under the same user credentials on the same system through unprotect_data.

The following options may be specified:

-audit BOOLEAN | If true, an audit event is generated. Default is false.
-description DESCRIPTION | A descriptive string that is stored with the encrypted data.
-hwnd HWND | The handle to the parent window if a dialog is to be shown to the user.
-localmachine BOOLEAN | If false (default), only the same user can decrypt the data. If true, any user on the same machine can do the decryption.
-noui BOOLEAN | If true, the operation fails if any user dialog is required to be shown. Default is false.
-prompt PROMPTSTRING | If specified, the user is shown a dialog with the specified PROMPTSTRING to set the security level of the encrypted data. The user will also be prompted at the time the data is decrypted.

unprotect_data BINDATA ?options?
Decrypts and verifies the signature on the binary data BINDATA which must have been encrypted with the protect_data command. The command will raise an error if BINDATA was encrypted under different user or machine credentials. The command returns the decrypted data.

The following options may be specified:

-withdescription BOOLEAN | By default the command returns just the decrypted data. If specified as true, the command returns a list of two elements - the decrypted data and a descriptive string that is stored with the encrypted data.
-hwnd HWND | The handle to the parent window if a dialog is to be shown to the user.
-noui BOOLEAN | If true, the operation fails if any user dialog is required to be shown. Default is false.
-prompt PROMPTSTRING | If specified, the user is shown a dialog with the specified PROMPTSTRING.

COPYRIGHT

Copyright © 2007-2013 Ashok P. Nadkarni


SSPI - Security Service Provider Interface

SSPI

Commands for invoking the Security Service Provider Interface

SYNOPSIS

package require twapi_crypto

sspi_acquire_credentials ?options?
sspi_client_context CREDENTIALS ?options?
sspi_context_features CONTEXT
sspi_context_sizes CONTEXT
sspi_context_username CONTEXT
sspi_decrypt CONTEXT ENCRYPTTOKEN ENCRYPTEDDATA PADDING ?options?
sspi_decrypt_stream CONTEXT ENCRYPTEDDATA
sspi_delete_context CONTEXT
sspi_encrypt CONTEXT BINDATA ?options?
sspi_encrypt_and_write CONTEXT BINDATA ?options?
sspi_encrypt_stream CONTEXT BINDATA ?options?
sspi_enumerate_packages ?options?
sspi_free_credentials arg CREDENTIALS
sspi_issuers_accepted_by_peer CONTEXT
sspi_local_cert CONTEXT
sspi_remote_cert CONTEXT
sspi_server_context CREDENTIALS CLIENTDATA ?options?
sspi_sign CONTEXT DATA ?options?
sspi_schannel_credentials ?options?
sspi_shutdown_context CONTEXT
sspi_step CONTEXT ?RESPONSE?
sspi_verify_signature CONTEXT SIGNATURE DATA ?options?
sspi_winnt_identity_credentials USER DOMAIN PASSWORD

DESCRIPTION

This module is still experimental and liable to change.

This package includes procedures related to the Security Service Provider Interface (SSPI) on the Windows platforms. For commands for other cryptographic operations, refer to the CryptoAPI documentation.

SSPI overview

The Security Support Provider Interface is a standard interface to various security protocols that provide for security functions such as authentication, encryption and integrity. The SSPI interface allows establishment of a security context that can be used for signing and encrypting data passed between a client and a server.

This module currently supports only the Negotiate, NTLM, Kerberos, SChannel and Microsoft Unified Security Protocol Provider packages.

SSPI security context establishment

On the client side, the application program starts off by retrieving the credentials to be used to authenticate itself to the server by calling sspi_acquire_credentials with the -role client option. It then creates a new client security context by calling sspi_client_context specifying appropriate desired security characteristics. The application then exchanges messages with the server to complete the authentication.

Depending on the security protocol in use, the authentication between the client and the server may require multiple message exchanges between the client and the server. Once it obtains its security context, the client calls sspi_step passing it the security context. This command returns an indication of whether the authentication is complete, or more exchanges with the server are required. In the latter case, data returned by the command is sent to the server and the server response is passed back to the command. This sequence is repeated until the command indicates the authentication is complete or generates a Tcl exception indicating authentication failure. The security context generated in this manner can then be used to sign and encrypt messages between the client and the server.

On the server side, the application program starts off by retrieving its own credentials by calling sspi_acquire_credentials with the -role server. It then creates a new server security context by calling sspi_server_context passing it the authentication data sent by the client. The server then enters the authentication loop described below. From this point on, the server follows the authentication loop calling sspi_step in the same manner as described above for the client.

Once a security context is established, either on the client or the server, its characteristics, including the negotiated parameters, security principal name etc. can be retrieved through commands sspi_context_features, sspi_context_username and sspi_context_sizes. In the case of SSL/SChannel based providers, the sspi_local_cert and sspi_remote_cert return the certificates in use for a connection. Note that not all commands are supported by all security providers.

The security context should be released when no longer needed. For schannel based providers only, first call sspi_shutdown_context and pass any returned data to the remote peer. Then call sspi_delete_context to release context releases. For other providers, only sspi_delete_context should be called.

Similarly, when no longer required, both the server and client ends should free resources associated with their credentials by calling sspi_free_credentials.

SSPI message signing and encryption

Once a security context has been completely created as above, it can then be used to generate and verify messages signatures using sspi_sign and sspi_verify_signature respectively.

Similarly, the security context can be used to encrypt and decrypt messages using sspi_encrypt and sspi_decrypt.

SSPI stream encryption

For SSPI stream contexts, the commands sspi_encrypt_stream and sspi_decrypt_stream encrypt and decrypt streaming data. Alternately the sspi_encrypt_and_write command can be used to directly write encrypted data to a channel.

Commands

sspi_acquire_credentials ?options?
Returns a credentials handle that can be used to negotiate and establish a security context. The command returns the handle to the credentials unless the -getexpiration option is specified in which case it returns a keyed list with two fields: -handle which is the handle to the credentials, and -expiration which returns the time (as number of 100ns intervals since January 1, 1601) at which the credentials expire.

The following options may be specified with the command:

-credentials CREDENTIALS | Specifies the credentials to which a handle is to be returned. If unspecified the default credentials for the package are used. For NTLM or Negotiate providers, the sspi_winnt_identity_credentials should be used to return non-default credentials in the appropriate format. For SSL/Schannel based providers, the sspi_schannel_credentials should be used for the same purpose.
-getexpiration | If specified, the expiration time for the returned credentials is also returned. See description of command return value above.
-package SECURITYPACKAGE | Specifies the security package with which the credentials are to be used. By default, this is NTLM. The list of available security packages on a system can be obtained through sspi_enumerate_packages.
-principal PRINCIPAL | Specifies the name of the principal whose credentials are to be referenced. By default, this is the user account under which the process is running.
-role ROLE | Indicates how the credentials will be used, based on ROLE - client or outbound for clients, server or inbound for servers and both (default) if credentials are used for both purposes. Note that SSL/SChannel based providers require separate client and server credentials and both is not a valid option for them.

The returned credentials handle must be freed by calling sspi_free_credentials when no longer needed.

sspi_client_context CREDENTIALS ?options?
Initiates the building of a new client-side, security context from based on the specified credentials. CREDENTIALS is a handle to credentials returned by sspi_acquire_credentials. The returned value, which is a handle to a security context, should be treated as opaque by the caller and used as described in SSPI security context establishment.

The options below specify the requirements for the context. Note that not all security providers support all options or combinations of options. Refer to the Windows SDK for more information about these options.

-confidentiality BOOL | If specified as true, messages are to be encrypted.
-connection BOOL | If specified as true, the security context will not handle formatting of messages.
-datarep DATAREP | Specifies the data representation on the target. DATAREP must be either network (default) or native.
-delegate BOOL | If specified as true, the server can use the context to other servers as the client. Requires -mutualauth to also be specified as true.
-extendederror BOOL | When true, the remote end is notified of errors. Note that several Windows versions, including Windows 7, may experience SSL/TLS negotiation failures when this option is specified. See Microsoft Knowledgebase article KB975858 for details.
-integrity BOOL | If specified as true, messages are to be signed.
-manualvalidation BOOL | If BOOL is false (default), SChannel based providers will validate the remote server's certificate. If specified as true, the provider will not validate the received certificate. It is the caller's responsibility to do so. The remote certificate can be retrieved with sspi_remote_cert and verified as described in Certificate verification.
-mutualauth BOOL | If specified as true, both the client and server are to be authenticated.
-replaydetect BOOL | If specified as true, detection of replayed messages is desired.
-sequencedetect BOOL | If specified as true, detection of out-of-sequence messages is desired.
-stream BOOL | If specified as true, indicates a stream oriented connection.
-target TARGET | Specifies the target of the security context. The format depends on the security service provider. In the case of a SSL/SChannel based provider, this is generally the name that should match the subject name in the certificate sent by the server.
-usesessionkey BOOL | If specified as true, a new session key must be negotiated.

When a security context is no longer required, it should be released by calling sspi_delete_context.

sspi_context_features CONTEXT
After a security context is established, this command may be used to retrieve information about what security features were negotiated. The command returns a keyed list with boolean values for the following fields.

-confidentiality | If true, encryption is supported.
-connection | If true, the security context will not handle formatting of messages.
-delegate | If true, the server can use the context to other servers as the client.
-extendederror | If true, the remote end is notified of errors.
-integrity | If true, messages signing is supported.
-mutualauth | If true, both the client and server are authenticated.
-replaydetect | If true, detection of replayed messages is enabled.
-sequencedetect | If true, detection of out-of-sequence messages is enabled.
-stream | If true, indicates a stream oriented connection.

sspi_context_sizes CONTEXT
Returns a keyed list with the following fields:

-maxtoken | Maximum size of token used in the authentication exchange.
-maxsig | Maximum size of signature.
-blocksize | Messages should preferably be a multiple of this value.
-trailersize | Size of security trailer to be appended to messages.

sspi_context_username CONTEXT
TBD
sspi_decrypt CONTEXT ENCRYPTTOKEN ENCRYPTEDDATA PADDING ?options?
Returns the decrypted data. CONTEXT is a datagram or connection context. The other parameters correspond to the corresponding values returned from sspi_encrypt.
sspi_decrypt_stream CONTEXT ENCRYPTEDDATA
Returns the decrypted data using the specified stream context. The return value is a pair consisting of a status and the decrypted data. The status may be one of ok, expired, or renegotiate. In all cases the second element, if non empty, contains the decrypted data.

A status of ok is a normal return. If the status is expired, the context has expired and the caller should call sspi_shutdown_context and sspi_delete_context to free the context.
sspi_delete_context CONTEXT
Closes a security context constructed through sspi_client_context or sspi_server_context or and frees any associated resources.
sspi_encrypt CONTEXT BINDATA ?options?
Encrypts the binary data BINDATA based on the specified security context. Returns a list of three elements - the encryption token, the encrypted data and padding. These must all be passed to the remote peer for it successfully decrypt and verify the data.
sspi_encrypt_and_write CONTEXT BINDATA ?options?
Encrypts binary data BINDATA based on the specified security context and writes it to the specified channel. The channel must be in binary mode.
sspi_encrypt_stream CONTEXT BINDATA ?options?
Encrypts BINDATA based on the specified security context and returns the encrypted data.
sspi_enumerate_packages ?options?
If no arguments are specified, returns a list of the names of the security provider packages available on the system. If any options are specified, returns a dictionary keyed by the package name. The corresponding value is itself a dictionary with the keys dependent on the options specified to the command:

-all | Same as all options being specified.
-capabilities | A list of tokens that describe the capabilties of the provider.
-comment | A comment describing the provider.
-rpcid | A DCE RPC identifier, if supported.
-maxtokensize | Maximum size of a security token.
-name | Name of the provider.
-version | The version of the provider interface.

sspi_free_credentials arg CREDENTIALS
Frees resources associated with credentials returned by sspi_acquire_credentials.
sspi_issuers_accepted_by_peer CONTEXT
For SChannel based client contexts, the remote server can request a client certificate issued by specific certificate issuers it will accept. This command returns the list of issuers acceptable to the remote server.
sspi_local_cert CONTEXT
Returns a certificate context for the certificate for the local end of a secured connection. The returned certificate context must be freed by calling cert_release.
sspi_remote_cert CONTEXT
Returns a certificate context for the certificate sent by the remote end of a secured connection. The returned certificate context must be freed by calling cert_release.
sspi_server_context CREDENTIALS CLIENTDATA ?options?
Initiates the building of a new server-side, security context from based on the specified credentials and security data received from the client. CREDENTIALS is a handle to credentials returned by sspi_acquire_credentials. The returned value, which is a handle to a security context, should be treated as opaque by the caller and used as described in SSPI security context establishment.

The options below specify the requirements for the context. Note that not all security providers support all options or combinations of options. Refer to the Windows SDK for more information about these options.

-confidentiality BOOL | If specified as true, messages are to be encrypted.
-connection BOOL | If specified as true, the security context will not handle formatting of messages.
-datarep DATAREP | Specifies the data representation on the target. DATAREP must be either network (default) or native.
-delegate BOOL | If specified as true, the server can use the context to other servers as the client. Requires -mutualauth to also be specified as true.
-extendederror BOOL | When true, the remote end is notified of errors.
-integrity BOOL | If specified as true, messages are to be signed.
-mutualauth BOOL | If specified as true, both the client and server are to be authenticated.
-replaydetect BOOL | If specified as true, detection of replayed messages is desired.
-sequencedetect BOOL | If specified as true, detection of out-of-sequence messages is desired.
-stream BOOL | If specified as true, indicates a stream oriented connection.

When a security context is no longer required, it should be released by calling sspi_delete_context.

sspi_sign CONTEXT DATA ?options?
Generates a signature for DATA based on the supplied security context. Returns a list containing the generated signature and DATA.
sspi_schannel_credentials ?options?
Returns credentials that can be passed to the sspi_acquire_credentials command for SSL/SChannel providers. The credentials are specified through the following options:

-certificates CERTLIST | CERTLIST is a list of certificate context handles with private keys that are used to authenticate the application. Each handle corresponds to a key exchange method supported by the application. On the client end, this need not be specified in which case the provider will find an appropriate certificate if needed.
-cipherstrength CIPHERSTRENGTH | Specifies the strength of the block ciphers to be used in connections using the returned credentials. CIPHERSTRENGTH is list of one or two elements. The first element is the minimum number of bits required in the negotiated encryption key. The second element is the maximum number of bits in the key and defaults to the minimum number of bits if the list contains only one element. A value of 0 indicates a system-specific default to be used. A value of -1 indicates a null cipher (no encryption but with message authentication). This should be used only for debugging purposes.
-protocols PROTOCOLLIST | Specifies the protocols that are acceptable for a connection using the returned credentials. PROTOCOLLIST is a list of one or more of the following: ssl2, ssl3, tls1, tls1.1 and tls1.2. If unspecified, or if PROTOCOLLIST is an empty list, defaults to the list of protocols configured in the system registry.
-rootstore HSTORE | Specifies a handle to an additional certificate root store that contains root certificates to authenticate incoming client connections. This is only used by server applications which need to authenticate clients.
-sessionlifespan MILLISECS | Specifies the number of milliseconds that a Schannel session should be cached. New connections after this time will require a new session. A value of 0 (default) indicates the system-specific default is to be used.

sspi_shutdown_context CONTEXT
Begins the process of shutting down a context. This command is needed, and should be called, only for contexts based on the Schannel based providers. The return value from the command is a pair, the first element of which is the continue, or done. In the former case, the caller should call sspi_step to continue the process of shutting down. In the latter case, the caller can release the context by calling sspi_delete_context. In both cases, the second element contains binary data to be sent to the remote end to complete the shutdown.
sspi_step CONTEXT ?RESPONSE?
Depending on the security provider in use, building a security context may require negotiation with multiple message exchanges between the client and server. This command indicates to the caller whether the negotiation is complete or additional exchange is required. See SSPI security context establishment for an overview of this process.

CONTEXT is a handle to the security context being built. This is the return value from sspi_client_context or sspi_server_context.

The command returns a list containing two or three elements. The first element is a status which may be one of the following values:

done | Indicates that the security context negotiation is completed. The application can use it for cryptographic operations such as signing or encryption.
continue | The security context negotiation is in progress. Additional steps are required in the negotiation process and sspi_step must be called again with additional data received from the remote end.
disconnected | The negotiation is terminated and cannot be used for cryptographic operations. Caller should delete the context using sspi_delete_context.
If the second element of the returned list is not an empty string, it contains data that must be sent to the remote end. This is true for all three cases above.

Finally, the third element of the returned list, if present, contains leftover application data after negotiation is complete (indicated by a status of done). If not empty, it must be passed to the decryption commands. This occurs for stream oriented contexts only (like SSL/TLS).

The command will raise a Tcl exception if the security context negotiation fails for any reason, including authentication failures.

sspi_verify_signature CONTEXT SIGNATURE DATA ?options?
Verifies that the signature SIGNATURE for the supplied data DATA is valid. Generates a Tcl error if the signature is not valid else returns an integer mask that indicates the level of protection (provider dependent).
sspi_winnt_identity_credentials USER DOMAIN PASSWORD
Returns the credentials based on the specified arguments in a format that can be passed to the sspi_acquire_credentials command when NTLM, Kerberos or Negotiate providers are in use. PASSWORD should be in the form described in Password protection.

COPYRIGHT

Copyright © 2007-2013 Ashok P. Nadkarni


SSL/TLS - Transport Layer Security

SSL/TLS

Secure Sockets Layer and Transport Layer Security Channels

SYNOPSIS

package require twapi_crypto

tls_socket ?options? REMOTEADDR PORT
tls_socket -server SERVERCALLBACK ?options? PORT

DESCRIPTION

This module is still experimental and liable to change.

This package provides a Tcl channel facility that implements the Secure Sockets Layer / Transport Layer Security on top of the Windows Security Service Provider Interface (SSPI) interface.

SSL/TLS channels

The module implements a single command, tls_socket, that implements a SSL/TLS based channel which can be used with all Tcl channel based commands like puts, read, chan.

Commands

tls_socket ?options? REMOTEADDR PORT
tls_socket -server SERVERCALLBACK ?options? PORT
The tls_socket command provides the same interface as the Tcl socket command except that the connection runs over TLS or SSL.

The first form is used by client-side applications to connect to a remote server running on port PORT at address REMOTEADDR. The latter form is used by server-side applications to listen for incoming connections on port PORT.

The command options include -server, -myaddr, -myport and -async. Please refer to the Tcl documentation of the socket command for the use of these options.

The tls_socket command supports the following additional options:

-credentials CREDENTIALS | Specifies the credentials to be used for the connection. CREDENTIALS should be credentials returned from a call to sspi_acquire_credentials using the -package unisp option. For client-side connections, this option only needs to be specified when connecting to servers that require clients to be authenticated. For server-side connections, this option is usually required for the connection to complete as most remote clients will require validation of server certificates.
-peersubject PEERNAME | Specifies the subject name to be verified on the remote certificate. Only used for client-side connections to verify the name in the certificate returned by the remote server. If unspecified, defaults to REMOTEADDR. This option is silently ignored for server-side connections.
-verifier VERIFYCOMMAND Specifies a callback to invoke to verify remote credentials. The VERIFYCOMMAND command prefix is invoked with two additional parameters - the channel and a handle to the security context for the connection. If the command returns a true value, the connection is completed. For any other values or errors, the connection is aborted. The callback can retrieve the remote certificate from the passed security context with the sspi_remote_cert command and use cert_tls_verify to validate it.

For client-side connections, if this option is specified and is not empty, automatic verification of the server certificate is not done. For server-side connections, automatic verification of client certificates is never done and must be done through this callback.
The channel returned by tls_socket may be used with any of the Tcl channel commands and supports all channel and socket configuration options. In addition, the following read-only configuration options are supported:

-credentials | Returns the handle to the local credentials for the channel.
-context | Returns the handle to the security context for the channel.
-verifier | Returns the verification callback for the channel.

COPYRIGHT

Copyright © 2013 Ashok P. Nadkarni


Console - Windows console mode

Console

Commands related to Windows consoles

SYNOPSIS

package require twapi_console

allocate_console
clear_console CONOUTH ?-fillchar CHARACTER? ?-windowonly BOOL?
console_read CONINH ?options?
console_write CONOUTH STRING ?options?
create_console_screen_buffer ?options?
fill_console CONOUTH ?options?
flush_console_input CONINH
free_console
generate_console_control_event EVENT ?PROCESSGROUP?
get_console_cursor_position CONOUTH
get_console_handle TYPE
get_console_input_codepage
get_console_input_mode ?CONINH?
get_console_output_mode ?CONOUTH?
get_console_pending_input_count CONINH
get_console_screen_buffer_info CONH ?options?
get_console_title
get_console_window
get_console_window_location CONOUTH
get_console_window_maxsize
get_standard_handle TYPE
modify_console_input_mode CONINH MODEOPTIONS...
modify_console_output_mode CONOUTH MODEOPTIONS...
num_console_mouse_buttons
set_console_active_screen_buffer CONOUTH
set_console_control_handler SCRIPT
set_console_cursor_position CONOUTH XY
set_console_default_attr CONOUTH ?options?
set_console_input_codepage CODEPAGE
set_console_output_codepage CODEPAGE
set_console_screen_buffer_size CONOUTH SCRSIZE
set_console_title TEXT
set_console_window_location CONOUTH RECT ?-absolute BOOL?
set_standard_handle TYPE HANDLE

DESCRIPTION

This module provides commands for manipulating console windows.

Consoles

A console may have multiple processes attached to it. However, a process may be attached to at most one console. Character mode applications are generally started with a console attached. GUI mode processes however do not have a console attached. The command allocate_console may be used to allocate and attach to a console. An allocated console may be released with the free_console command.

Console Handles

The input and screen buffers for a console are identified by handles that can be retrieved through the get_console_handle call. Alternately, the the strings stdin, stdout and stderr may be passed to the various console commands to identify the input, output and error handles. The standard input, output and error handles may be retrieved through the get_standard_handle calls. These may not refer to the console if standard input/output has been redirected.

Console Input

A console is associated with an input buffer that contains input events such as keyboard and mouse inputs. The console can be read through the console_read command. The number of events in the input buffer can be obtained through get_console_pending_input_count and any pending events can be flushed through flush_console_input.

Console input is associated with a specific code page that can be retrieved and set through the get_console_input_codepage and set_console_input_codepage commands.

A console control event may be generated with the generate_console_control_event command. Console control event handlers may be set up with the set_console_control_handler command.

The number of mouse buttons available through the console interface is returned by the num_console_mouse_buttons command.

Console Output

A console may have one or more screen buffers only one of which is active and visible at a time. A screen buffer is a two dimensional array of cells with each cell containing a character and an attribute that controls how the character is displayed. Screen buffers can be written to with the console_write command. The code page used for output can be retrieved and set through the get_console_output_codepage and set_console_output_codepage commands.

Screen buffers can be allocated through create_console_screen_buffer and made to be the active buffer by calling set_console_active_screen_buffer. The size of the buffer can be controlled through the set_console_screen_buffer_size command.

The console window is the portion of the screen buffer that is actually visible on the display. The commands get_console_window_location and set_console_window_location can be used to retrieve and set the location of this window into the screen buffer. The window handle of the console window can be obtained through the get_console_window command. The maximum possible size of the window that can fit on the display given the font can be obtained through get_console_window_maxsize. The title associated with a console window may be retrieved and set through the get_console_title and set_console_title respectively.

The command clear_console clears the screen buffer or a portion of it and can optionally fill it with a specific character.

Characteristics of the screen buffer such as buffer size, cursor position, window coordinates can be obtained through get_console_screen_buffer_info. The position of the cursor can be retrived or set through the commands get_console_cursor_position and set_console_cursor_position respectively.

Console Modes

A console's input and output modes control how characters are handled when when entered and displayed.

Characters typed into a console window may be handled differently based on the input mode of the console. The commands get_console_input_mode, and modify_console_input_mode allow retrieval and setting of the input mode. The various mode settings are specified as arguments to these functions and may contain zero or more of the following elements:

-echoinput BOOL | If true, characters are echoed as they are read in. This is only valid if the -lineinput mode is true.
-extendedmode BOOL | This is automatically set if -quickeditmode or -insertmode are specified.
-insertmode BOOL | If true, characters are inserted as they entered and do not overwrite the characters at the current cursor position.
-lineinput BOOL | If true, calls to read input only return when a carriage return character is read. If false, input is returned without a carraige return character required. Note when multiple characters are typed, they may be returned in a single read or require multiple reads. If this option is specified as false, the -echoinput option must also be specified to be false or be already set to false in the console input mode.
-mouseinput BOOL | If true, mouse events are placed in the input queue when the console window has focus and the mouse is within the window coordinates.
-processedinput BOOL | If true, control characters are handled by the system and not placed in the input queue. If -lineinput is also true, carriage returns, line feeds and tabs are also handled by the system.
-quickeditmode BOOL | If true, allows the user to use the mouse to select and edit text.
-windowinput BOOL | If true, changes in the console window coordinates are reported through the input queue.
In a similar fashion, the characters written to a screen buffer may be displayed differently depending on the output mode of the console. The commands get_console_output_mode, and modify_console_output_mode allow retrieval and setting of the input mode. The various mode settings are specified as arguments to these functions and may contain zero or more of the following elements:

-processedoutput BOOL | If true, characters written to the screen buffer are processed for ASCII control characters - backspace, tab, bell, carriage return, linefeed - and appropriate action taken.
-wrapoutput BOOL | If true, characters written to the screen buffer will wrap around to the next row when the end of row is reached. Otherwise, the last character in the row will be overwritten with characters that extend beyond the width of the row.

Text Attributes

Each cell in a screen buffer has attributes that control the display characteristics of that cell. The default attribute used for writing to the screen buffer can be set through set_console_default_attr.

Text attributes are retrieved and controlled through the following options:

-bgCOLOR BOOL | If true, adds COLOR to the background text color. COLOR may be one of blue, green, red, purple, yellow, gray, or white.
-fgCOLOR BOOL | If true, adds COLOR to the foreground text color. COLOR may be one of blue, green, red, purple, yellow, gray, or white.
-fgbright BOOL | If true, intensifies the foreground color.
-bgbright BOOL | If true, intensifies the background color.
The command fill_console can be used to change the attribute of portions of the screen buffer.

Commands

allocate_console
Allocates a console for the process. If the process already has a console, an error exception is generated.
clear_console CONOUTH ?-fillchar CHARACTER? ?-windowonly BOOL?
If no option are specified, sets the contents of the entire screen buffer to spaces. The -fillchar option may be used to specify a different character to use. If -windowonly is specified as true, only the portion of screen buffer that is visible is cleared.
console_read CONINH ?options?
Reads input from the console. Note that the input is from the console even if standard input has been redirected. options specify the input mode to use and are passed to modify_console_input_mode before input is read. The original mode is restored before returning.
console_write CONOUTH STRING ?options?
Writes the sequence of characters in STRING to the screen buffer identified by CONOUTH. The characters are always written to the screen buffer in raw mode, i.e. as if the -processedoutput mode (see Console Modes) was off. The original mode setting is restored after the write is completed. Note however, that newline characters are treated specially.

In addition, the following options may be specified to alter the behavour of the write.

-newlinemode line|column | If the -newlinemode is set to column (default), a newline character in STRING causes further characters to be written at the original starting column position on the next line. If the option is specified as line, characters after the newline character are written starting at the first column on the next line.
-position COORD | By default, the characters are written starting at the current cursor position. This option may be specified to change the location at which the characters are written. COORD is a list of two integers containing the column and row coordinates of the starting location.
-restoreposition BOOL

create_console_screen_buffer ?options?
Creates a new console screen buffer and returns a handle to it. The following options may be specified:

-inherit BOOL | If true, the returned handle is inheritable by child processes.
-mode read|write|readwrite | Specifies whether the buffer access is read, write or both.
-secd SECURITY_DESCRIPTOR | Specifies a security descriptor to be attached to the screen buffer.
-share none|read|write|readwrite | Specifies whether the buffer is not shared or can be shared for read, write or both (default).
The allocated screen buffer handle should be closed by calling close_handle when no longer needed.

fill_console CONOUTH ?options?
Sets the text attribute of cells in specified area of the screen buffer. The text attributes are specified with one or more of the options described in Text Attributes. The following additional options may also be specified:

-fillchar CHARACTER | Normally, the command does not change the text contents in the specified region. If this option is specified, in addition to changing the attributes in the specified region, the contents of each cell are set to CHARACTER.
-mode line|column | If specified as column (default), the fill region in the second line starts at the same column as the first line. If specified as line, the fill region starts at the first column in the second and subsequent lines.
-numcols INTEGER | Width of the region to be filled. By default, the fill region extends to the rightmost column of the screen buffer.
-numlines INTEGER | Number of rows to be filled. By default, the fill region extends to the rightmost column of the screen buffer.
-position POSITION | Location of the top left corner of the fill region. POSITION is specified as a list of two integers corresponding to the column and row.
-window BOOL | If specified as true, the fill region is the visible window portion of the screen buffer. This option cannot be used with the -position, -numlines and -numrows options.

flush_console_input CONINH
Removes any pending input events from the buffer of the specified input console.
free_console
Frees the console attached to the process.
generate_console_control_event EVENT ?PROCESSGROUP?
Sends a control event to a process group. EVENT should be one of ctrl-c or ctrl-break. PROCESSGROUP indicates the console process group to which the event should be sent. By default, the event is sent to all processes sharing the console of the caller.
get_console_cursor_position CONOUTH
Returns the cursor position in a screen buffer as a list of two integers specifying the column and row that the cursor is to be positioned at. CONOUTH is the handle to the buffer and XY is a list of two integers.
get_console_handle TYPE
Returns a handle to console input, output or error. Note if input and output have been redirected, the handle may not be the same as returned by get_standard_handle. TYPE must be stdin or stdout.
get_console_input_codepage
Returns the input code page of the console.
get_console_input_mode ?CONINH?
Returns the input mode of the console. CONINH is a handle to console input and defaults to stdin. The returned value is a list describing the current mode. See Console Modes for the possible values.
get_console_output_mode ?CONOUTH?
Returns the output mode of the console. CONOUTH is a handle to console output and defaults to stdout. The returned value is a list describing the current mode. See Console Modes for the possible values.
get_console_pending_input_count CONINH
Returns the number of pending input events for the specified console.
get_console_screen_buffer_info CONH ?options?
Retrieves various information about a screen buffer as a flat list of option VALUE pairs. The following options determine what information is returned:

-all | Equivalent to specifying all other options.
-cursorpos | Returns the cursor position in the screen buffer.
-maxwindowsize | Returns the maximum possible size of a window in the screen buffer as a pair of integer corresponding to the width and height. This takes into account the screen buffer size, the display size and the font being used.
-size | Returns a list of two integers containing the number of columns and rows in the screen buffer.
-textattr | Returns the default text attributes used when writing into the screen buffer.
-windowpos | Returns a list of two integers corresponding to the column and row of the top left cell of the window.
-windowsize | Returns a list of two integers containing the number of columns and rows in the window.

get_console_title
Returns the title of the window of the currently attached console.
get_console_window
Returns the handle to the window displaying the currently attached console.
get_console_window_location CONOUTH
Returns a list of four integers containing the left column position, the top row position, the right column position and the bottom row position of the window within the screen buffer.
get_console_window_maxsize
Returns the maximum size of a console window given the current display size and font as a list of two integers corresponding to the width and height. This command does not take into account the size of the screen buffer itself. The -maxwindowsize option of get_console_screen_buffer_info does take into account the screen buffer size.
get_standard_handle TYPE
Returns a handle to standard input, output or error. This may correspond to the console or some other device if the standard devices have been redirected. If the process does not have associated standard handles, an exception is generated with errorCode set to TWAPI_WIN32 2 ERRORMESSAGE. If the returned handle corresponds to a console device, it can be passed to the other console commands. TYPE is one of stdin, stdout, stderr.

Note this command returns a handle to standard input, output and error, which may not be the console if they have been redirected. To retrieve handles to the console, use the get_console_handle function.
modify_console_input_mode CONINH MODEOPTIONS...
Modifies the input modes for the console identified by CONINH according to the mode options specified. MODEOPTIONS must correspond to the input mode options described in Console Modes. Any options not specified are unchanged. The command returns the previous input modes of the console.
modify_console_output_mode CONOUTH MODEOPTIONS...
Modifies the output modes for the console identified by CONOUTH according to the mode options specified. MODEOPTIONS must correspond to the output mode options described in Console Modes. Any options not specified are unchanged. The command returns the previous output modes of the console.
num_console_mouse_buttons
Returns the number of console mouse buttons.
set_console_active_screen_buffer CONOUTH
Sets the active screen buffer of the currently attached console to CONOUTH.
set_console_control_handler SCRIPT
Registers SCRIPT to be invoked when a console application receives one of the control events in the table below. The appropriate event name is appended to SCRIPT before it is invoked. The script should return a non-zero integer value if it has handled the event itself. Any other value returned from the script will result in the event being passed on to other handlers including the operating system default handler.

Calling the command a second time will result in the previous callback script being replaced. So if multiple scripts are to be invoked, the application has to do the chaining itself.

If SCRIPT is empty, the callback handler is unregistered.

In order for the callback scripts to be invoked, the Tcl event loop must be running (through vwait, update etc.). Note that this function should be used only in console applications, not Win32 GUI applications.

The following event names are passed to SCRIPT.

ctrl-c | A Ctrl-C signal was received.
ctrl-break | A Ctrl-Break signal was received.
close | The user requested the console window to be closed.
logoff | The user is logging off.
shutdown | The system is being shut down.

This command requires a threaded build of Tcl and will raise an exception on non-threaded builds.

Only one Tcl interp should register a console control handler. Behaviour with multiple registrations is undefined.

set_console_cursor_position CONOUTH XY
Sets the cursor position in a screen buffer. CONOUTH is the handle to the buffer and XY is a list of two integers specifying the column and row that the cursor is to be positioned at.
set_console_default_attr CONOUTH ?options?
Sets the default attribute to be used when writing to the specified screen buffer. See Text Attributes for a list of valid options.
set_console_input_codepage CODEPAGE
Sets the input code page of the console.
set_console_output_codepage CODEPAGE
Sets the output code page of the console.
set_console_screen_buffer_size CONOUTH SCRSIZE
Sets the size of the specified console screen buffer. SCRSIZE should be a list of two integers containing the width and height of the screen buffer in characters.
set_console_title TEXT
Sets the title of the window of the currently attached console to TEXT.
set_console_window_location CONOUTH RECT ?-absolute BOOL?
Sets the position and size of the visible window within the specified screen buffer. RECT is a list of four integers containing the left column position, the top row position, the right column position and the bottom row position. If option -absolute is true (default), the coordinates are absolute coordinates in the screen buffer. Otherwise, they are relative to the current window coordinates.
set_standard_handle TYPE HANDLE
Redirects standard input, output or error to the specified HANDLE. TYPE is one of stdin, stdout, stderr. HANDLE may be any handle to a device.

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


Desktops and Window stations - Desktop and window stations

Desktops and Window stations

Commands related to desktops and window stations

SYNOPSIS

package require twapi_winsta

close_desktop_handle HDESK
close_window_station_handle HWINSTA
find_desktops ?-winsta WINSTA?
find_window_stations
get_current_window_station_handle
get_desktop_handle DESKTOP ?-inherit BOOL? ?-access ACCESSRIGHTS? ?-allowhooks BOOL?
get_window_station_handle WINDOWSTATION ?-inherit BOOL? ?-access ACCESSRIGHTS?
set_process_window_station HWINSTA

DESCRIPTION

This package provides procedures related to desktops and window stations on Windows platforms.

Window Stations

TBD

Desktops

TBD

Commands

close_desktop_handle HDESK
Closes a desktop handle that was previously returned by a call to get_desktop_handle and frees and associated resources.
close_window_station_handle HWINSTA
Closes a window station handle that was previously returned by a call to get_window_station_handle.
find_desktops ?-winsta WINSTA?
Returns a list of desktops. By default, the desktops from the current window station are returned. The -winsta option may be used to specify a different window station whose id is WINSTA.
find_window_stations
Returns a list of identifiers for all window stations in the system for which the caller has the WINSTA_ENUMERATE privilege.
get_current_window_station_handle
Returns a handle to the window station for the calling process. This handle need not (and should not) be closed.
get_desktop_handle DESKTOP ?-inherit BOOL? ?-access ACCESSRIGHTS? ?-allowhooks BOOL?
Returns a handle to the specified desktop.

The -inherit option determines whether the returned handle will be inherited by child processes. This is false by default.

The access rights associated with the handle default to generic_read unless the -access option is specified. ACCESSRIGHTS specifies the desired access rights and may be specified as a list of integer access rights flags or symbols as described in Access Rights.

If the option -allowhooks is specified as true, processes running in other accounts on the desktop will be allowed to set hooks in the calling process.

When no longer needed, the returned handle should be closed with a call to to close_desktop_handle.
get_window_station_handle WINDOWSTATION ?-inherit BOOL? ?-access ACCESSRIGHTS?
Returns a handle to the window station identified by WINDOWSTATION.

The access rights associated with the handle default to generic_read unless the -access option is specified. ACCESSRIGHTS specifies the desired access rights and may be specified as a list of integer access rights flags or symbols as described in Access Rights.

The -inherit option determines whether the returned handle will be inherited by child processes. This is false by default.

When no longer needed, the returned handle should be closed with a call to to close_window_station_handle.
set_process_window_station HWINSTA
Assigns the window station identified by HWINSTA to the calling process. HWINSTA should be a window station handle previously returned by get_window_station_handle. See the description of SetProcessWindowStation in the Windows SDk for more details.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Task Scheduler - Windows task scheduler

Task Scheduler

Commands related to the Windows task scheduler

SYNOPSIS

package require twapi_mstask

itask_configure ITASK_HANDLE ?options?
itask_delete_itasktrigger ITASK_HANDLE INDEX
itask_edit_dialog ITASK_HANDLE
itask_end ITASK_HANDLE
itask_get_info ITASK_HANDLE ?options?
itask_get_itasktrigger ITASK_HANDLE INDEX
itask_get_itasktrigger_count ITASK_HANDLE
itask_get_itasktrigger_string ITASK_HANDLE INDEX
itask_get_runtimes_within_interval ITASK_HANDLE ?options?
itask_new_itasktrigger ITASK_HANDLE
itask_release ITASK_HANDLE
itask_run ITASK_HANDLE
itask_save ITASK_HANDLE
itaskscheduler_delete_task ITASKSCHEDULER_HANDLE TASKNAME
itaskscheduler_get_itask ITASKSCHEDULER_HANDLE TASKNAME
itaskscheduler_get_target_system ITASKSCHEDULER_HANDLE
itaskscheduler_get_tasks ITASKSCHEDULER_HANDLE
itaskscheduler_new ?-system SYSTEMNAME?
itaskscheduler_new_itask ITASKSCHEDULER_HANDLE TASKNAME
itaskscheduler_release ITASKSCHEDULER_HANDLE
itaskscheduler_set_target_system ITASKSCHEDULER_HANDLE SYSTEMNAME
itaskscheduler_task_exists ITASKSCHEDULER_HANDLE TASKNAME
itasktrigger_configure ITASKTRIGGER_HANDLE ?options?
itasktrigger_get_info ITASKTRIGGER_HANDLE
itasktrigger_release ITASKTRIGGER_HANDLE
mstask_create TASKNAME ?options?
mstask_delete TASKNAME ?options?

DESCRIPTION

This module provides commands for scheduling and running jobs through the Windows task scheduler.

Overview

The Windows task scheduler allows programs to be automatically started at certain times or when certain conditions are met. Tasks may be scheduled on either local or remote computers.

The simplest way to create and delete tasks is through the mstask_create and mstask_delete commands. These take care of acquiring and releasing the low lever interface handles and deal with the common case where a single task trigger is associated with a task.

More flexible and complete task scheduler functionality is available through commands that expose the interface handles to the different types of task scheduler objects. Working with the task scheduler involves three types of objects:

  • The task scheduler service which manages tasks
  • A task which is a unit of work scheduled by the task scheduler and is identified by a name unique to a system.
  • A task trigger which defines the conditions under which a task will be run. A task may have multiple associated task triggers.
An interface to the local or a remote task scheduler is obtained through the itaskscheduler_new command. The returned interface handle can be used to manage tasks on that computer. The commands itaskscheduler_get_target_system and itaskscheduler_set_target_system allow retrieving and changing the system associated with the task scheduler handle at any time.

Once a task scheduler interface handle is obtained, it can be used to access task definitions for that scheduler. The commands itaskscheduler_new_itask and itaskscheduler_get_itask will return interfaces to new and existing tasks which can be manipulated as described below. Tasks can also be deleted through the itaskscheduler_delete_task command and enumerated using itaskscheduler_get_tasks. Existence of a task definition can be verified using the itaskscheduler_task_exists command. (Note: as a general rule, commands related to tasks that require a task interface handle use itask in the command name while commands that require a task name use task.)

Once an interface handle to a task is obtained, its settings can be accessed and modified through the itask_get_info and itask_configure commands. Any changes made must be saved by then calling the itask_save command. Alternately, itask_edit_dialog may be used to display a dialog that allows the user to configure a task.

In addition to scheduling through the task scheduler, task execution can also be directly controlled. itask_run will immediately run a task while itask_end will terminate a task that is currently executing. Future times when a task will be run can be obtained using the itask_get_runtimes_within_interval call.

Each task is associated with zero or more task triggers that determine when and under what conditions the task is executed. The commands itask_new_itasktrigger and itask_get_itasktrigger return interface handles to new or existing task triggers. When not required triggers can be deleted through itask_delete_itasktrigger. The number of triggers associated with a task can be obtained through the itask_get_itasktrigger_count command. itask_get_itasktrigger_string returns a string describing the trigger.

Once a handle to a trigger is obtained, its settings can be retrieved and modified through the itasktrigger_get_info and itasktrigger_configure commands respectively.

Commands

itask_configure ITASK_HANDLE ?options?
Modifies the settings for the task associated with the handle ITASK_HANDLE. Note that the command itask_save must be called to save the changes.

The following options may be specified to change the settings for the task:

-account USERNAME | Sets USERNAME as the account under which the task will be run. If USERNAME is specified as the empty string, the task will be run under the system account. If any user other than the system account is specified, the -password option must also be specified.
-application PATH | Sets the application to be executed to PATH.
-comment COMMENT | Sets the comment for the task.
-creator NAME | Sets the task's creator name.
-data BINDATA | Stores BINDATA as the application-defined data for the task. BINDATA is treated as binary data.
-deletewhendone BOOLEAN | If specified as true, the task will be automatically deleted from the task scheduler when it has no more scheduled run times. Default is false.
-disabled BOOLEAN | If specified as true, the task is disabled and will not be run at its scheduled times. Default is false.
-dontstartonbatteries BOOLEAN | If specified as true, the task is not started at the scheduled time if the system is running on batteries. Default is false.
-hidden BOOLEAN | If specified as true, the task is hidden. Default is false.
-idlewait MINUTES | Sets the number of minutes that the system must be idle before the task runs.
-idlewaitdeadline MINUTES | Sets the maximum number of minutes that the task scheduler will wait for the system to become idle.
-killifonbatteries BOOLEAN | If specified as true, the task is not terminated if if the system is switches to batteries while the task is running. Default is false.
-killonidleend BOOLEAN | If specified as true, the task is terminated, if running, when the computer switches to a non-idle state (i.e. receives user input). Default is false.
-maxruntime MILLISECONDS | Sets the maximum time (in milliseconds) the application can run before it is terminated. If MILLISECONDS is specified as -1, there is no limit on the run time.
-params PARAMSTRING | Sets PARAMSTRING as the parameters to be passed to the application when the task is run.
-password PASSWORD | Specifies PASSWORD as the password associated with the user account specified with the -account option. PASSWORD should be in encrypted form as returned by by the read_credentials or conceal commands.
-priority PRIORITY | Sets the priority for the process executing the task. PRIORITY must be one of normal, abovenormal, belownormal, high, realtime, or idle.
-resumesystem BOOLEAN | If specified as true, the system will be awakened from a suspended state, if necessary, at the task's scheduled time. Default is false.
-restartonidleresume BOOLEAN | If specified as true, the task is restarted when the system goes into an idle state and the task had been previously terminated when the system went into a non-idle state. Default is false.
-runonlyifloggedon BOOLEAN | If specified as true, the task is only run if the user specified through the -account option is logged on. Default is false.
-startonlyifidle BOOLEAN | If specified as true, the task is only run if the system is idle at the task's scheduled run time. Default is false.
-workingdir PATH | Sets PATH as the working directory when the task is executed.

itask_delete_itasktrigger ITASK_HANDLE INDEX
Deletes the task trigger at position INDEX in the list of triggers for the task associated with handle ITASK_HANDLE.
itask_edit_dialog ITASK_HANDLE
Displays a dialog that allows the user to edit the task properties. Note that the dialog is modal and will lock out other windows until it is closed.
itask_end ITASK_HANDLE
Terminates (forcibly if necessary) the task associated with handle ITASK_HANDLE it it is running.
itask_get_info ITASK_HANDLE ?options?
Returns the settings for the task associated with handle ITASK_HANDLE. Any of the options described in itask_configure, except -password, may be specified to retrieve the corresponding setting. In addition, the command supports the following additional options:

-all | Returns all settings.
-lastruntime | Returns the last time that the task was run in the format Year-Month-Day Hour:Minutes:Seconds. (Note the month must be specified numerically.) An empty string is returned if the task has not been run yet.
-nextruntime | Returns the next time that the task is scheduled to run in the format Year-Month-Day Hour:Minutes:Seconds. (Note the month must be specified numerically.) The return value may also be one of disabled if the task is disabled, notriggers if no triggers are defined for it, or oneventonly if the task is configured to run on events as opposed to time.
-status | Returns the status of the task which is one of ready, running, disabled, partiallydefined, or unknown.

itask_get_itasktrigger ITASK_HANDLE INDEX
Returns an interface handle for an existing task trigger for the task associated with the handle ITASK_HANDLE. INDEX is the index of the trigger in the list of triggers defined for the task. When no longer required, the returned handle must be released by calling itasktrigger_release.
itask_get_itasktrigger_count ITASK_HANDLE
Returns the number of task triggers defined for the task associated with handle ITASK_HANDLE.
itask_get_itasktrigger_string ITASK_HANDLE INDEX
Returns a string description for an existing task trigger for the task associated with the handle ITASK_HANDLE. INDEX is the index of the trigger in the list of triggers defined for the task.
itask_get_runtimes_within_interval ITASK_HANDLE ?options?
Returns a list of times that the task is scheduled to run within a specified interval. Each item in the list is in the format Year-Month-Day Hour:Minutes:Seconds. The following options may be specified:

-count COUNT | The maximum number of time elements to return. COUNT must be less than 1440. The actual number returned may of course be less than COUNT depending on how many times the task is scheduled to run in the specified interval.
-end DATETIMESPEC | The ending time of the interval specified as Year-Month-Day Hour:Minutes:Seconds. By default, this is January 1, 2038. Note the month must be specified numerically.
-start DATETIMESPEC | The starting time of the interval specified as Year-Month-Day Hour:Minutes:Seconds. By default, this is the current time. Note the month must be specified numerically.
-statusvar VARNAME | If specified, VARNAME in the caller's context is set to the status of the call. This is success to indicate successful retrieval of the scheduled times. Otherwise, it may also be be one of disabled if the task is disabled, notriggers if no triggers are defined for it, or oneventonly if the task is configured to run on events as opposed to time. In all these three cases, the return value of the command is an empty list.

itask_new_itasktrigger ITASK_HANDLE
Creates a new task trigger for the task associated with the handle ITASK_HANDLE. The command returns a list of two elements. The first is the index of the newly created trigger in the list of triggers defined for the task. The second element is an interface handle to the newly defined task trigger. When no longer required, this must be released by calling itasktrigger_release.
itask_release ITASK_HANDLE
Releases resources associated with a task handle.
itask_run ITASK_HANDLE
Runs the task associated with handle ITASK_HANDLE.
itask_save ITASK_HANDLE
Saves any changes that have been made to the task associated with handle ITASK_HANDLE.
itaskscheduler_delete_task ITASKSCHEDULER_HANDLE TASKNAME
Deletes an existing task with name TASKNAME from the task scheduler associated with the handle ITASKSCHEDULER_HANDLE.
itaskscheduler_get_itask ITASKSCHEDULER_HANDLE TASKNAME
Returns an interface handle to an existing task with name TASKNAME. ITASKSCHEDULER_HANDLE is an interface handle to a task scheduler instance returned by itaskscheduler_new. The returned handle must be released by calling itask_release when it is no longer required.
itaskscheduler_get_target_system ITASKSCHEDULER_HANDLE
Returns the name of the system that the task scheduler associated with the handle ITASKSCHEDULER_HANDLE operates on.
itaskscheduler_get_tasks ITASKSCHEDULER_HANDLE
Returns a list of the names of the tasks contained in the task scheduler associated with the handle ITASKSCHEDULER_HANDLE.
itaskscheduler_new ?-system SYSTEMNAME?
Returns an interface handle to the task scheduler on the local system, or if the -system option is specified, on a remote system. The returned handle must be released by calling itaskscheduler_release when it is no longer required.
itaskscheduler_new_itask ITASKSCHEDULER_HANDLE TASKNAME
Creates a new task with name TASKNAME and returns an interface handle to it. ITASKSCHEDULER_HANDLE is an interface handle to a task scheduler instance returned by itaskscheduler_new. The returned handle must be released by calling itask_release when it is no longer required.
itaskscheduler_release ITASKSCHEDULER_HANDLE
Releases resources associated with a task scheduler handle returned by itaskscheduler_new.
itaskscheduler_set_target_system ITASKSCHEDULER_HANDLE SYSTEMNAME
Sets the task scheduler associated with the handle ITASKSCHEDULER_HANDLE to be the system identified by SYSTEMNAME.
itaskscheduler_task_exists ITASKSCHEDULER_HANDLE TASKNAME
Returns true if a new task with name TASKNAME exists in the task scheduler associated with handle ITASKSCHEDULER_HANDLE.
itasktrigger_configure ITASKTRIGGER_HANDLE ?options?
Configures the task trigger associated with the handle ITASKTRIGGER_HANDLE.

The following options may be specified to configure the task trigger:

-begindate DATESPEC | Specifies the date on which the trigger is activated. DATESPEC must be in the format YEAR-MONTH-DAY. Defaults to the current date.
-daysofmonth MONTHDAYMASK | Specifies the days of the month that the task is scheduled to run. MONTHDAYMASK is a bitmask with the low order bit corresponding to the first day of the month. This option only has effect if the value of the -type option is monthlydate.
-disabled BOOLEAN | If specified as true, disables the trigger so it has no effect. Default is false.
-duration MINUTES | Specifies the number of minutes after the task starts that the trigger is active. The task will be continuously restarted during this period with the interval between starts given by the option -interval.
-enddate DATESPEC | Specifies the date on which the trigger becomes inactive. DATESPEC must be in the format YEAR-MONTH-DAY. If DATESPEC is the empty string, there is no end date and the trigger never becomes inactive. This is also the default.
-interval MINUTES | See description of -duration.
-killatdurationend BOOLEAN | If specified as true, the task is terminated if it is still running at the end of the trigger duration. Default is false.
-months MONTHMASK | Specifies the months in which the trigger is active. MONTHMASK is a bitmask with the low order bit corresponding to January. The trigger is active in those months for which the corresponding bit is set. By default, the trigger is active for all months. This option is only used if the -type option specifies the trigger type to be either monthlydate or monthlydow.
-period PERIOD | If -type is daily, PERIOD is the number of days between invocations of the task. Similarly, if -type is weekly, PERIOD is the number of weeks between invocations of the task. This option is not used for other trigger types. If unspecified, this option defaults to 1.
-starttime TIMESPEC | Specifies the time at which the task is to be run. TIMESPEC is of the form HOUR:MINUTES.
-type TRIGGERTYPE Specifies the type of the trigger. If TRIGGERTYPE is once, the task will only be run once.

A value of daily or weekly will cause the task to be scheduled daily or weekly respectively. In both cases, the interval between runs being governed by the -period option. Furthermore, in the weekly case, the option -weekdays will control which days of the week the task is run.

If TRIGGERTYPE is monthlydate, the task will be scheduled for the days defined by the -months and -daysofmonth options.

A value of monthlydow allows the task to be scheduled during a specific week of a month. The -weekofmonth option specifies which week of the month, the -weekdays option specifies which days in that week, and -months option specifies which months are included.

In addition, there are three trigger types that are event based - if TRIGGERTYPE is onidle, the trigger is activated when the system becomes idle, atsystemstart causes the task to run every time the system starts and atlogon causes it to run everytime the user logs on.
-weekdays WEEKMASK | Specifies the days of a week that the trigger should be activated. WEEKMASK is a bitmask corresponding to days of the week with the low order bit corresponding to Sunday. This option is only used if -type is specified as weekly or monthlydow.
-weekofmonth WEEKNUMBER | Specifies the week of the month that a task should be active. WEEKNUMBER must be an integer in the range 1-5 where 1-4 correspond to the first four weeks while a value of 5 corresponds to the last week of the month.

itasktrigger_get_info ITASKTRIGGER_HANDLE
Returns the settings for the task trigger associated with the handle ITASKTRIGGER_HANDLE. The settings are returned as a flat list of option value pairs. See itasktrigger_configure for information about the returned fields. Note that the returned fields depend on the trigger type as noted there.
itasktrigger_release ITASKTRIGGER_HANDLE
Releases resources associated with a task trigger handle.
mstask_create TASKNAME ?options?
This is command is a wrapper around that the various task scheduler interfaces that allows for easy creation of a task. It handles the common case where a task has a single associated trigger.

The command creates a new task based on the specified options. It accepts all the task related options as described for the itask_configure command. It associates a single trigger with the task and accepts all task trigger configuration options described for task triggers in itasktrigger_configure except for -disabled.

In addition, the command accepts the option -system which allows specification of which system the task is to be created on. By default, the task is created on the local system.
mstask_delete TASKNAME ?options?
This is command is a wrapper around that the various task scheduler interfaces that allows for easy deletion of a task. TASKNAME is the name that identifies the task.

The command accepts the option -system which allows specification of which system the task is to be deleted. By default, the task is deleted on the local system.

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


Resources - Resource handling

Resources

Commands related to Windows file resources

SYNOPSIS

package require twapi_resource

begin_resource_update MODULEPATH ?-deleteall?
delete_resource HMODULE RESTYPE RESNAME LANGID
end_resource_update HMODULE ?-discard?
enumerate_resource_languages HMODULE RESTYPE RESNAME
enumerate_resource_names HMODULE RESTYPE
enumerate_resource_types HMODULE
extract_resources HMODULE ?INCLUDEDATA?
free_bitmap HBITMAP
free_cursor HCURSOR
free_icon HBITMAP
get_file_version_resource PATH ?options? ?STRINGNAME...?
load_bitmap_from_file PATH ?options?
load_bitmap_from_module HMODULE NAME ?options?
load_bitmap_from_system NAME ?options?
load_cursor_from_file PATH ?options?
load_cursor_from_module HMODULE NAME ?options?
load_cursor_from_system NAME ?options?
load_icon_from_file PATH ?options?
load_icon_from_module HMODULE NAME ?options?
load_icon_from_system NAME ?options?
read_resource HMODULE RESTYPE RESNAME LANGID
read_resource_string HMODULE STRINGID LANGID
resource_stringblock_to_strings BINDATA
resource_stringid_to_stringblockid STRINGID
strings_to_resource_stringblock STRINGS
update_resource HMODULE RESTYPE RESNAME LANGID RESDATA

DESCRIPTION

Windows resources are binary data that can be added to executable files. Examples include icons, strings and fonts. This module provides commands related to manipulation of these resources.

Windows Resources

Resources are stored in Portable Executable format files (exe's and dll's). A resource has an associated name, type and a language. The name and type can be either integer values or strings. To retrieve a particular resource, you must know both the associated values, the type and the name, for that resource. When a resource type or name is a string, it must be explicitly enclosed in quotes. For example,

::twapi::read_resource $h 14 {"ICON3"} 0

and not

::twapi::read_resource $h 14 "ICON3" 0

or

::twapi::read_resource $h 14 ICON3 0

To support localization, there can be several resources with the same type and name, but associated with different languages. These languages are identified by a 16 bit language identifier (LANGID) as described in the TWAPI Internationalization documentation.

TWAPI provides commands to retrieve and update resources as binary data. It does not provide any functionality related to constructing the actual binary data itself. Each resource type has a specific structure and it is up to the application to construct it appropriately.

In addition to the commands to load resources as binary data, TWAPI also provides commands to load certain resource types - icons, cursors and bitmaps - as GDI objects accessed through handles by other functions in the Windows API.

The get_file_version_resource command can be used to directly retrieve various information stored within the version resource of a file without using the lower level resource manipulation commands.

Resource Types

Windows defines certain standard resource types shown in the table below along with the corresponding #define values from the SDK.

1 | RT_CURSOR - Cursor
2 | RT_BITMAP - Bitmap
3 | RT_ICON - Icon
4 | RT_MENU - Menu
5 | RT_DIALOG - Dialog
6 | RT_STRING - String (see String Resources)
7 | RT_FONTDIR - Font directory
8 | RT_FONT - Font
9 | RT_ACCELERATOR - Accelerator
10 | RT_RCDATA - Application defined raw data
11 | RT_MESSAGETABLE - Message table
12 | RT_GROUP_CURSOR - Hardware independent cursor
14 | RT_GROUP_ICON - Hardware independent icon
16 | RT_VERSION - Version
17 | RT_DLGINCLUDE - Name of C include file containing corresponding symbolic names of resources
19 | RT_PLUGPLAY - Plug and play
20 | RT_VXD - Vxd
21 | RT_ANICURSOR - Animated cursor
22 | RT_ANIICON - Animated icon
23 | RT_HTML - HTML
24 | RT_MANIFEST - Executable Manifest

Locating and Loading Resources

Manipulating a resource requires a Windows executable module handle for the corresponding executable file. The commands will accept NULL or 0 for this handle corresponding the the main executable for the process. To retrieve resources in other executables or DLL's, the module must be first loaded through the load_library call. Generally, the -datafile option should be passed to the load_library command if the only purpose is to access or update resources.

When the resources in a module are no longer required, it must be released through free_library call.

Once the module is loaded, the content of a particular resource can be retrieved using read_resource and read_resource_string.

You can also enumerate resources present in a module using the enumerate_resource_types enumerate_resource_names enumerate_resource_languages commands. The entire resource tree can be enumerated, optionally retrieving the resource values, through the command extract_resources.

Note that resources themselves do not need to be explicitly freed up. In particular, do not try to close the resource handles through the CloseHandle or close_handles.

Updating Resources

Updating a resource in a file requires that the file not be in use by any application (including the current process). The begin_resource_update command prepares the file for update. One or more update_resource commands can be used to modify the resources in the file and delete_resource commands can be used to delete resources. Finally, the the end_resource_update command is used to commit or discard the modifications.

String Resources

Strings defined through a string table definition in a resource definition file are not directly stored in the resource binary. They are stored in string blocks, each containing 16 strings. It is therefore not possible to directly retrieve or update a string based on its string id.

If you call read_resource with a resource type of 6 (STRING), the resource name or id has to actually be the id of the string block, not the string. The command resource_stringid_to_stringblockid will take a string id and return a pair consisting of the id of the corresponding block and the index of the string within the block. The block id can be passed to read_resource to read the string block. Since this is in binary format, it needs to be converted into a list of strings using resource_stringblock_to_strings. The string index returned from resource_stringid_to_stringblockid can be used to then pick out the appropriate string from the this list.

If you are only interested in a single string, the command read_resource_string encapsulates this entire process.

Updating strings in a resource involves multiple steps for the same reason. First, the string block has to be retrieved and converted to a list of strings as described above. The list must then be modified as desired and converted back to a string block using strings_to_resource_stringblock and then written out using update_resource.

Deleting a string resource is similar. Once the list of strings in the appropriate block is retrieved, set the corresponding element in the list to an empty string before writing it back using update_resource.

A peculiarity in the storage format for resource strings means it is not always possible to distinguish between a resource string that is not defined and a resource string that is defined with an empty value. An attempt to read an undefined resource string may either result in an error being generated, or in the return of an empty string.

Loading Resources as GDI objects

TWAPI also provides commands to load some resource types as GDI objects whose handles are opaque but can be passed to other commands in the Windows API. These include the commands load_icon_from_file, load_cursor_from_file, load_bitmap_from_file, load_icon_from_module, load_cursor_from_module, load_bitmap_from_module, load_icon_from_system, load_cursor_from_system and load_bitmap_from_system.

The handles returned by the above commands may be shared or unshared (as described in the documentation for the specific command). Unshared handles must be freed using free_icon, free_cursor and free_bitmap respectively. Shared handles are automatically freed by the system and must not be passed to the free commands.

The commands to load these GDI objects share a common set of options:

-createdibsection BOOLEAN | If true, returns a DIB section bitmap instead of a compatible bitmap. Default is false. This option is only valid for bitmap resources.
-defaultsize BOOLEAN | If false (default) and options -height and -width are not specified or specified as 0, Windows will use the actual resource size. If true, Windows will use the system metric settings. This option is only valid for cursors and icons.
-height INTEGER | Specifies the desired height of the icon or cursor. Default value is 0 in which case the width is controlled by the -defaultsize option.
-loadtransparent BOOLEAN | If specified as true, the color of the first pixel is replaced with the default window color. Should be used only if the color depth is 8 bpp or less. Default is false.
-monochrome BOOLEAN | If specified as true, returns a monochrome image. Default is false.
-vgacolor BOOLEAN | If true, uses VGA color.
-width INTEGER | Specifies the desired width of the icon or cursor. Default value is 0 in which case the width is controlled by the -defaultsize option.

Commands

begin_resource_update MODULEPATH ?-deleteall?
Returns a handle to the file MODULEPATH to be updated. The returned handle must be closed through the end_resource_update command. If the option -deleteall is specified, all existing resources in the file are deleted.
delete_resource HMODULE RESTYPE RESNAME LANGID
Deletes a resource from the specified module HMODULE which must be a handle previously retrieved via begin_resource_update. The resource is not actually deleted from the file until the end_resource_update command is called.
end_resource_update HMODULE ?-discard?
Closes a handle previously returned by the begin_resource_update command. Any modifications made through update_resource are written to the file unless the -discard option is specified in which case they are discarded.
enumerate_resource_languages HMODULE RESTYPE RESNAME
Returns a list of language identifiers for which the specified module contains a resource of type RESTYPE with name RESNAME. HMODULE must be a handle previously retrieved via load_library.
enumerate_resource_names HMODULE RESTYPE
Returns a list of the names of resources of type RESTYPE in the specified module. HMODULE must be a handle previously retrieved via load_library, get_module_handle, or get_module_handle_from_address.
enumerate_resource_types HMODULE
Returns a list of the types of resources in the specified module. HMODULE must be a handle previously retrieved via load_library.
extract_resources HMODULE ?INCLUDEDATA?
Extracts all resources from the specified module. The returned data is a nested dictionary with the first level key being the resource type, second level key the resource name and the third level key the language identifier.

If INCLUDEDATA is true, the actual binary data for the resource is returned as the value for each nested key. If INCLUDEDATA is not specified or is false, an empty string is returned as the value.
free_bitmap HBITMAP
Frees a bitmap handle and associated resources. The handle must not be for be a shared bitmap.
free_cursor HCURSOR
Frees a cursor handle and associated resources. The handle must not be for be a shared cursor.
free_icon HBITMAP
Frees a icon handle and associated resources. The handle must not be for be a shared icon.
get_file_version_resource PATH ?options? ?STRINGNAME...?
Returns the information stored within the version resource of a file. The command will generate a Tcl error if the file specified by PATH does not contain a version resource.

The version resource consists of two parts. The information in the first part is in a fixed format and can be retrieved by specifying appropriate options in options. The second part is a string table, the entries in which can be retrieved by specifying the key as a STRINGNAME argument.

The following options may be used with the command:

-all | Returns all information in the fixed part.
-datetime | Returns the date and time the file was created (as stored in the version resource) as a 64 bit number. Refer to large_system_time_to_timelist or large_system_time_to_secs_since_1970.
-fileversion | Returns the file version as indicated in the version resource. This is returned in the format MAJOR.MINOR.BUILD.PRIVATE. Note this is not necessarily identical to the value specified for the FileVersion entry in the string table.
-fileos | Returns a value specifying the platform for which the file was designed. This may be one of dos (MS-DOS), os216 (16-bit OS/2), os232 (16-bit OS/2), nt (Windows NT), wince (Windows CE), windows16 (16-bit Windows), pm16 (16-bit Presentation Manager), pm32 (32-bit Presentation Manager), windows32 (32-bit Windows), dos_windows32 (32-bit Windows on MS-DOS), os216_pm16 (16-bit Presentation Manager on 16-bit OS/2), os232_pm32 (32-bit Presentation Manager on 32-bit OS/2) or nt_windows32 (32-bit Windows on Windows NT).
-filetype | Returns the file type which may be one of the following: application, dll, driver.printer, driver.keyboard, driver.language, driver.display, driver.mouse, driver.network, driver.system, driver.installable, driver.sound, driver.comm, driver.inputmethod, driver.versionedprinter, driver.DRIVERSUBTYPENUMBER, font.raster, font.vector, font.truetype, font.FONTSUBTYPENUMBER, vxd.VIRTUALDEVICEID, staticlib or FILETYPENUMBER.FILESUBTYPENUMBER. (Note in cases where the file type or subtype is not recognized, the actual numeric value is returned.)
-flags | Returns a list of symbols corresponding to flags set in the version resource. The list may contain symbols from the following: debug, prerelease, patched, privatebuild, infoinferred and specialbuild. In addition, the list may also contain a numeric value corresponding to bits that are set but are not recognized as one of the above.
-foundcodepage | Returns the code page of the matched string table (see below).
-foundlangid | Returns the language of the matched string table (see below). The returned value is a list of two elements containing the numeric language identifier and a description string for the corresponding language.
-langid LANGID | Specifies LANGID as the language identifier to be used for string table lookup (see below). By default, the language identifier returned by get_user_ui_langid is used.
-codepage CODEPAGE | Specifies CODEPAGE as the code page to be used for string table lookup (see below).
-productversion | Returns the product version as indicated in the version resource. This is returned in the format MAJOR.MINOR.BUILD.PRIVATE. Note this is not necessarily identical to the value specified for the ProductVersion entry in the string table.
-signature | Contains a longword that is a signature for the fixed part of the version resource. Not particularly useful for the application.
-structversion | Returns the version of the version resource format.
In addition to the options that retrieve fixed portions of the version resource, the caller may also specify string names corresponding to language-specific string tables in the version resource. Each such STRINGNAME is looked up in the string table and returned as a STRINGNAME VALUE pair. If a particular string name does not exist in the string table, an empty string is returned as its value. The following string names are commonly defined in version resources: Comments, InternalName, ProductName, CompanyName, LegalCopyright, ProductVersion, FileDescription, LegalTrademarks, PrivateBuild, FileVersion, OriginalFilename, SpecialBuild.

The version resource may contain multiple string tables for different languages and code pages. The caller can control the string table used through the -langid and -codepage options. The command uses the following algorithm in selecting the string table that is looked up.

  • If a string table exactly matches the language id and code page, it is used.
  • Otherwise, if a string table exactly matches the language id, it is used irrespective of the code page.
  • Otherwise, a string table matching the primary language portion of the language id and the code page is used.
  • Otherwise, a string table matching the primary language portion of the language id is used regardless of the code page.
  • Otherwise, a string table specified as language neutral is used.
  • Otherwise, a string table specified as English is used.
  • Finally, the string table corresponding to the first language and code page specified in the resource is used.
The language identifier and code page corresponding to the actual string table that was looked up may be optionally be retrieved by passing the -foundlangid and -foundcodepage to the command.
load_bitmap_from_file PATH ?options?
Returns a handle to a bitmap loaded from a standalone file. The returned bitmap must be freed when no longer needed by calling free_bitmap.

See Loading Resources as GDI objects for a list of valid options.
load_bitmap_from_module HMODULE NAME ?options?
Returns a handle to a bitmap from a resource in a module that has been loaded into the process. The returned bitmap must be freed when no longer needed by calling free_bitmap.

HMODULE is handle to the module as returned by load_library, get_module_handle, or get_module_handle_from_address. NAME is the resource identifier.

See Loading Resources as GDI objects for a list of valid options.
load_bitmap_from_system NAME ?options?
Returns a handle to a bitmap built into Windows. The returned bitmap is a shared bitmap. Applications must not attempt to free it by calling free_bitmap.

NAME must be one of close, uparrow, dnarrow, rgarrow, lfarrow, reduce, zoom, restore, reduced, zoomd, restored, uparrowd, dnarrowd, rgarrowd, lfarrowd, mnarrow, combo, uparrowi, dnarrowi, rgarrowi, lfarrowi, size, btsize, check, checkboxes, btncorners.

See Loading Resources as GDI objects for a list of valid options.
load_cursor_from_file PATH ?options?
Returns a handle to a cursor loaded from a standalone file. The returned cursor must be freed when no longer needed by calling free_cursor.

See Loading Resources as GDI objects for a list of valid options.
load_cursor_from_module HMODULE NAME ?options?
Returns a handle to a cursor from a resource in a module that has been loaded into the process. The returned cursor must be freed when no longer needed by calling free_cursor.

HMODULE is handle to the module as returned by load_library, get_module_handle, or get_module_handle_from_address. NAME is the resource identifier.

See Loading Resources as GDI objects for a list of valid options.
load_cursor_from_system NAME ?options?
Returns a handle to a cursor built into Windows. The returned cursor is a shared cursor. Applications must not attempt to free it by calling free_cursor.

NAME must be one of normal, ibeam, wait, cross, up, sizenwse, sizenesw, sizewe, sizens, sizeall, no, hand or appstarting.

See Loading Resources as GDI objects for a list of valid options.
load_icon_from_file PATH ?options?
Returns a handle to an icon loaded from a standalone file. The returned icon must be freed when no longer needed by calling free_icon.

See Loading Resources as GDI objects for a list of valid options.
load_icon_from_module HMODULE NAME ?options?
Returns a handle to an icon from a resource in a module that has been loaded into the process. The returned icon must be freed when no longer needed by calling free_icon.

HMODULE is handle to the module as returned by load_library, get_module_handle, or get_module_handle_from_address. NAME is the resource identifier.

See Loading Resources as GDI objects for a list of valid options.
load_icon_from_system NAME ?options?
Returns a handle to an icon built into Windows. The returned icon is a shared icon. Applications must not attempt to free it by calling free_icon.

NAME must be one of sample, hand, ques, bang, note, winlogo, warning, error, information or shield.

See Loading Resources as GDI objects for a list of valid options.
read_resource HMODULE RESTYPE RESNAME LANGID
Returns the content of a resource from the specified module HMODULE which must be a handle previously retrieved via load_library.

Note that If RESTYPE is 6, specifying a STRING resource, RESTYPE is the id for a string block, not an individual string. The returned value is the binary data corresponding to the string block. To retrieve individual strings, use the read_resource_string command.
read_resource_string HMODULE STRINGID LANGID
Returns the string in the resource table for the module specified by HMODULE which must be a handle previously retrieved via load_library.

Because of the storage format used in string resources, it is not always possible to distinguish between a resource string that is not defined and a resource string that is defined with an empty value. An attempt to read an undefined resource string may either result in an error being generated, or in the return of an empty string.
resource_stringblock_to_strings BINDATA
Converts a binary resource string block to a list of strings. As every string block contains 16 strings, the returned list as exactly 16 strings.
resource_stringid_to_stringblockid STRINGID
Maps a string resource id to a list containing the id of the corresponding string block in the resource and the index of the string within the block as described in String Resources.
strings_to_resource_stringblock STRINGS
Converts the list of strings in STRINGS to a binary resource string block that can be passed to update_resource. The number of strings in STRINGS must not be more than 16 which is the number stored in a single resource string block. If fewer than 16 strings are provided, they are stored as empty strings.
update_resource HMODULE RESTYPE RESNAME LANGID RESDATA
Updates a resource from the specified module HMODULE which must be a handle previously retrieved via begin_resource_update. RESDATA should be the raw binary data for the resource in the type-specific format.

The resource is not actually written out to the file until the end_resource_update command is called.

COPYRIGHT

Copyright © 2010 Ashok P. Nadkarni


Microsoft Windows Installer - Microsoft Windows Installer support

Microsoft Windows Installer

Commands for accessing Microsoft Windows Installer

SYNOPSIS

package require twapi_msi

cast_msi_object MSICOMOBJ MSITYPE

DESCRIPTION

This module is experimental.

This module provides commands for accessing the Microsoft Windows Installer (MSI) component through its COM interfaces. The primary motivation for this module is that although the Installer provides a COM interface, it cannot be bound and types discovered at run time. This module provides the required type definitions for the various interfaces. These type definitions must be programmatically loaded into a MSI object instance by the application.

Creation and Destruction of MSI objects

MSI objects are created through TWAPI's COM interface commands. The Installer object is created through the command

set msiobj [comobj WindowsInstaller.Installer]

Once an MSI object is no longer needed, it must be deleted like any other COM object.

$msiobj -destroy

Note a final call to $MSIOBJ -destroy is required for all MSI objects, not just the top-level Installer object.

Once an MSI object is created, it must be cast to the appropriate type with the command cast_msi_object before calling any methods on the object.

twapi::load_msi_prototypes $msiobj Installer

cast_msi_object MSICOMOBJ MSITYPE
Loads the type information corresponding to the MSI type MSITYPE into the COM object command MSICOMOBJ. MSITYPE corresponds to one of the object types defined in the Windows Installer Reference: Database, FeatureInfo, Installer, Patch, Product, Record, RecordList, Session, StringList, SummaryInfo, UiPreview and View.

When an object of a MSI type is created, it should be passed to cast_msi_object along with the type before making any method calls on the objects.

COPYRIGHT

Copyright © 2007-2009 Ashok P. Nadkarni


Internationalization - Internationalization

Internationalization

Commands related to internationalization

SYNOPSIS

package require twapi_nls

extract_primary_langid LANGID
extract_sublanguage_langid LANGID
format_currency NUMBER LCID ?options?
format_number NUMBER LCID ?options?
get_locale_info LCID ?options?
get_system_default_langid
get_system_default_lcid
get_system_ui_langid
get_user_default_langid
get_user_default_lcid
get_user_ui_langid
map_code_page_to_name CODEPAGENUM
map_langid_to_name LANGID

DESCRIPTION

This package provides procedures related to internationalization capabilities on Windows platforms.

Locales

A locale defines user preferences related to languages and culture-dependent formatting of numbers, currencies etc.. A locale identifier (LCID) is an integer or one of the keywords systemdefault or userdefault corresponding to the system and user default locales respectively.

The system maintains locale settings for the system as well as the user. These can be retrieved through the commands get_system_default_lcid and get_user_default_lcid respectively.

The command get_locale_info can be used to retrieve the settings associated with a particular locale.

Languages

Languages are identified by a 16 bit integer (LANGID) that includes the primary and sublanguage information. The commands extract_primary_langid and extract_sublanguage_langid may be used to retrieve these from the language identifier.

The system maintains several language settings. These can be retrieved through the commands get_system_default_langid, get_system_ui_langid, get_user_default_langid and get_user_ui_langid. Information related to a LANGID, such as it full name, can be retrieved by passing it to get_locale_info.

Formatting

Windows provides functions for formatting data as per local conventions. The command format_number formats numbers using a given locale as a base and with the ability to override particular format settings.

Commands

extract_primary_langid LANGID
Returns the primary language identifier for the language identifier specified by LANGID.
extract_sublanguage_langid LANGID
Returns the sublanguage identifier for the language identifier specified by LANGID.
format_currency NUMBER LCID ?options?
Formats NUMBER as a currency string per the given formatting specifications. LCID is a locale identifier. NUMBER must be in decimal format (the fractional part is optional) and may have a leading negative sign.

If no options are specified, the settings in the locale identified by LCID are used for formatting NUMBER.

If one or more of the following options are specified, they override the settings in the locale given by LCID.

-icurrency CURRENCYFORMAT | Controls how positive currency numbers are formatted including spacing, position of the currency symbol etc.. See the documentation for LOCALE_ICURRENCY in the Windows SDK for possible values of CURRENCYFORMAT.
-idigits DECIMALPLACES | Indicates the number of digits after the decimal point to include in the result. If specified as -1, the number of decimal places in the result is the same as in NUMBER.
-ilzero BOOLEAN | Specifies whether the result includes leading zeroes (true) or not (false) when NUMBER is a pure fraction.
-inegcurr NEGFORMAT | Controls how negative numbers are formatted including location of the currency symbol, the negative number indicator etc.. See the documentation for LOCALE_INEGCURR in the Windows SDK for possible values of NEGFORMAT.
-scurrency SYMBOL | Specifies that the string SYMBOL should be used as the monetary symbol.
-sdecimal DECIMALSEPARATOR | Specifies the string to be used to represent the decimal point.
-sgrouping GROUPNUM | Specifies the size of each group of digits to the left of the decimal point. GROUPNUM may be any integer between 0 and 9 or the value 32 which indicates the Indic convention of the grouping by the first thousand (3 digits) followed by groups of 2 digits.
-sthousand THOUSANDSEPARATOR | Specifies the string to be used as the thousands' separator.

format_number NUMBER LCID ?options?
Formats the number NUMBER as per the given formatting specifications. LCID is a locale identifier. NUMBER must be in decimal format (the fractional part is optional) and may have a leading negative sign.

If no options are specified, the settings in the locale identified by LCID are used for formatting NUMBER.

If one or more of the following options are specified, they override the settings in the locale given by LCID.

-idigits DECIMALPLACES | Indicates the number of digits after the decimal point to include in the result. If specified as -1, the number of decimal places in the result is the same as in NUMBER.
-ilzero BOOLEAN | Specifies whether the result the result includes leading zeroes (true) or not (false).
-inegnumber NEGFORMAT | Controls how negative numbers are formatted. See the documentation for LOCALE_INEGNUMBER in the Windows SDK for possible values of NEGFORMAT.
-sgrouping GROUPNUM | Specifies the size of each group of digits to the left of the decimal point. GROUPNUM may be any integer between 0 and 9 or the value 32 which indicates the Indic convention of the grouping by the first thousand (3 digits) followed by groups of 2 digits.
-sdecimal DECIMALSEPARATOR | Specifies the string to be used to represent the decimal point.
-sthousand THOUSANDSEPARATOR | Specifies the string to be used as the thousands' separator.

get_locale_info LCID ?options?
Returns a list containing information about the locale identified by LCID. The information returned depends on the options specified and is formatted as a list of the form "option VALUE...".

-ilanguage | language id
-slanguage | localized name of language
-senglanguage | English name of language
-sabbrevlangname | abbreviated language name
-snativelangname | native name of language
-icountry | country code
-scountry | localized name of country
-sengcountry | English name of country
-sabbrevctryname | abbreviated country name
-snativectryname | native name of country
-idefaultlanguage | default language id
-idefaultcountry | default country code
-idefaultcodepage | default oem code page
-idefaultansicodepage | default ansi code page
-idefaultmaccodepage | default mac code page
-slist | list item separator
-imeasure | 0 = metric, 1 = US
-sdecimal | decimal separator
-sthousand | thousand separator
-sgrouping | digit grouping
-idigits | number of fractional digits
-ilzero | leading zeros for decimal
-inegnumber | negative number mode
-snativedigits | native ascii 0-9
-scurrency | local monetary symbol
-sintlsymbol | intl monetary symbol
-smondecimalsep | monetary decimal separator
-smonthousandsep | monetary thousand separator
-smongrouping | monetary grouping
-icurrdigits | # local monetary digits
-iintlcurrdigits | # intl monetary digits
-icurrency | positive currency mode
-inegcurr | negative currency mode
-sdate | date separator
-stime | time separator
-sshortdate | short date format string
-slongdate | long date format string
-stimeformat | time format string
-idate | short date format ordering
-ildate | long date format ordering
-itime | time format specifier
-itimemarkposn | time marker position
-icentury | century format specifier (short date)
-itlzero | leading zeros in time field
-idaylzero | leading zeros in day field (short date)
-imonlzero | leading zeros in month field (short date)
-s1159 | AM designator
-s2359 | PM designator
-icalendartype | type of calendar specifier
-ioptionalcalendar | additional calendar types specifier
-ifirstdayofweek | first day of week specifier
-ifirstweekofyear | first week of year specifier
-sdayname1 | long name for Monday
-sdayname2 | long name for Tuesday
-sdayname3 | long name for Wednesday
-sdayname4 | long name for Thursday
-sdayname5 | long name for Friday
-sdayname6 | long name for Saturday
-sdayname7 | long name for Sunday
-sabbrevdayname1 | abbreviation for Monday
-sabbrevdayname2 | abbreviation for Tuesday
-sabbrevdayname3 | abbreviation for Wednesday
-sabbrevdayname4 | abbreviation for Thursday
-sabbrevdayname5 | abbreviation for Friday
-sabbrevdayname6 | abbreviation for Saturday
-sabbrevdayname7 | abbreviation for Sunday
-smonthname1 | long name for January
-smonthname2 | long name for February
-smonthname3 | long name for March
-smonthname4 | long name for April
-smonthname5 | long name for May
-smonthname6 | long name for June
-smonthname7 | long name for July
-smonthname8 | long name for August
-smonthname9 | long name for September
-smonthname10 | long name for October
-smonthname11 | long name for November
-smonthname12 | long name for December
-smonthname13 | long name for 13th month (if exists)
-sabbrevmonthname1 | abbreviation for January
-sabbrevmonthname2 | abbreviation for February
-sabbrevmonthname3 | abbreviation for March
-sabbrevmonthname4 | abbreviation for April
-sabbrevmonthname5 | abbreviation for May
-sabbrevmonthname6 | abbreviation for June
-sabbrevmonthname7 | abbreviation for July
-sabbrevmonthname8 | abbreviation for August
-sabbrevmonthname9 | abbreviation for September
-sabbrevmonthname10 | abbreviation for October
-sabbrevmonthname11 | abbreviation for November
-sabbrevmonthname12 | abbreviation for December
-sabbrevmonthname13 | abbreviation for 13th month (if exists)
-spositivesign | positive sign
-snegativesign | negative sign
-ipossignposn | positive sign position
-inegsignposn | negative sign position
-ipossymprecedes | mon sym precedes pos amt
-ipossepbyspace | mon sym sep by space from pos amt
-inegsymprecedes | mon sym precedes neg amt
-inegsepbyspace | mon sym sep by space from neg amt
-fontsignature | font signature
-siso639langname | ISO language abbreviation
-siso3166ctryname | ISO country name abbreviation
-idefaultebcdiccodepage | default ebcdic code page
-ipapersize | 1 = letter, 5 = legal, 8 = a3, 9 = a4
-sengcurrname | english name of currency
-snativecurrname | native name of currency
-syearmonth | year month format string
-ssortname | sort name
-idigitsubstitution | 0 = context, 1 = none, 2 = national

get_system_default_langid
Returns the default language identifier for the system.
get_system_default_lcid
Returns the default locale identifier for the system.
get_system_ui_langid
Returns the language identifier for the system default UI language.
get_user_default_langid
Returns the default user language identifier.
get_user_default_lcid
Returns the default user-locale identifier.
get_user_ui_langid
Returns the language identifier for the user's UI language.
map_code_page_to_name CODEPAGENUM
Returns the name of the code page identified by CODEPAGENUM.
map_langid_to_name LANGID
Returns the name of the language identified by LANGID.

COPYRIGHT

Copyright © 2005-2009 Ashok P. Nadkarni


Performance Counters - Performance Counters

Performance Counters

Commands related to retrieving performance counters

SYNOPSIS

package require twapi_pdh

pdh_add_counter HPERF CTRPATH ?options?
pdh_counter_path PERFOBJ CTRNAME ?options?
pdh_enumerate_objects ?options?
pdh_enumerate_object_counters PERFOBJ ?options?
pdh_enumerate_object_instances PERFOBJ ?options?
pdh_enumerate_object_items PERFOBJ ?options?
pdh_get_array HCOUNTER ?options?
pdh_get_scalar HCOUNTER ?options?
pdh_parse_counter_path CTRPATH
pdh_query_close HPERF
pdh_query_get HPERF ?NAME1 NAME2....?
pdh_query_open
pdh_query_refresh HPERF
pdh_remove_counter HPERF CTRNAME
pdh_system_performance_query ?CTRNAME ....?

DESCRIPTION

This package provides procedures related to retrieving Windows performance counters.

Performance Objects

To get a list of performance objects on a system, call pdh_enumerate_objects. Commands pdh_enumerate_object_counters, pdh_enumerate_object_instances and pdh_enumerate_object_items return the counters and instances for a particular performance object.

Counter Paths

Similar to files in a file system, performance counters are identified by a counter path. A counter path is of the form

\\Computer\PerfObject(ParentInstance/ObjectInstance#InstanceIndex)\Counter

Not all components in a counter path need to be specified. See Windows SDK documentation for a detailed description and examples. Note that \ and / are not interchangeable in a counter path

To construct a counter path, call pdh_counter_path. The break down a counter path into its components, call pdh_parse_counter_path.

Retrieving Counter Values

To retrieve values for a counter, use the following sequence of commands

pdh_query_open | Opens a query object to which counters can be added.
pdh_counter_path | Constructs a counter path for the performance object and instance of interest. Call for each counter of interest.
pdh_add_counter | Adds a counter (specified by its counter path as returned in the previous step) to a query and returns a handle to it. Call for each counter of interest.
pdh_query_refresh | Updates all counters in the query to their current values. For rate based counters, this must be called at least twice before retrieving the value of a counter.
pdh_get_scalar | Returns the scalar value of a counter as updated in the last call to pdh_query_refresh.
pdh_get_array | Returns a counter that is an array of values (for example, one for each process) as updated in the last call call to pdh_query_refresh.
pdh_query_get | Returns values for multiple counters from a query. Internally does the equivalent of pdh_query_refresh.
pdh_query_close | Closes a query. This should be called to release resources associated with a query once the contained counters are no longer required.
The pdh_system_performance_query is a wrapper around pdh_query_open that includes some commonly used system counters.

set queryh [pdh_system_performance_query processor_utilization memory_free_kb]
proc print_counters {queryh} {
    pdh_query_refresh $queryh
    puts [pdh_query_get $queryh]
    after 1000 [info level 0]
}
print_counters $queryh
vwait forever

Commands

pdh_add_counter HPERF CTRPATH ?options?
Adds a counter specified by its path CTRPATH to a performance query. HPERF is a query handle previously returned by pdh_query_open. CTRPATH is a counter path normally constructed through pdh_counter_path. Subsequent calls to pdh_query_refresh for that query will update the counter.

The command returns a handle to the counter which can then be passed to pdh_get_scalar or pdh_get_array to retrieve its value. Alternatively, the pdh_query_get command can be used to get values of multiple counters from a query.

The counter is automatically released when the query is closed. However, if a counter is no longer required while the other counters in the query are still in use, it can be removed from the query by calling pdh_remove_counter.

The following options may be specified with the command. They impact how values from the counter are returned from the pdh_query_get command.

-array BOOLEAN | If true ,the counter is treated as an array of values. If false (default), it will be returned as a scalar.
-format FORMAT | Specifies how the counter value should be formatted. FORMAT may be on of long, large or double for a 32-bit integer, a 64-bit integer or a floating point double.
-name NAME | Specifies the mnemonic name by which the counter will be identified when multiple counter values are retrieved with pdh_query_get. If unspecified, defaults to the full counter path CTRPATH.
-scale SCALE | By default, each counter has a default scaling factor. If SCALE is none, the counter value is returned without the default scaling. If SCALE is x1000, the returned value is scaled up by a factor of 1000. If SCALE is nocap100, the counter value is not capped at 100 as is the scale for some counters like processor utilization.

pdh_counter_path PERFOBJ CTRNAME ?options?
Returns a path to a performance counter that can then be passed to pdh_add_counter. PERFOBJ should be the name of the performance object, such as TCPv4. CTRNAME should be the name of the performance counter in the object, such as Connection Failures. The following additional options may be passed:

-instance INSTANCE | When there are many instances of a performance object, as is true for the Process object for example, this option allows specification of a particular instance by specifying its name as INSTANCE. Many performance objects allow INSTANCE to be specified as * to indicate counters for all instances are to be returned.
-instanceindex INSTANCEINDEX | When there is more than one instance of a performance object with the same name, this option allows selection of a particular one by specifying its numeric instance index.
-localized BOOLEAN | Performance object and counter names are localized based on the system languages. Using Process as the object name on a French localized system will result in a failure. By default the command assumes the passed names are in English and localizes them for the local system. If -localized is passed as true, the command assumes that the names being passed are already appropriately localized.
-parent PARENTINSTANCE | Some performance objects, like Thread, are contained within another parent object, Process in the case of Thread. In such cases PARENTINSTANCE specifies the context for the target object.
See Windows SDK documentation for more details on counter path syntax and components.

pdh_enumerate_objects ?options?
Returns a list of the names of the performance objects on a system. The following options may be specified:

-detail DETAILLEVEL | Controls which detail levels are to be returned. DETAILLEVEL may be one of novice, advanced, expert and wizard (default) which return performance objects at an increasing level of detail.
-refresh | The list of performance objects is returned from a cache. Performance objects may be added by any application at any time. Specifying -refresh causes the cache to be refreshed before being returned.

pdh_enumerate_object_counters PERFOBJ ?options?
Returns a list of the names of counters present in the performance object PERFOBJ. See pdh_enumerate_object_items for valid options.
pdh_enumerate_object_instances PERFOBJ ?options?
Returns a list of the names of instances of the performance object PERFOBJ. The list may be empty if the object supports instances but none are present. The command raises an error if PERFOBJ does not support instances at all. See pdh_enumerate_object_items for valid options.
pdh_enumerate_object_items PERFOBJ ?options?
Returns a list of one or two elements, the first being a list of counter names for the performance object PERFOBJ. If the performance object does not support instances, the returned list contains only that element. Otherwise, the second element is the list of instance names for object. This may be empty in the case the performance object supports instances but none are present. The following options may be specified:

-detail DETAILLEVEL | Controls which detail levels are to be returned. DETAILLEVEL may be one of novice, advanced, expert and wizard (default) which return performance objects at an increasing level of detail.
-refresh | The list of performance objects is returned from a cache. Performance objects may be added by any application at any time. The command will fail if PERFOBJ is not in the cache. Specifying -refresh causes the cache to be refreshed before attempting to access the information for PERFOBJ.

pdh_get_array HCOUNTER ?options?
Returns a flat list of instance name and value pairs for a counter that covers multiple objects, such as one containing wildcards. Refer to pdh_get_scalar for options.

Note that the command does not refresh the counter value. Caller must do that with pdh_query_refresh before calling this command if so desired.
pdh_get_scalar HCOUNTER ?options?
Returns the value of the specified counter as of the last call to pdh_query_refresh. HCOUNTER is a handle to a counter as returned by a prior call to pdh_add_counter. If the counter was specified using a wildcard, use pdh_get_array instead to retrieve multiple values for all matching instances.

The following options may be specified:

-format FORMAT | Specifies how the counter value should be formatted. FORMAT may be on of long, large or double for a 32-bit integer, a 64-bit integer or a floating point double.
-scale SCALE | By default, each counter has a default scaling factor. If SCALE is none, the counter value is returned without the default scaling. If SCALE is x1000, the returned value is scaled up by a factor of 1000. If SCALE is nocap100, the counter value is not capped at 100 as is the scale for some counters like processor utilization.
-var VARNAME | Specifies VARNAME as the name of a variable in the caller's context where the counter value is stored instead of being returned as the result of the command. If specified, the return value of the command is 1 on success and 0 if the counter does not exist. Without this option, the command will raise an error if the counter does not exist.
Note that the command does not refresh the counter value. Caller must do that with pdh_query_refresh before calling this command if so desired.

pdh_parse_counter_path CTRPATH
Returns a dictionary containing the components of the counter path CTRPATH. The dictionary contains the following keys corresponding to each component of the path: machine, object, instance, instanceindex, parent and counter.
pdh_query_close HPERF
Closes a performance counter query. All counters added to the query are also released. HPERF is a query handle previously returned by pdh_query_open.
pdh_query_get HPERF ?NAME1 NAME2....?
Returns the values for one or more counters added to the query with pdh_add_counter. If no arguments are specified, values for all counters added to the query are returned. Otherwise, each argument must be the name associated with the counter with the -name option to the pdh_add_counter command.

The counters are refreshed with their current values from the system before being returned.

The returned value is a dictionary, each key of which is the mnemonic name associated with the abovementioned -name option of pdh_add_counter. The corresponding value in the dictionary may be a scalar or an array (as returned by the pdh_get_array command) depending on whether the -array option was specified as true in the corresponding pdh_add_counter call.
pdh_query_open
Open a new performance counter query and returns a handle to it. Counters can be added and removed from the query using The query must be closed when no longer needed by calling pdh_query_close.
pdh_query_refresh HPERF
Refreshes all counters in the specified performance counter query with their current values from the system. HPERF is a query handle previously returned by pdh_query_open.

In the case of rate-based counters like processor utilization, the first call only serves to initialize the counters. Valid data is collected only from the second call onwards. Microsoft recommends calls be at least one second apart.
pdh_remove_counter HPERF CTRNAME
Removes a counter from a performance counter query. Counters are automatically released when a query is closed. However, if a counter is no longer of use but the other counters in the query are, this command can be used to remove it.
pdh_system_performance_query ?CTRNAME ....?
This is a wrapper around pdh_query_open that includes some commonly used system counters.

Calling the command without any arguments will return a list of counter mnemonics that the command understands.

If called with arguments, each argument must be the name of a counter mnemonic. The command then returns a handle to a performance query with those counters already added. The command also internally calls pdh_query_refresh.

The returned query handle can be used exactly as a handle from pdh_query_open including addition of more counters, retrieving counter values etc. It must also be closed in the same manner by calling pdh_query_close.

COPYRIGHT

Copyright © 2014 Ashok P. Nadkarni


Printers - Printers

Printers

Printer management

SYNOPSIS

package require twapi_printer

enumerate_printers ?-proximity PROXIMITY?
get_default_printer

DESCRIPTION

This module provides commands related to Windows printer management.

Printer Management

The command enumerate_printers returns all the printers on the system. The command get_default_printer returns the name of the default printer.

Commands

enumerate_printers ?-proximity PROXIMITY?
Returns information about the printers on the system. The data is returned as a record array with the following fields:

-name | The following value is the name of the printer.
-server | The following value is the server on which the printer resides.
-attrs | The following value is a list of attributes for the printer. This is a list of zero or more symbols from the following list: queued, direct, default, shared, network, hidden, local, enabledevq, keepprintedjobs, docompletefirst, workoffline, enablebidi, rawonly, published, fax, ts. Refer to the Windows SDK documentation for the meaning of these attributes.
PROXIMITY may be one of all (default), local or remote depending on whether all printers, local printers or remote printers are to be included in the returned list.

get_default_printer
Returns the name of the default printer.

COPYRIGHT

Copyright © 2006-2009 Ashok P. Nadkarni


Device management - Device management

Device management

Commands related to devices and device interfaces

SYNOPSIS

package require twapi_device

device_ioctl DEVICEHANDLE IOCTLCODE ?-outputcount BUFSIZE?
eject DEVICE
eject_media DEVICE
find_physical_disks
get_physical_disk_info DISK ?options?
load_media DEVICE
lock_media DEVICE
start_device_notifier SCRIPT ?-deviceinterface DEVICEINTERFACE? ?-handle DEVICEHANDLE?
stop_device_notifier MONITORID
unlock_media DEVICE

DESCRIPTION

This package provides procedures related to device information and management in Windows operating systems.

Device ioctls

The device_ioctl command provides thin wrapper around the DeviceIoControl Win32 function. This allows for device specific control commands to be issued to devices. You will need to refer to the Windows SDK documentation for specifics of the ioctls supported by various devices.

Media control

The commands eject_media, load_media and lock_media and unlock_media provide control over removable devices and media.

Device notifications

Device notifications are generated by Windows to inform applications about changes in device configurations as well as related events. For example, notifications can be used by an application to learn about media change in CD-ROM drives, plugging in of a USB device, mounting a remote share and so on. These notifications allow applications to save any changes and release resources as appropriate.

Notifications are also used by the system to inform applications about pending changes giving them the chance to cancel them.

TWAPI delivers device notifications through callback scripts registered by the application through the start_device_notifier command. Applications must specify the device or device interface class for which they wish to receive notifications and the corresponding script to be invoked to receive them.

Physical disks

The find_physical_disks command returns the list of physical disks installed in the system. The get_physical_disk_info command can then be used to retrieve detailed information about the physical disk.

Commands

device_ioctl DEVICEHANDLE IOCTLCODE ?-outputcount BUFSIZE?
This is a thin wrapper around the Win32 DeviceIoControl function. Primary role of the wrapper is to do automatic output buffer management for the caller. DEVICEHANDLE, usually obtained through create_file, is a handle to the device of interest. IOCTLCODE is the IOCTL code to be sent to the device. The -outputcount option should be specified if the call is expected to return data. BUFSIZE should be the size of the output buffer expected by the call. The command will then return the result as a Tcl binary value that should in general be parsed with the Tcl binary scan command.
eject DEVICE
Alias for eject_media.
eject_media DEVICE
Ejects a removable device, such as a CD-ROM or pen drive. DEVICE should be of the form X:, X:\, X:/ where X is a drive letter, or a physical disk path as returned by the find_physical_disks command, or cdrom, in which case the first CD-ROM in the device list is ejected.
find_physical_disks
Returns the list of physical disks in the system. The returned paths can be passed to CreateFile or create_file to get a handle to the raw physical disk.
get_physical_disk_info DISK ?options?
Returns information about a physical disk. DISK is a device path to the physical disk in the format returned by find_physical_disks. The command returns a keyed list with fields depending on the passed options:

-all | Returns all fields.
-geometry | Returns the geometry of the disk. The value is itself a keyed list with the fields -cylinders, -mediatype, -trackspercylinder, -sectorspertrack and -bytespersector.
-layout | Returns the layout of the disk in terms of how it is partitioned. The returned value is a keyed list with the fields depending on how the disk is partitioned. See below for a discussion.

The partitioning of a disk can take several forms and the information returned by the -layout differs in each case. The following is a brief summary that assumes familiarity with disk formats. See the Windows DDK documentation for details.

On Windows 2000, the -layout field value is a keyed list with the fields -partitioncount, -signature and -partitions containing the number of partitions of the disk, the disk signature, and a list of partitions. Each element of the partition list is itself a keyed list with the fields -startingoffset, -partitionlength, -hiddensectors, -partitionnumber, -partitiontype, -bootindicator, -recognizedpartition and -rewritepartition.

On Windows XP and newer operating systems, the -layout field value is a keyed list with the fields, -partitioncount, -partitionstyle and -partitions. If the -partitionstyle field is mbr, an additional field -signature is present. If the -partitionstyle is gpt, three additional fields -startingusableoffset, -usablelength and -maxpartitioncount. Other possible value of -partitionstyle are raw or unknown in which case there are no additional fields. The -partitions field is a list each element of which is itself a keyed list containing information about each partition. Note that the number of elements of the -partitions list may not match the value of the -partitioncount field in case information for some partitions cannot be retrieved. Every element of the -partitions field will have the fields -partitionstyle, -startingoffset, -partitionlength, -partitionnumber and -rewritepartition. In addition, if -partitionstyle is mbr, the element will also have the fields -hiddensectors, -partitiontype, -bootindicator and -recognizedpartition. If -partitionstyle is gpt, it will have the fields -partitiontype, -partitionif, -attributes and -name. Partition styles raw and unknown have no additional fields.

load_media DEVICE
Load removable media such as a CD or DVD. DEVICE should be of the form X:, X:\, X:/ where X is a drive letter, or a physical disk path as returned by the find_physical_disks command, or cdrom, in which case the first CD-ROM in the device list is loaded.
lock_media DEVICE
Locks the media in a device with removable media such as a CD-ROM. On devices that support this function (not all do), locking the media will prevent the media from being ejected. The media can be unlocked with unlock_media. DEVICE should be of the form X:, X:\, X:/ where X is a drive letter, or a physical disk path as returned by the find_physical_disks command, or cdrom, in which case the media in the first CD-ROM in the device list is locked.
start_device_notifier SCRIPT ?-deviceinterface DEVICEINTERFACE? ?-handle DEVICEHANDLE?
Registers SCRIPT to be invoked when the events are generated from a specified device class or device.

The command creates a new notifier and returns its identifier. When no longer interested in the specified changes, the returned identifier should be passed to stop_device_notifier to stop the notifications and release associated resources.

If no additional options were specified to the command, or if the -deviceinterface option was specified with DEVICEINTERFACE as an empty string, all device interfaces are monitored. If DEVICEINTERFACE is one of the keywords port or volume, then all ports and all volumes respectively are monitored. Otherwise, DEVICEINTERFACE must be the GUID for a particular device interface class, and only that interface class is monitored. Refer to the Windows SDK for a list of GUIDs for various device interface classes.

If the -handle option is specified, DEVICEHANDLE must be a handle to a resource on the device obtained through either create_file or get_tcl_channel_handle. In this case, only event notifications from that particular device are passed to the callback script.

At most one of the options -deviceinterface and -handle can be specified.

The callback SCRIPT is invoked with additional arguments. The first argument is the id of the notifier that was returned by this command. The second argument is the event notification type and may be followed by additional arguments specific to the type.

For compatibility with future releases, the callback script should ignore notification types not listed below. For the same reason, it should also ignore any additional arguments or unexpected values for listed arguments.

Certain event types require the callback script to return a value. These are noted below.

The notification type and the corresponding arguments are shown in the table below. The symbols match exactly the DBT_* symbols defined in the Windows SDK except for the character case and prefix. For example, devicearrival corresponds to DBT_DEVICEARRIVAL. More detail about each event can be obtained by looking at the SDK documentation for the corresponding symbol.

configchangecanceled | A request to change the current dock/undock device configuration was canceled. No additional arguments are present.
configchanged | The current device configuration has changed due to docking or undocking. No additional arguments are present.
customevent | A custom event defined by a driver. An additional argument may be present if the notifier was created with a -devicehandle option. This provides more detail on the event and has one of the following values: io_volume_change, io_volume_dismount, io_volume_dismount_failed, io_volume_mount, io_volume_lock, io_volume_lock_failed, io_volume_unlock, io_volume_name_change, io_volume_physical_configuration_change, io_volume_device_interface, io_media_arrival, io_media_removal, io_device_becoming_ready, io_device_external_request, io_media_eject_request, io_drive_requires_cleaning, io_tape_erase, io_disk_layout_change. Refer to the Windows SDK and DDK for more information on these.
devicearrival A new device or media has become available. The first additional argument is one of deviceinterface, handle, port or volume depending on source of the notification.

If this first argument in deviceinterface, (ie. device interfaces are being monitored (DEVICEINTERFACE is unspecified, an empty string, or a device interface GUID), it is followed by the device interface class GUID for the new device interface, and the device interface class name.

If the value is handle, two additional arguments may be present containing the internal device and notification handles. These should be treated as opaque.

If the value is port, one additional argument, the name of the port, may be present.

If the value is volume, the first additional argument is a list of drive letters corresponding to the new detected volumes (note there may be more than one). This is followed by a list of attributes. If the list includes mediachange, it indicates that new media was inserted (e.g. a CD-ROM); otherwise, it indicates a new physical device (e.g. a USB pen drive). If the list includes networkvolume, it indicates the new volume is accessed over the network.
devicequeryremove Request permission to remove a device. The application can deny the request by returning the string deny. Any other value will be treated as an allow. It is important that the script return an answer in prompt fashion. Any significant processing should be queued for later.

The arguments are the same as those for devicearrival when the device source type is handle.

Note this notification is only delivered when the -handle option is used. The application can therefore easily use the notifier id to associate the notification with a specific device. If the callback script returns anything other than deny, it should first close all open handles on the device, including the one passed as the argument value for the -handle option. Otherwise, the device removal will fail.
devicequeryremovefailed | A request to remove a device was canceled, either because an application denied it or there were open handles to the device. Additional arguments are the same as devicequeryremove.
deviceremovecomplete | Removal of a device or media has been completed. For physical devices this means the device has been physically disconnected. For volumes, this indicates the volume has been dismounted. Additional arguments are identical to those of devicearrival.
deviceremovepending | A device is being removed and not available. Additional arguments are identical to those of devicearrival.
devicetypespecific | An event specific to the type of device. Additional arguments are identical to those of devicearrival.
devnodes_changed | The system device tree has been modified. Windows does not provide any additional detail about the change and it is up to the application to examine the device tree components of interest.
querychangeconfig | Request to change the current dock/undock configuration. The application can allow or deny the request. The command has no additional arguments. See devicequeryremove for more detail on how the script should respond.
userdefined | A user defined event sent by an application using BroadcaseSystemMessage. An additional argument specifies the name of the event (vendor defined).

This command requires a threaded build of Tcl and will raise an exception on non-threaded builds.

stop_device_notifier MONITORID
Cancels monitoring of device changes. MONITORID which must be an identifier previously returned by start_device_notifier.
unlock_media DEVICE
Unlocks the media in a device with removable media such as a CD-ROM which had been previously locked with lock_media. DEVICE should be of the form X:, X:\, X:/ where X is a drive letter, or a physical disk path as returned by the find_physical_disks command, or cdrom, in which case the first CD-ROM in the device list is unlocked.

COPYRIGHT

Copyright © 2008 Ashok P. Nadkarni


Synchronization - Synchronization

Synchronization

Commands related to synchronization primitives

SYNOPSIS

package require twapi_synch

create_event ?options?
create_mutex ?options?
lock_mutex HANDLE ?-wait MILLISECS?
open_mutex ?-access ACCESSRIGHTS? ?-inherit BOOLEAN?
reset_event HANDLE
set_event HANDLE
unlock_mutex HANDLE

DESCRIPTION

This package provides procedures related to various syncrhonization primitives on Windows platforms.

Mutexes

A mutex is a synchronization object that can be used to coordinate mutually exclusive access to shared resources. Refer to the Windows SDK for details about capabilities and use.

Mutexes can be created using create_mutex. Existing mutexes can be accessed using open_mutex. The commands lock_mutex and unlock_mutex can be used to gain and release ownership of the shared resource.

Events

An event is a synchronization object that can be in one of two states - signalled and non-signalled. It is useful for notifying a process or thread of the occurence of some event. Refer to the Windows SDK for details about usage.

Event objects can be created through create_event and their state changed using the commands set_event and reset_event. An application can wait on an event object to be signalled using the wait_on_handle command.

Commands

create_event ?options?
Creates an event object with the specified options and returns a handle to it. The following options control the event properties:

-existvar VARNAME | If specified, the command will set the variable VARNAME in the caller's context to 0 if the event was newly created and to 1 if the event already existed.
-inherit BOOLEAN | If specified as true, the handle will be inherited by child processes (default false).
-manualreset BOOLEAN | By default, events are automatically reset to a non-signalled state when a thread successfully waits on an event. If this option is specified as true, the event remains signalled until it is explicitly reset using the reset_event command. Default is false.
-name NAME | Specifies the name of the event. Events are unnamed by default.
-secd SECURITY_DESCRIPTOR | Specifies a security descriptor for the event object. By default, a null security descriptor is used.
-signalled BOOLEAN | If specified as true the event object is created in a signalled state. Default is false. This option must not be specified as true if the option -name is also specified.

The returned handle can be passed to set_event and reset_event to change the state of the event object. The application can wait for an event to be signalled by calling wait_on_handle. The handle must be closed when no longer needed by passing it to close_handle.

create_mutex ?options?
Creates a mutex object with the specified options and returns a handle to it. The following options control the mutex properties:

-inherit BOOLEAN | If specified as true, the handle will be inherited by child processes (default false).
-lock BOOLEAN | If specified as true the mutex is created in a locked state. Default is false. This option must not be specified as true if the option -name is also specified.
-name NAME | Specifies the name of the event. Events are unnamed by default.
-secd SECURITY_DESCRIPTOR | Specifies a security descriptor for the event object. By default, a null security descriptor is used.

The returned mutex handle can be passed to lock_mutex and unlock_mutex to claim or release ownership. The handle must be closed when no longer needed by passing it to close_handle.

lock_mutex HANDLE ?-wait MILLISECS?
Attempts to lock the mutex specified by HANDLE. Refer to wait_on_handle for possible return values and details about the -wait option.
open_mutex ?-access ACCESSRIGHTS? ?-inherit BOOLEAN?
Returns a handle to an existing mutex. The following options may be specfied:

-access ACCESSRIGHTS | Specifies a list of desired access rights. If this option is not specified, access rights default to mutex_all_access. See Access Rights for a description of the format of this list and for a description of standard access rights.
-inherit BOOLEAN | If specified as true, the handle will be inherited by child processes (default false).
The returned mutex handle can be passed to lock_mutex and unlock_mutex to claim or release ownership. The handle must be closed when no longer needed by passing it to close_handle.

reset_event HANDLE
Changes the state of the event object specified by HANDLE to be non-signalled.
set_event HANDLE
Changes the state of the event object specified by HANDLE to be signalled.
unlock_mutex HANDLE
Unlocks the mutex specified by HANDLE.

COPYRIGHT

Copyright © 2010 Ashok P. Nadkarni


Power management - Power management

Power management

Power management

SYNOPSIS

package require twapi_power

get_device_power_state DEVICEHANDLE
get_power_status
start_power_monitor SCRIPT
stop_power_monitor POWER_ID

DESCRIPTION

This module provides commands related to power management in a Windows system.

Overview

The current state of the power subsystem, including battery status, can be obtained through the get_power_status command. The state of an individual device can be obtained through the get_device_power_state command.

Changes in the power subsystem state can be monitored through the start_power_monitor and stop_power_monitor.

Commands

get_device_power_state DEVICEHANDLE
Returns 1 if the device indicated by DEVICEHANDLE is fully powered up and 0 if it is in a low-power state. DEVICEHANDLE is a handle to the device or to an object on the device. For example, it can be the handle returned by a get_tcl_channel_handle command corresponding to a Tcl file handle.

DEVICEHANDLE must not be a handle to a display device.
get_power_status
Returns a keyed list containing information about the state of the power system. The list includes the fields in the table below.

-acstatus | Indicates the state of the AC power. May have the values on, off or unknown.
-batterystate | Indicates the state of the battery charge. May be notpresent, critical, low, high or unknown.
-batterycharging | Indicates whether the battery is being charged. May have the values true, false or unknown.
-batterylifepercent | Indicates the percentage of the full battery life remaining or has the value unknown.
-batterylifetime | Indicates the remaining battery life time in seconds, if known, or has the value unknown.
-batteryfulllifetime | Indicates the number of seconds of battery life when it is full, or has the value unknown.

start_power_monitor SCRIPT
Begins monitoring of power state changes. SCRIPT will be invoked when the state of the power subsystem changes, for example, when the system switches to battery power.

The command returns a handle. When no longer required, this handle must be passed to the command stop_power_monitor.

Multiple monitoring scripts may be active at the same time. However, all returned handles must be passed to stop_power_monitor. before the application exits.

The callback script is invoked with two additional arguments. The first argument indicates the type of event and has one of the values in the table below.

apmbatterylow | Indicates that the system battery is low.
apmoemevent | Indicates an OEM-defined event.
apmpowerstatuschange | Indicates a change in the power status. Details may be obtained by calling get_power_status.
apmquerysuspendfailed | Indicates that a query to suspend the computer was denied.
apmresumeautomatic | Indicates that the system has woken up to handle an event.
apmresumecritical | Indicates the system has woken up after a critical system suspension (e.g. due to very low battery) where it was not possible to notify all applications before the suspension.
apmresumesuspend | Indicates that the system has resumed normal operation after a suspension.
apmsuspend | Indicates the system is about to be suspended and applications should save state and data if necessary.
The callback may be invoked with other values for the event indicator. These should be ignored.

The second argument passed to the callback is only meaningful when the event is apmoemevent. The value of the argument is an OEM-defined event code.

This command requires a threaded build of Tcl and will raise an exception on non-threaded builds.

stop_power_monitor POWER_ID
Stops a previously registered script that monitors the power subsystem. POWER_ID is monitoring handle previously returned by start_power_monitor.

COPYRIGHT

Copyright © 2008 Ashok P. Nadkarni


Version History - TWAPI Version History

Version History

Tcl Windows API extension version history

DESCRIPTION

Summarizes the list of changes for each version of TWAPI.

Version 4.0

Major changes in this release are support for Windows event tracing, new Windows event logging API, SSL/TLS sockets, greatly enhanced support for CryptoAPI including certificate handling, access to performance counters, enhancements to the COM module and architectural changes for modularity and run-time performance.

Make a special note of the list of Incompatible Changes at the end of this section. Some of these differences apply to prior 4.0 betas as well.

  • Added SSL/TLS socket channels.
  • Added support for the new event logging infrastructure in Windows Vista.
  • Added support for reading performance counters.
  • New Event Tracing for Windows module.
  • Enhanced SSPI module including stream support.
  • Added certificate commands for creation, verification and management of certificates and certificate stores.
  • New commands eject_media, load_media, lock_media and unlock_media for dealing with removable media.
  • Added read_credentials, credentials_dialog, confirm_credentials and credentials.
  • Added conceal/reveal for memory encryption and protect_data/unprotect_data for protecting data based on user credentials.
  • Added -active option to comobj to create an instance of an existing object.
  • Added named argument support for COM method calls
  • Added generate_code_from_typelib to generate COM client code from type libraries.
  • Added COM support for passing SAFEARRAY types as input parameters and enhanced output SAFEARRAY values to support multidimensional arrays. POTENTIAL INCOMPATIBILITY as previously multidimensional arrays were returned as a single list.
  • Added comobj? and comobj_instances to check for and return instances of comobj objects.
  • Significantly improved COM method call performance through the use of TclOO in newer Tcl versions (8.6b2 and later)
  • Added define_dispatch_prototypes.
  • Added get_network_adapters, get_network_adapters_detail and get_network_adapter_info.
  • Added the common data format record array for collections returned by many commands and the corresponding recordarray command.
  • Added get_keyboard_layout_name.
  • Added tclcast and tcltype.
  • Added commands get_user_local_groups, get_user_global_groups, add_members_to_local_group, remove_members_from_local_group and -type sid option to add_member_to_local_group, remove_member_from_local_group.
  • Added commands get_password_policy, get_lockout_policy, set_password_policy and set_lockout_policy for dealing with global account settings.
  • Added -runas to write_shortcut and read_shortcut.
  • Added random_bytes.
  • Added -raw option to write_clipboard_text.
  • Added -setvars option to parseargs.
  • Added the rethrow, trapresult and trapoptions commands to trap.
  • Added get_processor_group_config and get_numa_config.
  • Added get_build_config to return build information.
INCOMPATIBLE CHANGES

The following tables list incompatibilities and potential incompatibilities with respect to TWAPI 3.1.

Base module

debuglog | Calling interface has changed.
get_build_config | Return value format and content has changed.
try | Removed to prevent conflicts with the try command in Tcl 8.6. Use trap instead. The errorCode, errorResult and errorInfo variables are no longer brought into scope automatically in onerror clauses.
Users and Groups

get_global_groups get_global_group_members get_local_groups get_local_group_members get_users | Commands return record arrays instead of a list when the -level option is used. Field and optin names have been changed for consistency.
get_user_local_groups_recursive | Deprecated. Use get_user_local_groups with the -recurse flag instead.
Network configuration

address_to_hostname | Removed. Use the resolve_address command instead.
flush_arp_tables | Takes interface names as arguments instead of interface indices.
get_arp_table | Returns the ARP table as a record array. Options -ifindex and -validonly are no longer available. Use record array filtering instead.
get_ip_addresses | Was deprecated. Now removed Use get_system_ipaddrs instead.
get_netif_count, get_netif6_count | Removed. Returned internal driver interface information which was misleading in terms of the interfaces actually visible at the application level.
get_netif_indices get_netif6_indices | Removed. Use interface names as returned by get_network_adapters instead.
get_tcp_connections get_udp_connections | Return connections as record arrays instead of lists.
hostname_to_address | Removed. Use the resolve_hostname command instead.
COM

COM SAFEARRAY Multidimensional arrays are returned as nested lists. In 3.1, they were returned as a single flat list.
Network Shares and Lan Manager

find_lm_connections find_lm_sessions find_lm_open_files get_client_shares get_shares Commands return record arrays instead of a list when the -level option is used. Field and option names have been changed for consistency.
Services

get_multiple_service_status get_dependent_service_status Changed to return record arrays.
Device module

device_ioctl Calling interface has changed.
Windows Shell

file_properties_dialog printer_properties_dialog volume_properties_dialog | Removed. Use shell_object_properties_dialog instead.
shell_object_properties_dialog | Defaults the object type to file instead of attempting to guess the type.
TwapiThemeDefineValue | Removed.
Storage

get_logical_drives Removed. Use find_logical_drives instead.
Processes and Threads

get_process_info | The -toplevels option is no longer available. Use get_toplevel_windows -pids instead. Also, rate based performance options have been removed. Equivalent functionality is available through performance counters commands.
get_thread_info | Rate based performance options have been removed. Equivalent functionality is available through performance counters commands.
get_device_drivers | Changed to return record arrays.
System module

get_active_processor_mask | Removed. Use get_processor_group_configuration instead.
get_processor_info | Performance related options have been removed. Equivalent functionality is available through pdh_system_performance_query. The command now returns information about the current processor group, not the whole system.
get_system_info | Removed. Equivalent functionality is available through the pdh_system_performance_query, get_system_sid and get_system_uptime commands.
large_system_time_to_timelist | Returns an additional element - the day of the week.
Security and CryptoAPI

Password handling | Many commands which take a password as an argument now expect it to be passed in encrypted form as returned by read_credentials, credentials_dialog and conceal. Unencrypted forms of passwords are still accepted by existing commands but are deprecated and support will be dropped in a future release. Commands new in 4.0 will only work with the new encrypted password forms.
SSPI interface | API has been completely redone (post-4.0b23) and commands in older versions are no longer present.
Printers

enumerate_printers Changed to return record arrays.

Version 3.1

Note: Make sure you read list of incompatible changes at the end of this section.

  • Added support for IPv6 network commands.
  • Added support for taskbar notification icons.
  • Added resource loading commands extract_resources, load_icon_from_file, load_cursor_from_file, load_bitmap_from_file, load_icon_from_module, load_cursor_from_module, load_bitmap_from_module, load_icon_from_system, load_cursor_from_system, load_bitmap_from_system, free_icon, free_cursor and free_bitmap.
  • get_module_handle and get_module_handle_from_address.
  • Added options -primarygroupsid, -groupattrs, -restrictedgroups, -restrictedgroupattrs, -enabledprivileges, -enabledprivileges and -integritylabel to get_process_info.
  • Added options -primarygroupsid, -groupattrs, -restrictedgroups, -restrictedgroupattrs, -enabledprivileges, -enabledprivileges to get_thread_info.
  • Added get_default_printer.
  • Enhancements to parseargs to map boolean true values.
  • INCOMPATIBILITY Windows 2000 is no longer supported.
  • INCOMPATIBILITY Tcl 8.4 is no longer supported.
  • INCOMPATIBILITY The values returned by the -type option to get_netif_info have changed.
  • INCOMPATIBILITY The values returned by the -type option to get_netif_info have changed.

Version 3.0

  • Note the list of IMCOMPATIBLE CHANGES at the end of this section.
  • Added support for 64-bit versions of Windows.
  • Added support for loading into multiple interpreters and multithreading.
  • Added single-file DLL distribution that replaces the Tclkit format distribution.
  • Added support for named pipe channels and impersonate_namedpipe_client.
  • COM support has been reworked and enhanced to include script level access to interfaces and type libraries.
  • Added synchronization commands.
  • Added shell_execute.
  • Added command for manipulating Windows resources.
  • Added UAC related commands get_process_elevation, get_process_integrity and, set_process_integrity and, virtualized_process, set_process_virtualization, get_token_elevation, get_token_integrity and set_token_integrity, get_token_integrity_policy and set_token_integrity_policy, get_token_virtualization and, set_token_virtualization, get_token_linked_token.
  • Added options -virtualized, -integrity and -elevation to get_process_info.
  • Enhanced enumeration of users and groups to support incremental mode of retrieval and to optionally include more account detail.
  • Enhanced get_shares and get_client_shares to optionally return additional details.
  • Added wow64_process.
  • Added get_pid_from_handle.
  • get_os_info enhanced to support newer operating systems and configurations.
  • Added eventlog_monitor_start for asynchronous notification of event log modifications. Enhanced formatting of event log messages to automatically retrieve parameter message file references.
  • Added flash_window.
  • Added SDDL support through security_descriptor_to_sddl and sddl_to_security_descriptor.
  • Added new_restricted_dacl.
  • Added process_in_administrators.
  • Added -hprocess and -hthread options to get_process_token and get_thread_token respectively.
  • Added the -attributes option to get_global_group_info.
  • Added -append option to register_hotkey to allow multiple scripts to register for the same hotkey.
  • Renamed try to trap and aliased it to prevent conflicts with Tcl 8.6 try.
  • Added debuglog command to log debug and trace messages.
  • INCOMPATIBILITY Removed the commands lock_scm_db, unlock_scm_db and query_scm_db_lock_status as they have no effect on Vista and later systems and were rarely used on older machines as well.
  • INCOMPATIBILITY The format of the data returned by commands that return the status of Windows services has changed.
  • INCOMPATIBILITY Removed the command get_mapped_share_info which was deprecated in favor of get_client_share_info in previous releases.
  • INCOMPATIBILITY The format of the lists returned by get_dependent_service_status and get_multiple_service_status has changed to make access simpler and faster.
  • INCOMPATIBILITY The format of the appended arguments to the callback invoked via begin_filesystem_monitor has changed.
  • INCOMPATIBILITY The format of expiration time of user accounts as returned by get_user_account_info has changed as have the formats accepted by set_user_account_info and set_user_expiration.
  • INCOMPATIBILITY This version supports Windows XP or later versions of Windows and version 8.5 or later of Tcl. It has also been tested on Windows 2000 and Tcl 8.4 but any bugs specific to these platforms will not be fixed.
  • INCOMPATIBILITY This version does not support the twapi_desktop and twapi_server package subsets of TWAPI and does not provide a Tclkit format distribution.
  • INCOMPATIBILITY The command set_user_priv_level and the -priv option to the get_user_account_info, set_user_account_info and new_user commands have been removed as their use was unsuitable for domain environments. Use specific group membership instead to control privileges.
  • INCOMPATIBILITY set_console_input_mode and set_console_output_mode are deprecated. Use modify_console_input_mode and modify_console_output_mode instead.

Version 2.2

  • Added commands comobj_object, progid_to_clsid, and clsid_to_progid.
  • Device notifications significantly enhanced. New commands start_device_notifier and stop_device_notifier for handling device event notifications. "INCOMPATIBILITY" Commands start_device_change_monitor and stop_device_change_monitor are no longer available.
  • Support for Tcl-based Windows services enhanced to handle additional control signals and system events.
  • Added GetSystemMetrics and GetSystemWow64Directory, but no Tcl wrappers.

Version 2.1

  • Built desktop and server specific TWAPI packages containing a subset of the TWAPI commands with a smaller footprint. Reduced footprint of full TWAPI package as well.
  • Added recycle_file.
  • Added error notifications to begin_filesystem_monitor.
  • Added options -foundcodepage, -foundlangid and -datetime to get_file_version_resource.
  • Added Wow64EnableWow64FsRedirection, Wow64DisableWow64FsRedirection, and Wow64RevertWow64FsRedirection.
  • Added new formats to get_current_user.
  • Added SHChangeNotify, CryptAcquireContext, CryptReleaseContext, and CryptGenRandom. No Tcl wrappers for these.

Version 2.0

  • INCOMPATIBILITY Windows NT 4.0 is no longer a supported platform.
  • Added support for distribution as a single file Tcl module for Tcl 8.5.
  • Added support for Tcl-based Windows services.
  • Added Microsoft Windows Installer interface support.
  • Added SSPI support (experimental).
  • Added Power Management module.
  • Added start_device_change_monitor and stop_device_change_monitor.
  • Added start_clipboard_monitor and stop_clipboard_monitor.
  • Added -patterns option to begin_filesystem_monitor.
  • Added get_priority_class, set_priority_class, get_thread_relative_priority and set_thread_relative_priority.
  • Added commands get_outgoing_interface, get_route and get_routing_table.
  • Added commands get_display_devices, get_display_monitors, get_display_monitor_from_window, get_display_monitor_from_point, get_display_monitor_from_rect, get_display_monitor_info.
  • Added commands find_physical_disks and get_physical_disk_info.
  • Added create_file.
  • Added device_ioctl.
  • Added -extents option to get_volume_info.
  • Added -isnull subcommand to COM objects.
  • Added get_input_idle_time.
  • Added large_system_time_to_timelist and timelist_to_large_system_time.
  • Added -modulename, -modulepath, -bindtime options to get_tcp_connections and get_udp_connections. Modified -matchremoteaddr and -matchlocaladdr options to allow DNS names and accept multiple addresses.
  • Added -messageonlywindow option to find_windows.
  • Added options -noexist and -noaccess to get_thread_info. INCOMPATIBILITY The command no longer raises an exception if a thread does not exist or cannot be accessed.
  • Additional performance optimizations.

Version 1.1

  • Added enhanced Windows task scheduler interface.
  • Added commands find_lm_sessions, end_lm_sessions, get_lm_session_info and find_lm_connections dealing with Lan Manager sessions and connections.
  • Added commands find_lm_open_files, close_lm_open_file and get_lm_open_file_info dealing with files opened in Lan Manager sessions.
  • Added find_domain_controller command.
  • Added get_file_times and set_file_times dealing with file timestamps.
  • Enhanced get_process_info and get_thread_info return additional process and thread information.
  • Enhanced get_processor_info to return additional processor information.
  • Enhanced get_memory_info to return additional swap file information.
  • Replaced Windows performance counter calls with native Win32 calls resulting in almost two orders of magnitude better performance in retrieving process, thread and system information.
  • Added get_system_time.
  • Added secs_since_1970_to_large_system_time.
  • Added variant_time_to_timelist and timelist_to_variant_time.
  • Added -handle option to get_resource_security_descriptor and options -handle, -unprotect_dacl and -unprotect_sacl to set_resource_security_descriptor.
  • Added -logonsession option to get_process_ids.
  • Include process id and attribute information (if available) in data returned by get_service_status and get_multiple_service_status.
  • INCOMPATIBILITY Changed default value of new_share option -secd.
  • Bug fixes.

Version 1.0

First official release.

COPYRIGHT

Copyright © 2003-2014 Ashok P. Nadkarni