[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6. Contexts

All cryptographic operations in GPGME are performed within a context, which contains the internal state of the operation as well as configuration parameters. By using several contexts you can run several cryptographic operations in parallel, with different configuration.

Data type: GpgmeCtx
The GpgmeCtx type is a handle for a GPGME context, which is used to hold the configuration, status and result of cryptographic operations.

6.1 Creating Contexts  Creating new GPGME contexts.
6.2 Destroying Contexts  Releasing GPGME contexts.
6.3 Context Attributes  Setting properties of a context.
6.4 Key Management  Managing keys with GPGME.
6.5 Trust Item Management  Managing trust items with GPGME.
6.6 Crypto Operations  Using a context for cryptography.
6.7 Run Control  Controlling how operations are run.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.1 Creating Contexts

Function: GpgmeError gpgme_new (GpgmeCtx *ctx)
The function gpgme_data_new creates a new GpgmeCtx object and returns a handle for it in ctx.

The function returns GPGME_No_Error if the context was successfully created, GPGME_Invalid_Value if ctx is not a valid pointer, and GPGME_Out_Of_Core if not enough memory is available.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.2 Destroying Contexts

Function: void gpgme_release (GpgmeCtx ctx)
The function gpgme_release destroys the context with the handle ctx and releases all associated resources.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3 Context Attributes

6.3.1 Protocol Selection  Selecting the protocol used by a context.
6.3.2 ASCII Armor  Requesting ASCII armored output.
6.3.3 Text Mode  Choosing canonical text mode.
6.3.4 Included Certificates  Including a number of certificates.
6.3.5 Key Listing Mode  Selecting key listing mode.
6.3.6 Passphrase Callback  Getting the passphrase from the user.
6.3.7 Progress Meter Callback  Being informed about the progress.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.1 Protocol Selection

Function: GpgmeError gpgme_set_protocol (GpgmeCtx ctx, GpgmeProtocol proto)
The function gpgme_set_protocol sets the protocol used within the context ctx to proto. All crypto operations will be performed by the crypto engine configured for that protocol. See section 3. Protocols and Engines.

Setting the protocol with gpgme_set_protocol does not check if the crypto engine for that protocol is available and installed correctly. See section 3.1 Engine Version Check.

The function returns GPGME_No_Error if the protocol could be set successfully, and GPGME_Invalid_Value if protocol is not a valid protocol.

Function: GpgmeProtocol gpgme_get_protocol (GpgmeCtx ctx)
The function gpgme_get_protocol retrieves the protocol currently use with the context ctx.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.2 ASCII Armor

Function: void gpgme_set_armor (GpgmeCtx ctx, int yes)
The function gpgme_set_armor specifies if the output should be ASCII armored. By default, output is not ASCII armored.

ASCII armored output is disabled if yes is zero, and enabled otherwise.

Function: int gpgme_get_armor (GpgmeCtx ctx)
The function gpgme_get_armor returns 1 if the output is ASCII armored, and 0 if it is not, or if ctx is not a valid pointer.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.3 Text Mode

Function: void gpgme_set_textmode (GpgmeCtx ctx, int yes)
The function gpgme_set_textmode specifies if canonical text mode should be used. By default, text mode is not used.

Text mode is for example used for the RFC2015 signatures; note that the updated RFC 3156 mandates that the mail user agent does some preparations so that text mode is not needed anymore.

This option is only relevant to the OpenPGP crypto engine, and ignored by all other engines.

Canonical text mode is disabled if yes is zero, and enabled otherwise.

Function: int gpgme_get_textmode (GpgmeCtx ctx)
The function gpgme_get_textmode returns 1 if canonical text mode is enabled, and 0 if it is not, or if ctx is not a valid pointer.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.4 Included Certificates

Function: void gpgme_set_include_certs (GpgmeCtx ctx, int nr_of_certs)
The function gpgme_set_include_certs specifies how many certificates should be included in an S/MIME signed message. By default, only the sender's certificate is included. The possible values of nr_of_certs are:

-2
Include all certificates except the root certificate.
-1
Include all certificates.
0
Include no certificates.
1
Include the sender's certificate only.
n
Include the first n certificates of the certificates path, starting from the sender's certificate. The number n must be positive.

Values of nr_of_certs smaller than -2 are undefined.

This option is only relevant to the CMS crypto engine, and ignored by all other engines.

Function: int gpgme_get_include_certs (GpgmeCtx ctx)
The function gpgme_get_include_certs returns the number of certificates to include into an S/MIME signed message.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.5 Key Listing Mode

Function: void gpgme_set_keylist_mode (GpgmeCtx ctx, int mode)
The function gpgme_set_keylist_mode changes the default behaviour of the key listing functions. The value in mode is a bitwise-or combination of one or multiple of the following bit values:

GPGME_KEYLIST_MODE_LOCAL
The GPGME_KEYLIST_MODE_LOCAL symbol specifies that the local keyring should be searched for keys in the keylisting operation. This is the default.

GPGME_KEYLIST_MODE_EXTERN
The GPGME_KEYLIST_MODE_EXTERN symbol specifies that an external source should be should be searched for keys in the keylisting operation. The type of external source is dependant on the crypto engine used. For example, it can be a remote keyserver or LDAP certificate server.

At least one of GPGME_KEYLIST_MODE_LOCAL and GPGME_KEYLIST_MODE_EXTERN must be specified. For future binary compatibility, you should get the current mode with gpgme_get_keylist_mode and modify it by setting or clearing the appropriate bits, and then using that calulcated value in the gpgme_set_keylisting_mode operation. This will leave all other bits in the mode value intact (in particular those that are not used in the current version of the library).

The function returns GPGME_No_Error if the mode could be set correctly, and GPGME_Invalid_Value if ctx is not a valid pointer or mode is not a valid mode.

Function: int gpgme_get_keylist_mode (GpgmeCtx ctx)
The function gpgme_get_keylist_mode returns the current key listing mode of the context ctx. This value can then be modified and used in a subsequent gpgme_set_keylist_mode operation to only affect the desired bits (and leave all others intact).

The function returns 0 if ctx is not a valid pointer, and the current mode otherwise. Note that 0 is not a valid mode value.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.6 Passphrase Callback

Data type: const char *(*GpgmePassphraseCb)(void *hook, const char *desc, void **r_hd)
The GpgmePassphraseCb type is the type of functions usable as passphrase callback function.

The string desc contains a text usable to be displayed to the user of the application. The function should return a passphrase for the context when invoked with desc not being NULL.

The user may store information about the resources associated with the returned passphrase in *r_hd. When the passphrase is no longer needed by GPGME, the passphrase callback function will be called with desc being NULL, and r_hd being the same as at the first invocation.

Function: void gpgme_set_passphrase_cb (GpgmeCtx ctx, GpgmePassphraseCb passfunc, void *hook_value)
The function gpgme_set_passphrase_cb sets the function that is used when a passphrase needs to be provided by the user to passfunc. The function passfunc needs to implemented by the user, and whenever it is called, it is called with its first argument being hook_value. By default, no passphrase callback function is set.

Not all crypto engines require this callback to retrieve the passphrase. It is better if the engine retrieves the passphrase from a trusted agent (a daemon process), rather than having each user to implement their own passphrase query.

The user can disable the use of a passphrase callback function by calling gpgme_set_passphrase_cb with passfunc being NULL.

Function: void gpgme_get_passphrase_cb (GpgmeCtx ctx, GpgmePassphraseCb *passfunc, void **hook_value)
The function gpgme_get_passphrase_cb returns the function that is used when a passphrase needs to be provided by the user in *passfunc, and the first argument for this function in *hook_value. If no passphrase callback is set, or ctx is not a valid pointer, NULL is returned in both variables.

passfunc or hook_value can be NULL. In this case, the corresponding value will not be returned.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.7 Progress Meter Callback

Data type: const char *(*GpgmeProgressCb)(void *hook, const char *what, int type, int current, int total)
The GpgmeProgressCb type is the type of functions usable as progress callback function.

The arguments are specific to the crypto engine. More information about the progress information returned from the GnuPG engine can be found in the GnuPG source code in the file `doc/DETAILS' in the section PROGRESS.

Function: void gpgme_set_progress_cb (GpgmeCtx ctx, GpgmeProgressCb progfunc, void *hook_value)
The function gpgme_set_progress_cb sets the function that is used when progress information about a cryptographic operation is available. The function progfunc needs to implemented by the user, and whenever it is called, it is called with its first argument being hook_value. By default, no progress callback function is set.

Setting a callback function allows an interactive program to display progress information about a long operation to the user.

The user can disable the use of a progress callback function by calling gpgme_set_progress_cb with progfunc being NULL.

Function: void gpgme_get_progress_cb (GpgmeCtx ctx, GpgmeProgressCb *progfunc, void **hook_value)
The function gpgme_get_progress_cb returns the function that is used to inform the user about the progress made in *progfunc, and the first argument for this function in *hook_value. If no progress callback is set, or ctx is not a valid pointer, NULL is returned in both variables.

progfunc or hook_value can be NULL. In this case, the corresponding value will not be returned.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4 Key Management

Some of the cryptographic operations require that recipients or signers are specified. This is always done by specifying the respective keys that should be used for the operation. The following section describes how such keys can be selected and manipulated.

Data type: GpgmeKey
The GpgmeKey type is a handle for a public or secret key, and is used to select the key for operations involving it.

A key can contain several user IDs and sub keys.

6.4.1 Listing Keys  Browsing the list of available keys.
6.4.2 Information About Keys  Requesting detailed information about keys.
6.4.3 Manipulating Keys  Operations on keys.
6.4.4 Generating Keys  Creating new key pairs.
6.4.5 Exporting Keys  Retrieving key data from the key ring.
6.4.6 Importing Keys  Adding keys to the key ring.
6.4.7 Deleting Keys  Removing keys from the key ring.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4.1 Listing Keys

Function: GpgmeError gpgme_op_keylist_start (GpgmeCtx ctx, const char *pattern, int secret_only)
The function gpgme_op_keylist_start initiates a key listing operation inside the context ctx. It sets everything up so that subsequent invocations of gpgme_op_keylist_next return the keys in the list.

If pattern is NULL, all available keys are returned. Otherwise, pattern contains an engine specific expression that is used to limit the list to all keys matching the pattern.

If secret_only is not 0, the list is restricted to secret keys only.

The context will be busy until either all keys are received (and gpgme_op_keylist_next returns GPGME_EOF), or gpgme_op_keylist_end is called to finish the operation.

The function returns GPGME_Invalid_Value if ctx is not a valid pointer, and passes through any errors that are reported by the crypto engine support routines.

Function: GpgmeError gpgme_op_keylist_ext_start (GpgmeCtx ctx, const char *pattern[], int secret_only, int reserved)
The function gpgme_op_keylist_ext_start initiates an extended key listing operation inside the context ctx. It sets everything up so that subsequent invocations of gpgme_op_keylist_next return the keys in the list.

If pattern or *pattern is NULL, all available keys are returned. Otherwise, pattern is a NULL terminated array of strings that are used to limit the list to all keys matching at least one of the patterns verbatim.

If secret_only is not 0, the list is restricted to secret keys only.

The value of reserved must be 0.

The context will be busy until either all keys are received (and gpgme_op_keylist_next returns GPGME_EOF), or gpgme_op_keylist_end is called to finish the operation.

The function returns GPGME_Invalid_Value if ctx is not a valid pointer, and passes through any errors that are reported by the crypto engine support routines.

Function: GpgmeError gpgme_op_keylist_next (GpgmeCtx ctx, GpgmeKey *r_key)
The function gpgme_op_keylist_next returns the next key in the list created by a previous gpgme_op_keylist_start operation in the context ctx. The key will have one reference for the user. See section 6.4.3 Manipulating Keys.

This is the only way to get at GpgmeKey objects in GPGME.

If the last key in the list has already been returned, gpgme_op_keylist_next returns GPGME_EOF.

The function returns GPGME_Invalid_Value if ctx or r_key is not a valid pointer, GPGME_No_Request if there is no pending operation, GPGME_Out_Of_Core if there is not enough memory for the operation.

Function: GpgmeError gpgme_op_keylist_end (GpgmeCtx ctx)
The function gpgme_op_keylist_next ends a pending key list operation in the context ctx.

The function returns GPGME_Invalid_Value if ctx is not a valid pointer, GPGME_No_Request if there is no pending operation, GPGME_Out_Of_Core if at some time during the operation there was not enough memory available.

The following example illustrates how all keys containing a certain string (g10code) can be listed with their key ID and the name and e-mail address of the main user ID:

 
GpgmeCtx ctx;
GpgmeError err = gpgme_new (&ctx);

if (!err)
  {
    err = gpgme_op_keylist_start (ctx, "g10code", 0);
    while (!err && (err = gpgme_op_keylist_next (ctx, &key)) != GPGME_EOF)
      {
        printf ("%s: %s <%s>\n",
                gpgme_key_get_string_attr (key, GPGME_ATTR_KEYID, 0, 0),
	        gpgme_key_get_string_attr (key, GPGME_ATTR_NAME, 0, 0),
	        gpgme_key_get_string_attr (key, GPGME_ATTR_EMAIL, 0, 0));
        gpgme_key_release (key);
      }
    gpgme_release (ctx);
  }
if (err)
  {
    fprintf (stderr, "%s: can not list keys: %s\n",
             argv[0], gpgme_strerror (err));
    exit (1);
  }


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4.2 Information About Keys

Function: char * gpgme_key_get_as_xml (GpgmeKey key)
The function gpgme_key_get_as_xml returns a string in XML format describing the key key. The user has to release the string with free.

The function returns NULL if key is not a valid pointer, or there is not enough memory available.

Data type: GpgmeAttr
The GpgmeAttr type is used to specify a key or trust item attribute. The following attributes are defined:

GPGME_ATTR_KEYID
This is the key ID of a sub key. It is representable as a string.

For trust items, the trust item refers to the key with this ID.

GPGME_ATTR_FPR
This is the fingerprint of a sub key. It is representable as a string.

GPGME_ATTR_ALGO
This is the crypto algorithm for which the sub key can be used. It is representable as a string and as a number. The numbers correspond to the enum gcry_pk_algos values in the gcrypt library.

GPGME_ATTR_LEN
This is the key length of a sub key. It is representable as a number.

GPGME_ATTR_CREATED
This is the timestamp at creation time of a sub key. It is representable as a number.

GPGME_ATTR_EXPIRE
This is the expiration time of a sub key. It is representable as a number.

GPGME_ATTR_OTRUST
XXX FIXME (also for trust items)

GPGME_ATTR_USERID
This is a user ID. There can be more than one user IDs in a GpgmeKey object. The first one (with index 0) is the primary user ID. The user ID is representable as a number.

For trust items, this is the user ID associated with this trust item.

GPGME_ATTR_NAME
This is the name belonging to a user ID. It is representable as a string.

GPGME_ATTR_EMAIL
This is the email address belonging to a user ID. It is representable as a string.

GPGME_ATTR_COMMENT
This is the comment belonging to a user ID. It is representable as a string.

GPGME_ATTR_VALIDITY
This is the validity belonging to a user ID. It is representable as a string and as a number. See below for a list of available validities.

For trust items, this is the validity that is associated with this trust item.

GPGME_ATTR_UID_REVOKED
This specifies if a user ID is revoked. It is representable as a number, and is 1 if the user ID is revoked, and 0 otherwise.

GPGME_ATTR_UID_INVALID
This specifies if a user ID is invalid. It is representable as a number, and is 1 if the user ID is invalid, and 0 otherwise.

GPGME_ATTR_LEVEL
This is the trust level of a trust item.

GPGME_ATTR_TYPE
This returns information about the type of key. For the string function this will eother be "PGP" or "X.509". The integer function returns 0 for PGP and 1 for X.509. It is also used for the type of a trust item.

GPGME_ATTR_IS_SECRET
This specifies if the key is a secret key. It is representable as a string or a number. If the key is a secret key, the representation is "1" or 1, otherwise it is NULL or 0.

GPGME_ATTR_KEY_REVOKED
This specifies if a sub key is revoked. It is representable as a number, and is 1 if the key is revoked, and 0 otherwise.

GPGME_ATTR_KEY_INVALID
This specifies if a sub key is invalid. It is representable as a number, and is 1 if the key is invalid, and 0 otherwise.

GPGME_ATTR_KEY_EXPIRED
This specifies if a sub key is expired. It is representable as a number, and is 1 if the key is expired, and 0 otherwise.

GPGME_ATTR_KEY_DISABLED
This specifies if a sub key is disabled. It is representable as a number, and is 1 if the key is disabled, and 0 otherwise.

GPGME_ATTR_KEY_CAPS
This is a description of the capabilities of a sub key. It is representable as a string. The string contains the letter "e" if the key can be used for encryption, "s" if the key can be used for signatures, and "c" if the key can be used for certifications.

GPGME_ATTR_CAN_ENCRYPT
This specifies if a sub key can be used for encryption. It is representable as a number, and is 1 if the sub key can be used for encryption, and 0 otherwise.

GPGME_ATTR_CAN_SIGN
This specifies if a sub key can be used for signatures. It is representable as a number, and is 1 if the sub key can be used for signatures, and 0 otherwise.

GPGME_ATTR_CAN_CERTIFY
This specifies if a sub key can be used for certifications. It is representable as a number, and is 1 if the sub key can be used for certifications, and 0 otherwise.

GPGME_ATTR_SERIAL
The X.509 issuer serial attribute of the key. It is representable as a string.

GPGME_ATTR_ISSUE
The X.509 issuer name attribute of the key. It is representable as a string.

GPGME_ATTR_CHAINID
The X.509 chain ID can be used to build the certification chain. It is representable as a string.

Data type: GpgmeValidity
The GpgmeValidity type is used to specify the validity of a user ID in a key. The following validities are defined:

GPGME_VALIDITY_UNKNOWN
The user ID is of unknown validity. The string representation of this validity is "?".

GPGME_VALIDITY_UNDEFINED
The validity of the user ID is undefined. The string representation of this validity is "q".

GPGME_VALIDITY_NEVER
The user ID is never valid. The string representation of this validity is "n".

GPGME_VALIDITY_MARGINAL
The user ID is marginally valid. The string representation of this validity is "m".

GPGME_VALIDITY_FULL
The user ID is fully valid. The string representation of this validity is "f".

GPGME_VALIDITY_ULTIMATE
The user ID is ultimately valid. The string representation of this validity is "u".

Function: const char * gpgme_key_get_string_attr (GpgmeKey key, GpgmeAttr what, const void *reserved, int idx)
The function gpgme_key_get_string_attr returns the value of the string-representable attribute what of key key. If the attribute is an attribute of a sub key or an user ID, idx specifies the sub key or user ID of which the attribute value is returned. The argument reserved is reserved for later use and should be NULL.

The string returned is only valid as long as the key is valid.

The function returns 0 if an attribute can't be returned as a string, key is not a valid pointer, idx out of range, or reserved not NULL.

Function: unsigned long gpgme_key_get_ulong_attr (GpgmeKey key, GpgmeAttr what, const void *reserved, int idx)
The function gpgme_key_get_ulong_attr returns the value of the number-representable attribute what of key key. If the attribute is an attribute of a sub key or an user ID, idx specifies the sub key or user ID of which the attribute value is returned. The argument reserved is reserved for later use and should be NULL.

The function returns 0 if the attribute can't be returned as a number, key is not a valid pointer, idx out of range, or reserved not NULL.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4.3 Manipulating Keys

Function: void gpgme_key_ref (GpgmeKey key)
The function gpgme_key_ref acquires an additional reference for the key key.

Function: void gpgme_key_unref (GpgmeKey key)
Function: void gpgme_key_release (GpgmeKey key)
The function gpgme_key_ref releases a reference for the key key. If this was the last reference, the key will be destroyed and all resources associated to it will be released.

The function gpgme_key_release is an alias for gpgme_key_unref.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4.4 Generating Keys

Function: GpgmeError gpgme_op_genkey (GpgmeCtx ctx, const char *parms, GpgmeData pubkey, GpgmeData seckey)
The function gpgme_op_genkey generates a new key pair in the context ctx and puts it into the standard key ring if both pubkey and seckey are NULL. In this case the function returns immediately after starting the operation, and does not wait for it to complete. If pubkey is not NULL it should be the handle for an empty (newly created) data object, and upon successful completion the data object will contain the public key. If seckey is not NULL it should be the handle for an empty (newly created) data object, and upon successful completion the data object will contain the secret key.

Note that not all crypto engines support this interface equally. GnuPG does not support pubkey and subkey, they should be both NULL, and the key pair will be added to the standard key ring. GpgSM does only support pubkey, the secret key will be stored by gpg-agent. GpgSM expects pubkey being not NULL.

The argument parms specifies parameters for the key in an XML string. The details about the format of parms are specific to the crypto engine used by ctx. Here is an example for GnuPG as the crypto engine:

 
<GnupgKeyParms format="internal">
Key-Type: DSA
Key-Length: 1024
Subkey-Type: ELG-E
Subkey-Length: 1024
Name-Real: Joe Tester
Name-Comment: with stupid passphrase
Name-Email: joe@foo.bar
Expire-Date: 0
Passphrase: abc
</GnupgKeyParms>

Here is an example for GpgSM as the crypto engine:
 
<GnupgKeyParms format="internal">
Key-Type: RSA
Key-Length: 1024
Name-DN: C=de,O=g10 code,OU=Testlab,CN=Joe 2 Tester
Name-Email: joe@foo.bar
</GnupgKeyParms>

Strings should be given in UTF-8 encoding. The only format supported for now is "internal". The content of the GnupgKeyParms container is passed verbatim to GnuPG. Control statements are not allowed.

The function returns GPGME_No_Error if the operation could be started successfully, GPGME_Invalid_Value if parms is not a valid XML string, GPGME_Not_Supported if pubkey or seckey is not valid, and GPGME_General_Error if no key was created by the backend.

Function: GpgmeError gpgme_op_genkey_start (GpgmeCtx ctx, const char *parms, GpgmeData pubkey, GpgmeData seckey)
The function gpgme_op_genkey_start initiates a gpgme_op_genkey operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the operation could be started successfully, GPGME_Invalid_Value if parms is not a valid XML string, and GPGME_Not_Supported if pubkey or seckey is not NULL.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4.5 Exporting Keys

Function: GpgmeError gpgme_op_export (GpgmeCtx ctx, GpgmeRecipients recipients, GpgmeData keydata)
The function gpgme_op_export extracts the public keys of the user IDs in recipients and returns them in the data buffer keydata. The type of the public keys returned is determined by the ASCII armor attribute set for the context ctx.

The function returns GPGME_No_Error if the operation completed successfully, GPGME_Invalid_Value if recipients is NULL or keydata is not a valid empty data buffer, and passes through any errors that are reported by the crypto engine support routines.

Function: GpgmeError gpgme_op_export_start (GpgmeCtx ctx, GpgmeRecipients recipients, GpgmeData keydata)
The function gpgme_op_export_start initiates a gpgme_op_export operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the operation could be started successfully, and GPGME_Invalid_Value if recipients is NULL or keydata is not a valid empty data buffer.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4.6 Importing Keys

Function: GpgmeError gpgme_op_import (GpgmeCtx ctx, GpgmeData keydata)
The function gpgme_op_import adds the keys in the data buffer keydata to the key ring of the crypto engine used by ctx. The format of keydata can be ASCII armored, for example, but the details are specific to the crypto engine.

More information about the import is available with gpgme_get_op_info. See section 6.6.6 Detailed Results.

The function returns GPGME_No_Error if the import was completed successfully, GPGME_Invalid_Value if keydata if ctx or keydata is not a valid pointer, and GPGME_No_Data if keydata is an empty data buffer.

Function: GpgmeError gpgme_op_import_start (GpgmeCtx ctx, GpgmeData keydata)
The function gpgme_op_import_start initiates a gpgme_op_import operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the import could be started successfully, GPGME_Invalid_Value if keydata if ctx or keydata is not a valid pointer, and GPGME_No_Data if keydata is an empty data buffer.

Function: GpgmeError gpgme_op_import_ext (GpgmeCtx ctx, GpgmeData keydata, int *nr)
The function gpgme_op_import_ext is like gpgme_op_import, but also returns the number of processed keys in nr. This is the same as the count information in the detailed results available with gpgme_get_op_info.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4.7 Deleting Keys

Function: GpgmeError gpgme_op_delete (GpgmeCtx ctx, const GpgmeKey key, int allow_secret)
The function gpgme_op_delete deletes the key key from the key ring of the crypto engine used by ctx. If allow_secret is 0, only public keys are deleted, otherwise secret keys are deleted as well, if that is supported.

The function returns GPGME_No_Error if the key was deleted successfully, GPGME_Invalid_Value if ctx or key is not a valid pointer, GPGME_Invalid_Key if key could not be found in the keyring, and GPGME_Conflict if the secret key for key is available, but allow_secret is zero.

Function: GpgmeError gpgme_op_delete_start (GpgmeCtx ctx, const GpgmeKey key, int allow_secret)
The function gpgme_op_delete_start initiates a gpgme_op_delete operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the operation was started successfully, and GPGME_Invalid_Value if ctx or key is not a valid pointer.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.5 Trust Item Management

Caution: The trust items interface is experimental.

Data type: GpgmeTrustItem
The GpgmeTrustItem type is a handle for a trust item.

6.5.1 Listing Trust Items  Browsing the list of available trust items.
6.5.2 Information About Trust Items  Requesting detailed information about trust items.
6.5.3 Manipulating Trust Items  Operations on trust items.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.5.1 Listing Trust Items

Function: GpgmeError gpgme_op_trustlist_start (GpgmeCtx ctx, const char *pattern, int max_level)
The function gpgme_op_trustlist_start initiates a trust item listing operation inside the context ctx. It sets everything up so that subsequent invocations of gpgme_op_trustlist_next return the trust items in the list.

The string pattern contains an engine specific expression that is used to limit the list to all trust items matching the pattern. It can not be the empty string.

The argument max_level is currently ignored.

The context will be busy until either all trust items are received (and gpgme_op_trustlist_next returns GPGME_EOF), or gpgme_op_trustlist_end is called to finish the operation.

The function returns GPGME_Invalid_Value if ctx is not a valid pointer, and passes through any errors that are reported by the crypto engine support routines.

Function: GpgmeError gpgme_op_trustlist_next (GpgmeCtx ctx, GpgmeTrustItem *r_item)
The function gpgme_op_trustlist_next returns the next trust item in the list created by a previous gpgme_op_trustlist_start operation in the context ctx. The trust item can be destroyed with gpgme_trust_item_release. See section 6.5.3 Manipulating Trust Items.

This is the only way to get at GpgmeTrustItem objects in GPGME.

If the last trust item in the list has already been returned, gpgme_op_trustlist_next returns GPGME_EOF.

The function returns GPGME_Invalid_Value if ctx or r_item is not a valid pointer, GPGME_No_Request if there is no pending operation, GPGME_Out_Of_Core if there is not enough memory for the operation.

Function: GpgmeError gpgme_op_trustlist_end (GpgmeCtx ctx)
The function gpgme_op_trustlist_next ends a pending key list operation in the context ctx.

The function returns GPGME_Invalid_Value if ctx is not a valid pointer, GPGME_No_Request if there is no pending operation, GPGME_Out_Of_Core if at some time during the operation there was not enough memory available.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.5.2 Information About Trust Items

Trust items have attributes which can be queried using the interfaces below. The attribute identifiers are shared with those for key attributes. See section 6.4.2 Information About Keys.

Function: const char * gpgme_trust_item_get_string_attr (GpgmeTrustItem item, GpgmeAttr what, const void *reserved, int idx)
The function gpgme_trust_item_get_string_attr returns the value of the string-representable attribute what of trust item item. The arguments idx and reserved are reserved for later use and should be 0 and NULL respectively.

The string returned is only valid as long as the key is valid.

The function returns 0 if an attribute can't be returned as a string, key is not a valid pointer, idx out of range, or reserved not NULL.

Function: int gpgme_trust_item_get_int_attr (GpgmeTrustItem item, GpgmeAttr what, const void *reserved, int idx)
The function gpgme_trust_item_get_int_attr returns the value of the number-representable attribute what of trust item item. If the attribute occurs more than once in the trust item, the index is specified by idx. However, currently no such attribute exists, so idx should be 0. The argument reserved is reserved for later use and should be NULL.

The function returns 0 if the attribute can't be returned as a number, key is not a valid pointer, idx out of range, or reserved not NULL.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.5.3 Manipulating Trust Items

Function: void gpgme_trust_item_release (GpgmeTrustItem item)
The function gpgme_trust_item_release destroys a GpgmeTrustItem object and releases all associated resources.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6 Crypto Operations

6.6.1 Decrypt  Decrypting a ciphertext.
6.6.2 Verify  Verifying a signature.
6.6.3 Decrypt and Verify  Decrypting a signed ciphertext.
6.6.4 Sign  Creating a signature.
6.6.5 Encrypt  Encrypting a plaintext.
6.6.6 Detailed Results  How to obtain more info about the operation.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.1 Decrypt

Function: GpgmeError gpgme_op_decrypt (GpgmeCtx ctx, GpgmeData cipher, GpgmeData plain)
The function gpgme_op_decrypt decrypts the ciphertext in the data object cipher and stores it into the data object plain.

The function returns GPGME_No_Error if the ciphertext could be decrypted successfully, GPGME_Invalid_Value if ctx, cipher or plain is not a valid pointer, GPGME_No_Data if cipher does not contain any data to decrypt, GPGME_Decryption_Failed if cipher is not a valid cipher text, GPGME_No_Passphrase if the passphrase for the secret key could not be retrieved, and passes through any errors that are reported by the crypto engine support routines.

Function: GpgmeError gpgme_op_decrypt_start (GpgmeCtx ctx, GpgmeData cipher, GpgmeData plain)
The function gpgme_op_decrypt_start initiates a gpgme_op_decrypt operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the operation could be started successfully, and GPGME_Invalid_Value if cipher or plain is not a valid pointer.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.2 Verify

Data type: enum GpgmeSigStat
The GpgmeSigStat type holds the result of a signature check, or the combined result of all signatures. The following results are possible:

GPGME_SIG_STAT_NONE
This status should not occur in normal operation.

GPGME_SIG_STAT_GOOD
This status indicates that the signature is valid. For the combined result this status means that all signatures are valid.

GPGME_SIG_STAT_GOOD_EXP
This status indicates that the signature is valid but expired. For the combined result this status means that all signatures are valid and expired.

GPGME_SIG_STAT_GOOD_EXPKEY
This status indicates that the signature is valid but the key used to verify the signature has expired. For the combined result this status means that all signatures are valid and all keys are expired.

GPGME_SIG_STAT_BAD
This status indicates that the signature is invalid. For the combined result this status means that all signatures are invalid.

GPGME_SIG_STAT_NOKEY
This status indicates that the signature could not be verified due to a missing key. For the combined result this status means that all signatures could not be checked due to missing keys.

GPGME_SIG_STAT_NOSIG
This status indicates that the signature data provided was not a real signature.

GPGME_SIG_STAT_ERROR
This status indicates that there was some other error which prevented the signature verification.

GPGME_SIG_STAT_DIFF
For the combined result this status means that at least two signatures have a different status. You can get each key's status with gpgme_get_sig_status.

Function: GpgmeError gpgme_op_verify (GpgmeCtx ctx, GpgmeData sig, GpgmeData plain, GpgmeSigStat *r_stat)
The function gpgme_op_verify verifies that the signature in the data object sig is a valid signature. If plain is initialized with plaintext data, it is assumed that sig is a detached signature, and its validity for the plaintext given in plain is verified. If plain is an uninitialized data object, it is assumed that sig is a normal (or cleartext) signature, and the plaintext is available in plain after successful verification.

The combined status of all signatures is returned in r_stat. The results of the individual signature verifications can be retrieved with gpgme_get_sig_status and gpgme_get_sig_key.

The function returns GPGME_No_Error if the operation could be completed successfully, GPGME_Invalid_Value if ctx, sig, plain or r_stat is not a valid pointer, GPGME_No_Data if sig does not contain any data to verify, and passes through any errors that are reported by the crypto engine support routines.

Function: GpgmeError gpgme_op_verify_start (GpgmeCtx ctx, GpgmeData sig, GpgmeData plain)
The function gpgme_op_verify_start initiates a gpgme_op_verify operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the operation could be started successfully, GPGME_Invalid_Value if ctx, sig, plain or r_stat is not a valid pointer, and GPGME_No_Data if sig or plain does not contain any data to verify.

Function: const char * gpgme_get_sig_status (GpgmeCtx ctx, int idx, GpgmeSigStat *r_stat, time_t *r_created)
The function gpgme_get_sig_status receives information about a signature after the gpgme_op_verify or gpgme_op_verify_decrypt operation. A single detached signature can contain signatures by more than one key. The idx specifies which signature's information should be retrieved, starting from 0.

The status of the signature will be returned in r_stat if it is not NULL. The creation time stamp of the signature will be returned in r_created if it is not NULL.

The function returns a statically allocated string that contains the fingerprint of the key which signed the plaintext, or NULL if ctx is not a valid pointer, the operation is still pending, or no verification could be performed.

Function: const char * gpgme_get_sig_string_attr (GpgmeCtx ctx, int idx, GpgmeAttr what, int whatidx)
This function is similar to gpgme_get_sig_status but may be used to retrieve more detailed information. ctx should be the context used for the last signature verification, idx is used to enumerate over all signatures starting with 0 and whatidx should be 0 unless otherwise stated.

The following values may be used for what:

GPGME_ATTR_FPR
Return the fingerprint of the key used to create the signature.

GPGME_ATTR_ERRTOK
Return a token with a more detailed error description. A whatidx of 0 returns an error token associated with validity calculation, a value of 1 return an error token related to the certificate checking.

Function: const char * gpgme_get_sig_ulong_attr (GpgmeCtx ctx, int idx, GpgmeAttr waht, int whatidx)
This function is similar to gpgme_get_sig_string_attr but used for attributes which can be represented by an unsigned long data type. ctx should be the context used for the last signature verification, idx is used to enumerate over all signatures starting with 0 and whatidx should be 0 unless otherwise stated.

The following values may be used for what:

GPGME_ATTR_CREATED
Return the creation time of the signature in seconds since Epoch. This is the same value as returned by gpgme_get_sig_status.

GPGME_ATTR_EXPIRE
Return the expiration time of the signature in seconds since Epoch.

GPGME_ATTR_VALIDITY
Returns the validity of the key used to create the signature. This is a shortcut function which avoids an extra key lookup. The value returned is one of GPGME_VALIDITY_UNKNOWN, GPGME_VALIDITY_NEVER, GPGME_VALIDITY_MARGINAL or GPGME_VALIDITY_FULL.

GPGME_ATTR_SIG_STATUS
This is the same value as returned by gpgme_get_sig_status.

GPGME_ATTR_SIG_SUMMARY
This returns a bit vector giving a summary of the signature status. Itprovides an easy interface to a defined semantic of the signature status. Checking just one bit is sufficient to see whether a signature is valid without any restrictions.

The defined bits are:

GPGME_SIGSUM_VALID
The signature is fully valid.

GPGME_SIGSUM_GREEN
The signature is good but one might want to display some extra information. Check the other bits.

GPGME_SIGSUM_RED
The signature is bad. It might be useful to checkother bits and display moe information, i.e. a revoked certificate might not render a signature invalid when the message was received prior to the cause for the revocation.

GPGME_SIGSUM_KEY_REVOKED
The key or at least one certificate has been revoked.

GPGME_SIGSUM_KEY_EXPIRED
The key or one of the certificates has expired. It is probably a good idea to display the date of the expiration.

GPGME_SIGSUM_SIG_EXPIRED
The signature has expired.

GPGME_SIGSUM_KEY_MISSING
Can't verifydue to a missing key o certificate.

GPGME_SIGSUM_CRL_MISSING
The CRL (or an equivalent mechanism) is not available.

GPGME_SIGSUM_CRL_TOO_OLD
Available CRL is too old.

GPGME_SIGSUM_BAD_POLICY
A policy requirement was not met.

GPGME_SIGSUM_SYS_ERROR
A system error occured.

Function: const char * gpgme_get_sig_key (GpgmeCtx ctx, int idx, GpgmeSigKey *r_stat)
The function gpgme_get_sig_status receives a GpgmeKey object for the key which was used to verify the signature after the gpgme_op_verify or gpgme_op_verify_decrypt operation. A single detached signature can contain signatures by more than one key. The idx specifies which signature's information should be retrieved, starting from 0. The key will have on reference for the user.

The function is a convenient way to retrieve the keys belonging to the fingerprints returned by gpgme_get_sig_status.

The function returns GPGME_No_Error if the key could be returned, GPGME_Invalid_Value if r_key is not a valid pointer, GPGME_Invalid_Key if the fingerprint is not valid, GPGME_EOF if idx is too large, or some other error value if a problem occurred requesting the key.

Function: char * gpgme_get_notation (GpgmeCtx ctx)
The function gpgme_get_notation can be used to retrieve notation data from the last signature check in the context ctx.

If there is notation data available from the last signature check, this function may be used to return this notation data as a string. The string is an XML representation of that data embedded in a <notation> container. The user has to release the string with free.

The function returns a string if the notation data is available or NULL if there is no such data available.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.3 Decrypt and Verify

Function: GpgmeError gpgme_op_decrypt_verify (GpgmeCtx ctx, GpgmeData cipher, GpgmeData plain, GpgmeSigStat *r_stat)
The function gpgme_op_decrypt_verify decrypts the ciphertext in the data object cipher and stores it into the data object plain. If cipher contains signatures, they will be verified and their combined status will be returned in r_stat.

After the operation completed, gpgme_op_get_sig_status and gpgme_op_get_sig_key can be used to retrieve more information about the signatures.

The function returns GPGME_No_Error if the ciphertext could be decrypted successfully, GPGME_Invalid_Value if ctx, cipher, plain or r_stat is not a valid pointer, GPGME_No_Data if cipher does not contain any data to decrypt, GPGME_Decryption_Failed if cipher is not a valid cipher text, GPGME_No_Passphrase if the passphrase for the secret key could not be retrieved, and passes through any errors that are reported by the crypto engine support routines.

Function: GpgmeError gpgme_op_decrypt_verify (GpgmeCtx ctx, GpgmeData cipher, GpgmeData plain)
The function gpgme_op_decrypt_verify_start initiates a gpgme_op_decrypt_verify operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the operation could be started successfully, GPGME_Invalid_Value if ctx, cipher, plain or r_stat is not a valid pointer, and GPGME_No_Data if cipher does not contain any data to decrypt.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.4 Sign

A signature can contain signatures by one or more keys. The set of keys used to create a signatures is contained in a context, and is applied to all following signing operations in this context (until the set is changed).

6.6.4.1 Selecting Signers  How to choose the keys to sign with.
6.6.4.2 Creating a Signature  How to create a signature.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.4.1 Selecting Signers

Function: void gpgme_signers_clear (GpgmeCtx ctx)
The function gpgme_signers_clear releases a reference for each key on the signers list and removes the list of signers from the context ctx.

Every context starts with an empty list.

Function: GpgmeError gpgme_signers_add (GpgmeCtx ctx, const GpgmeKey key)
The function gpgme_signers_add adds the key key to the list of signers in the context ctx.

Calling this function acquires an additional reference for the key.

Function: GpgmeKey gpgme_signers_enum (const GpgmeCtx ctx, int seq)
The function gpgme_signers_enum returns the seqth key in the list of signers in the context ctx. An additional reference is acquired for the user.

If seq is out of range, NULL is returned.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.4.2 Creating a Signature

Data type: enum GpgmeSigMode
The GpgmeSigMode type is used to specify the desired type of a signature. The following modes are available:

GPGME_SIG_MODE_NORMAL
A normal signature is made, the output includes the plaintext and the signature.

GPGME_SIG_MODE_DETACH
A detached signature is made.

GPGME_SIG_MODE_CLEAR
A clear text signature is made. The ASCII armor and text mode settings of the context are ignored.

Function: GpgmeError gpgme_op_sign (GpgmeCtx ctx, GpgmeData plain, GpgmeData sig, GpgmeSigMode mode)
The function gpgme_op_sign creates a signature for the text in the data object plain and returns it in the data object sig. The type of the signature created is determined by the ASCII armor and text mode attributes set for the context ctx and the requested signature mode mode.

More information about the signatures is available with gpgme_get_op_info. See section 6.6.6 Detailed Results.

If an S/MIME signed message is created using the CMS crypto engine, the number of certificates to include in the message can be specified with gpgme_set_include_certs. See section 6.3.4 Included Certificates.

The function returns GPGME_No_Error if the signature could be created successfully, GPGME_Invalid_Value if ctx, plain or sig is not a valid pointer, GPGME_No_Data if the signature could not be created, GPGME_No_Passphrase if the passphrase for the secret key could not be retrieved, and passes through any errors that are reported by the crypto engine support routines.

Function: GpgmeError gpgme_op_sign_start (GpgmeCtx ctx, GpgmeData plain, GpgmeData sig, GpgmeSigMode mode)
The function gpgme_op_sign_start initiates a gpgme_op_sign operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the operation could be started successfully, and GPGME_Invalid_Value if ctx, plain or sig is not a valid pointer.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.5 Encrypt

One plaintext can be encrypted for several recipients at the same time. The list of recipients is created independently of any context, and then passed to the encryption operation.

6.6.5.1 Selecting Recipients  How to choose the recipients.
6.6.5.2 Encrypting a Plaintext  How to encrypt a plaintext.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.5.1 Selecting Recipients

Data type: GpgmeRecipients
The GpgmeRecipients type is a handle for a set of recipients that can be used in an encryption process.

Function: GpgmeError gpgme_recipients_new (GpgmeRecipients *r_rset)
The function gpgme_recipients_new creates a new, empty set of recipients and returns a handle for it in r_rset.

The function returns GPGME_No_Error if the recipient set could be created successfully, and GPGME_Out_Of_Core if not enough memory was available.

Function: void gpgme_recipients_release (GpgmeRecipients rset)
The function gpgme_recipients_release destroys the set of recipients rset and releases all associated resources.

Function: GpgmeError gpgme_recipients_add_name (GpgmeRecipients rset, const char *name)
The function gpgme_recipients_add_name adds the recipient name to the set of recipients rset. This is equivalent to gpgme_recipients_add_name_with_validity with a validity of GPGME_VALIDITY_UNKNOWN.

The function returns GPGME_No_Error if the recipient was added successfully, GPGME_Invalid_Value if rset or name is not a valid pointer, and GPGME_Out_Of_Core if not enough memory is available.

Function: GpgmeError gpgme_recipients_add_name_with_validity (GpgmeRecipients rset, const char *name, GpgmeValidity val)
The function gpgme_recipients_add_name_with_validity adds the recipient name with the validity val to the set of recipients rset. If the validity is not known, the function gpgme_recipients_add_name can be used. See section 6.4.2 Information About Keys, for the possible values for val.

The function returns GPGME_No_Error if the recipient was added successfully, GPGME_Invalid_Value if rset or name is not a valid pointer, and GPGME_Out_Of_Core if not enough memory is available.

Function: unsigned int gpgme_recipients_count (const GpgmeRecipients rset)
The function gpgme_recipients_count returns the number of recipients in the set rset.

Function: GpgmeError gpgme_recipients_enum_open (const GpgmeRecipients rset, void **iter)
The function gpgme_recipients_enum_open creates a new iterator iter that can be used to walk through the set of recipients in rset, using gpgme_recipients_enum_read.

If the iterator is not needed anymore, it can be closed with gpgme_recipients_enum_close.

The function returns GPGME_No_Error if the enumerator was successfully created and GPGME_Invalid_Value if rset or iter is not a valid pointer.

Function: const char * gpgme_recipients_enum_read (const GpgmeRecipients rset, void **iter)
The function gpgme_recipients_enum_read returns a string containing the name of the next recipient in the set rset for the iterator iter. The string is valid as long as rset is valid or the function is called the next time with the same recipient set and iterator, whatever is earlier.

Function: GpgmeError gpgme_recipients_enum_close (const GpgmeRecipients rset, void **iter)
The function gpgme_recipients_enum_close releases the iterator iter for the recipient set rset.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.5.2 Encrypting a Plaintext

Function: GpgmeError gpgme_op_encrypt (GpgmeCtx ctx, GpgmeRecipients rset, GpgmeData plain, GpgmeData cipher)
The function gpgme_op_encrypt encrypts the plaintext in the data object plain for the recipients rset and stores the ciphertext in the data object cipher. The type of the ciphertext created is determined by the ASCII armor and text mode attributes set for the context ctx.

If GPGME_Invalid_Recipients is returned, some recipients in rset are invalid, but not all. In this case the plaintext is encrypted for all valid recipients and returned in cipher. More information about the invalid recipients is available with gpgme_get_op_info. See section 6.6.6 Detailed Results.

If recp is NULL, symmetric rather than public key encryption is performed. Symmetrically encrypted cipher text can be deciphered with gpgme_op_decrypt. Note that in this case the crypto backend needs to retrieve a passphrase from the user. Symmetric encryption is currently only supported for the OpenPGP crypto backend.

The function returns GPGME_No_Error if the ciphertext could be created successfully, GPGME_Invalid_Value if ctx, rset, plain or cipher is not a valid pointer, GPGME_No_Recipients if rset does not contain any valid recipients, GPGME_Invalid_Recipients if rset contains some invalid recipients, GPGME_No_Passphrase if the passphrase for the secret key could not be retrieved, and passes through any errors that are reported by the crypto engine support routines.

Function: GpgmeError gpgme_op_encrypt_start (GpgmeCtx ctx, GpgmeRecipients rset, GpgmeData plain, GpgmeData cipher)
The function gpgme_op_encrypt_start initiates a gpgme_op_encrypt operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the operation could be started successfully, GPGME_Invalid_Value if ctx, rset, plain or cipher is not a valid pointer, and GPGME_No_Recipients if rset does not contain any valid recipients.

Function: GpgmeError gpgme_op_encrypt_sign (GpgmeCtx ctx, GpgmeRecipients rset, GpgmeData plain, GpgmeData cipher)
The function gpgme_op_encrypt_sign does a combined encrypt and sign operation. It is used like gpgme_op_encrypt, but the ciphertext also contains signatures for the signers listed in ctx.

The combined encrypt and sign operation is currently only available for the OpenPGP crypto engine.

Function: GpgmeError gpgme_op_encrypt_sign_start (GpgmeCtx ctx, GpgmeRecipients rset, GpgmeData plain, GpgmeData cipher)
The function gpgme_op_encrypt_sign_start initiates a gpgme_op_encrypt_sign operation. It can be completed by calling gpgme_wait on the context. See section 6.7.1 Waiting For Completion.

The function returns GPGME_No_Error if the operation could be started successfully, GPGME_Invalid_Value if ctx, rset, plain or cipher is not a valid pointer, and GPGME_No_Recipients if rset does not contain any valid recipients.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6.6 Detailed Results

Function: char * gpgme_get_op_info (GpgmeCtx ctx, int reserved)
The function gpgme_get_op_info retrieves more information about the last crypto operation.

The function returns a string in the XML format. The user has to release the string with free.

Here is a sample of the information that might be returned:
 
<GnupgOperationInfo>
  <signature>
    <detached/> <!-- or cleartext or standard -->
    <algo>17</algo>
    <hashalgo>2</hashalgo>
    <micalg>pgp-sha1</micalg>
    <sigclass>01</sigclass>
    <created>9222222</created>
    <fpr>121212121212121212</fpr>
  </signature>
</GnupgOperationInfo>

Currently, the only operations that return additional information are encrypt, sign and import. See section 6.6.5 Encrypt, See section 6.6.4 Sign, See section 6.4.6 Importing Keys.

The function returns a string or NULL if no such data is available.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7 Run Control

GPGME supports running operations synchronously and asynchronously. You can use asynchronous operation to set up a context up to initiating the desired operation, but delay performing it to a later point.

Furthermore, you can use an external event loop to control exactly when GPGME runs. This ensures that GPGME only runs when necessary and also prevents it from blocking for a long time.

6.7.1 Waiting For Completion  Waiting until an operation is completed.
6.7.2 Cancelling an Operation  Interrupting a running operation.
6.7.3 Hooking Up Into Idle Time  Doing something when nothing has to be done.
6.7.4 Using External Event Loops  Advanced control over what happens when.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7.1 Waiting For Completion

Function: GpgmeCtx gpgme_wait (GpgmeCtx ctx, GpgmeError *status, int hang)
The function gpgme_wait continues the pending operation within the context ctx. In particular, it ensures the data exchange between GPGME and the crypto backend and watches over the run time status of the backend process.

If hang is true, the function does not return until the operation is completed or cancelled. Otherwise the function will not block for a long time.

The error status of the finished operation is returned in status if gpgme_wait does not return NULL.

The ctx argument can be NULL. In that case, gpgme_wait waits for any context to complete its operation.

gpgme_wait can be used only in conjunction with any context that has a pending operation initiated with one of the gpgme_op_*_start functions except gpgme_op_keylist_start and gpgme_op_trustlist_start (for which you should use the corresponding gpgme_op_*_next functions). If ctx is NULL, all of such contexts are waited upon and possibly returned. Synchronous operations running in parallel, as well as key and trust item list operations, do not affect gpgme_wait.

In a multi-threaded environment, only one thread should ever call gpgme_wait at any time, irregardless if ctx is specified or not. This means that all calls to this function should be fully synchronized by locking primitives.

The function returns the ctx of the context which has finished the operation.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7.2 Cancelling an Operation

Function: void gpgme_cancel (GpgmeCtx ctx)
The function gpgme_cancel tries to cancel the pending operation. A running synchronous operation in the context or the function gpgme_wait with this context as its ctx argument might notice the cancellation flag and return. It is currently not guaranteed to work under all circumstances. Its current primary purpose is to prevent asking for a passphrase again in the passphrase callback.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7.3 Hooking Up Into Idle Time

Data type: void (*GpgmeIdleFunc) (void)
The GpgmeIdleFunc type is the type of functions usable as an idle function that can be registered with gpgme_register_idle.

Function: GpgmeIdleFunc gpgme_register_idle (GpgmeIdleFunc idle)
The function gpgme_register_idle can be used to register idle as the idle function.

idle will be called whenever GPGME thinks that it is idle and time can better be spent elsewhere. Setting idle to NULL disables use of the idle function (this is the default).

The function returns the old idle function, or NULL if none was registered yet.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7.4 Using External Event Loops

GPGME hides the complexity of the communication between the library and the crypto engine. The price of this convenience is that the calling thread can block arbitrary long waiting for the data returned by the crypto engine. In single-threaded programs, in particular if they are interactive, this is an unwanted side-effect. OTOH, if gpgme_wait is used without the hang option being enabled, it might be called unnecessarily often, wasting CPU time that could be used otherwise.

The I/O callback interface described in this section lets the user take control over what happens when. GPGME will provide the user with the file descriptors that should be monitored, and the callback functions that should be invoked when a file descriptor is ready for reading or writing. It is then the user's responsibility to decide when to check the file descriptors and when to invoke the callback functions. Usually this is done in an event loop, that also checks for events in other parts of the program. If the callback functions are only called when the file descriptors are ready, GPGME will never block. This gives the user mroe control over the program flow, and allows to perform other tasks when GPGME would block otherwise.

By using this advanced mechanism, GPGME can be integrated smoothly into GUI toolkits like GTK+ even for single-threaded programs.

6.7.4.1 I/O Callback Interface  How I/O callbacks are registered.
6.7.4.2 Registering I/O Callbacks  How to use I/O callbacks for a context.
6.7.4.3 I/O Callback Example  An example how to use I/O callbacks.
6.7.4.4 I/O Callback Example GTK+  How to use GPGME with GTK+.
6.7.4.5 I/O Callback Example GDK  How to use GPGME with GDK.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7.4.1 I/O Callback Interface

Data type: void (*GpgmeIOCb) (void *data, int fd)
The GpgmeIOCb type is the type of functions which GPGME wants to register as I/O callback handlers using the GpgmeRegisterIOCb functions provided by the user.

data and fd are provided by GPGME when the I/O callback handler is registered, and should be passed through to the handler when it is invoked by the user because it noticed activity on the file descriptor fd.

Data type: GpgmeError (*GpgmeRegisterIOCb) (void *data, int fd, int dir, GpgmeIOCb fnc, void *fnc_data, void **tag)
The GpgmeRegisterIOCb type is the type of functions which can be called by GPGME to register an I/O callback funtion fnc for the file descriptor fd with the user. fnc_data should be passed as the first argument to fnc when the handler is invoked (the second argument should be fd). If dir is 0, fnc should be called by the user when fd is ready for writing. If dir is 1, fnc should be called when fd is ready for reading.

data was provided by the user when registering the GpgmeRegisterIOCb function with GPGME and will always be passed as the first argument when registering a callback function. For example, the user can use this to determine the event loop to which the file descriptor should be added.

GPGME will call this function when a crypto operation is initiated in a context for which the user has registered I/O callback handler functions with gpgme_set_io_cbs. It can also call this function when it is in an I/O callback handler for a file descriptor associated to this context.

The user should return a unique handle in tag identifying this I/O callback registration, which will be passed to the GpgmeRegisterIOCb function without interpretation when the file descriptor should not be monitored anymore.

Data type: void (*GpgmeRemoveIOCb) (void *tag)
The GpgmeRemoveIOCb type is the type of functions which can be called by GPGME to remove an I/O callback handler that was registered before. tag is the handle that was returned by the GpgmeRegisterIOCb for this I/O callback.

GPGME can call this function when a crypto operation is in an I/O callback. It will also call this function when the context is destroyed while an operation is pending.

Data type: enum GpgmeEventIO
The GpgmeEventIO type specifies the type of an event that is reported to the user by GPGME as a consequence of an I/O operation. The following events are defined:

GPGME_EVENT_DONE
The operation is finished, the last I/O callback for this operation was removed. The accompanying type_data points to a GpgmeError variable that contains the status of the operation that finished. This event is signalled after the last I/O callback has been removed.

GPGME_EVENT_NEXT_KEY
In a gpgme_op_keylist_start operation, the next key was received from the crypto engine. The accompanying type_data is a GpgmeKey variable that contains the key with one reference for the user.

GPGME_EVENT_NEXT_TRUSTITEM
In a gpgme_op_trustlist_start operation, the next trust item was received from the crypto engine. The accompanying type_data is a GpgmeTrustItem variable that contains the trust item with one reference for the user.

Data type: void (*GpgmeEventIOCb) (void *data, GpgmeEventIO type, void *type_data)
The GpgmeEventIOCb type is the type of functions which can be called by GPGME to signal an event for an operation running in a context which has I/O callback functions registered by the user.

data was provided by the user when registering the GpgmeEventIOCb function with GPGME and will always be passed as the first argument when registering a callback function. For example, the user can use this to determine the context in which this event has occured.

type will specify the type of event that has occured. type_data specifies the event further, as described in the above list of possible GpgmeEventIO types.

GPGME can call this function in an I/O callback handler.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7.4.2 Registering I/O Callbacks

Data type: struct GpgmeIOCbs
This structure is used to store the I/O callback interface functions described in the previous section. It has the following members:

GpgmeRegisterIOCb add
This is the function called by GPGME to register an I/O callback handler. It must be specified.

void *add_data
This is passed as the first argument to the add function when it is called by GPGME. For example, it can be used to determine the event loop to which the file descriptor should be added.

GpgmeRemoveIOCb remove
This is the function called by GPGME to remove an I/O callback handler. It must be specified.

GpgmeEventIOCb event
This is the function called by GPGME to signal an event for an operation. It is optional, but if you don't specify it, you can not retrieve the return value of the operation.

void *event_data
This is passed as the first argument to the event function when it is called by GPGME. For example, it can be used to determine the context in which the event has occured.

Function: void gpgme_set_io_cbs (GpgmeCtx ctx, struct GpgmeIOCbs *io_cbs)
The function gpgme_set_io_cbs enables the I/O callback interface for the context ctx. The I/O callback functions are specified by io_cbs.

If io_cbs->add is NULL, the I/O callback interface is disabled for the context, and normal operation is restored.

Function: void gpgme_get_io_cbs (GpgmeCtx ctx, struct GpgmeIOCbs *io_cbs)
The function gpgme_get_io_cbs returns the I/O callback functions set with gpgme_set_io_cbs in io_cbs.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7.4.3 I/O Callback Example

To actually use an external event loop, you have to implement the I/O callback functions that are used by GPGME to register and unregister file descriptors. Furthermore, you have to actually monitor these file descriptors for activity and call the appropriate I/O callbacks.

The following example illustrates how to do that. The example uses locking to show in which way the the callbacks and the event loop can run concurrently. For the event loop, we use a fixed array. For a real-world implementation, you should use a dynamically sized structure because the number of file descriptors needed for a crypto operation in GPGME is not predictable.

 
#include <pthread.h>
#include <sys/types.h>
#include <gpgme.h>

/* The following structure holds the result of a crypto operation.  */
struct op_result
{
  int done;
  GpgmeError err;
};

/* The following structure holds the data associated with one I/O
callback.  */
struct one_fd
{
  int fd;
  int dir;
  GpgmeIOCb fnc;
  void *fnc_data;
};

struct event_loop
{
  pthread_mutex_t lock;
#define MAX_FDS 32
  /* Unused slots are marked with FD being -1.  */
  struct one_fd fds[MAX_FDS];
};

The following functions implement the I/O callback interface.

 
GpgmeError
add_io_cb (void *data, int fd, int dir, GpgmeIOCb fnc, void *fnc_data,
	   void **r_tag)
{
  struct event_loop *loop = data;
  struct one_fd *fds = loop->fds;
  int i;

  pthread_mutex_lock (&loop->lock);
  for (i = 0; i < MAX_FDS; i++)
    {
      if (fds[i].fd == -1)
	{
	  fds[i].fd = fd;
	  fds[i].dir = dir;
	  fds[i].fnc = fnc;
	  fds[i].fnc_data = fnc_data;
	  break;
	}
    }
  pthread_mutex_unlock (&loop->lock);
  if (i == MAX_FDS)
    return GPGME_General_Error;
  *r_tag = &fds[i];
  return 0;
}

void
remove_io_cb (void *tag)
{
  struct one_fd *fd = tag;

  pthread_mutex_lock (&loop->lock);
  fd->fd = -1;
  pthread_mutex_unlock (&loop->lock);
}

void
event_io_cb (void *data, GpgmeEventIO type, void *type_data)
{
  struct op_result *result = data;
  GpgmeError *err = data;

  /* We don't support list operations here.  */
  if (type == GPGME_EVENT_DONE)
    {
      result->done = 1;
      result->err = *data;
    }
}

The final missing piece is the event loop, which will be presented next. We only support waiting for the success of a single operation.

 
int
do_select (struct event_loop *loop)
{
  fd_set rfds;
  fd_set wfds;
  int i, n;
  int any = 0;

  pthread_mutex_lock (&loop->lock);
  FD_ZERO (&rfds);
  FD_ZERO (&wfds);
  for (i = 0; i < FDLIST_MAX; i++)
    if (fdlist[i].fd != -1)
      FD_SET (fdlist[i].fd, fdlist[i].dir ? &rfds : &wfds);
  pthread_mutex_unlock (&loop->unlock);

  do
    {
      n = select (FD_SETSIZE, &rfds, &wfds, NULL, 0);
    }
  while (n < 0 && errno == EINTR);

  if (n < 0)
    return n;	/* Error or timeout.  */

  pthread_mutex_lock (&loop->lock);
  for (i = 0; i < FDLIST_MAX && n; i++)
    {
      if (fdlist[i].fd != -1)
	{
	  if (FD_ISSET (fdlist[i].fd, fdlist[i].dir ? &rfds : &wfds))
	    {
	      assert (n);
	      n--;
	      any = 1;
              /* The I/O callback handler can register/remove callbacks,
                 so we have to unlock the file descriptor list.  */
              pthread_mutex_unlock (&loop->lock);
	      (*fdlist[i].fnc) (fdlist[i].fnc_data, fdlist[i].fd);
              pthread_mutex_lock (&loop->lock);
	    }
	}
    }
  pthread_mutex_unlock (&loop->lock);
  return any;
}

void
wait_for_op (struct event_loop *loop, struct op_result *result)
{
  int ret;

  do
    {
      ret = do_select (loop);
    }
  while (ret >= 0 && !result->done);
  return ret;
}

The main function shows how to put it all together.

 
int
main (int argc, char *argv[])
{
  struct event_loop loop;
  struct op_result result;
  GpgmeCtx ctx;
  GpgmeError err;
  GpgmeData sig, text;
  GpgmeSigStat status;
  int i;
  struct GpgmeIOCbs io_cbs =
  {
    add_io_cb,
    &loop,
    remove_io_cb,
    event_io_cb,
    &result
  };

  /* Initialize the loop structure.  */
  loop.lock = PTHREAD_MUTEX_INITIALIZER;
  for (i = 0; i < MAX_FDS; i++)
    loop->fds[i].fd = -1;

  /* Initialize the result structure.  */
  result.done = 0;

  err = gpgme_data_new_from_file (&sig, "signature", 1);
  if (!err)
    err = gpgme_data_new_from_file (&text, "text", 1);
  if (!err)
    err = gpgme_new (&ctx);
  if (!err)
    {
       gpgme_set_io_cbs (ctx, &io_cbs);
       err = gpgme_op_verify_start (ctx, sig, text, &status);
    }
  if (err)
    {
      fprintf (stderr, "gpgme error: %s\n", gpgme_strerror (err));
      exit (1);
    }

  wait_for_op (&loop, &result);
  if (!result.done)
    {
      fprintf (stderr, "select error\n");
      exit (1);
    }
  if (!result.err)
    {
      fprintf (stderr, "verification failed: %s\n", gpgme_strerror (result.err));
      exit (1);
    }
  /* Evaluate STATUS.  */
  ...
  return 0;
}


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7.4.4 I/O Callback Example GTK+

The I/O callback interface can be used to integrate GPGME with the GTK+ event loop. The following code snippets shows how this can be done using the appropriate register and remove I/O callback functions. In this example, the private data of the register I/O callback function is unused. The event notifications is missing because it does not require any GTK+ specific setup.

 
#include <gtk/gtk.h>

struct my_gpgme_io_cb
{
  GpgmeIOCb fnc;
  void *fnc_data;
  guint input_handler_id
};

void
my_gpgme_io_cb (gpointer data, gint source, GdkInputCondition condition)
{
  struct my_gpgme_io_cb *iocb = data;
  (*(iocb->fnc)) (iocb->data, source);
}

void
my_gpgme_remove_io_cb (void *data)
{
  struct my_gpgme_io_cb *iocb = data;
  gtk_input_remove (data->input_handler_id);
}

void
my_gpgme_register_io_callback (void *data, int fd, int dir, GpgmeIOCb fnc,
                               void *fnc_data, void **tag)
{
  struct my_gpgme_io_cb *iocb = g_malloc (sizeof (struct my_gpgme_io_cb));
  iocb->fnc = fnc;
  iocb->data = fnc_data;
  iocb->input_handler_id = gtk_input_add_full (fd, dir
                                                   ? GDK_INPUT_READ
                                                   : GDK_INPUT_WRITE,
                                               my_gpgme_io_callback,
                                               0, iocb, NULL);
  *tag = iocb;
  return 0;
}


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7.4.5 I/O Callback Example GDK

The I/O callback interface can also be used to integrate GPGME with the GDK event loop. The following code snippets shows how this can be done using the appropriate register and remove I/O callback functions. In this example, the private data of the register I/O callback function is unused. The event notifications is missing because it does not require any GDK specific setup.

It is very similar to the GTK+ example in the previous section.

 
#include <gdk/gdk.h>

struct my_gpgme_io_cb
{
  GpgmeIOCb fnc;
  void *fnc_data;
  gint tag;
};

void
my_gpgme_io_cb (gpointer data, gint source, GdkInputCondition condition)
{
  struct my_gpgme_io_cb *iocb = data;
  (*(iocb->fnc)) (iocb->data, source);
}

void
my_gpgme_remove_io_cb (void *data)
{
  struct my_gpgme_io_cb *iocb = data;
  gdk_input_remove (data->tag);
}

void
my_gpgme_register_io_callback (void *data, int fd, int dir, GpgmeIOCb fnc,
                               void *fnc_data, void **tag)
{
  struct my_gpgme_io_cb *iocb = g_malloc (sizeof (struct my_gpgme_io_cb));
  iocb->fnc = fnc;
  iocb->data = fnc_data;
  iocb->tag = gtk_input_add_full (fd, dir ? GDK_INPUT_READ : GDK_INPUT_WRITE,
                                  my_gpgme_io_callback, iocb, NULL);
  *tag = iocb;
  return 0;
}


[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated by John Goerzen on November, 21 2002 using texi2html