Imported Upstream version 2.1.10
[platform/upstream/gpg2.git] / g10 / keydb.h
1 /* keydb.h - Key database
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3  *               2006, 2010 Free Software Foundation, Inc.
4  * Copyright (C) 2015 g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #ifndef G10_KEYDB_H
23 #define G10_KEYDB_H
24
25 #include <assuan.h>
26
27 #include "types.h"
28 #include "util.h"
29 #include "packet.h"
30
31 /* What qualifies as a certification (rather than a signature?) */
32 #define IS_CERT(s)       (IS_KEY_SIG(s) || IS_UID_SIG(s) || IS_SUBKEY_SIG(s) \
33                          || IS_KEY_REV(s) || IS_UID_REV(s) || IS_SUBKEY_REV(s))
34 #define IS_SIG(s)        (!IS_CERT(s))
35 #define IS_KEY_SIG(s)    ((s)->sig_class == 0x1f)
36 #define IS_UID_SIG(s)    (((s)->sig_class & ~3) == 0x10)
37 #define IS_SUBKEY_SIG(s) ((s)->sig_class == 0x18)
38 #define IS_KEY_REV(s)    ((s)->sig_class == 0x20)
39 #define IS_UID_REV(s)    ((s)->sig_class == 0x30)
40 #define IS_SUBKEY_REV(s) ((s)->sig_class == 0x28)
41
42 struct getkey_ctx_s;
43 typedef struct getkey_ctx_s *GETKEY_CTX;
44 typedef struct getkey_ctx_s *getkey_ctx_t;
45
46 /****************
47  * A Keyblock is all packets which form an entire certificate;
48  * i.e. the public key, certificate, trust packets, user ids,
49  * signatures, and subkey.
50  *
51  * This structure is also used to bind arbitrary packets together.
52  */
53
54 struct kbnode_struct {
55     KBNODE next;
56     PACKET *pkt;
57     int flag;
58     int private_flag;
59     ulong recno;  /* used while updating the trustdb */
60 };
61
62 #define is_deleted_kbnode(a)  ((a)->private_flag & 1)
63 #define is_cloned_kbnode(a)   ((a)->private_flag & 2)
64
65
66 enum resource_type {
67     rt_UNKNOWN = 0,
68     rt_RING = 1
69 };
70
71
72 /* Bit flags used with build_pk_list.  */
73 #define PK_LIST_ENCRYPT_TO 1   /* This is an encrypt-to recipient.  */
74 #define PK_LIST_HIDDEN     2   /* This is a hidden recipient.       */
75 #define PK_LIST_CONFIG     4   /* Specified via config file.        */
76 /* To store private data in the flags they must be left shifted by
77    this value.  */
78 #define PK_LIST_SHIFT      3
79
80 /****************
81  * A data structure to hold information about the external position
82  * of a keyblock.
83  */
84 struct keyblock_pos_struct {
85     int   resno;     /* resource number */
86     enum resource_type rt;
87     off_t offset;    /* position information */
88     unsigned count;  /* length of the keyblock in packets */
89     iobuf_t  fp;     /* Used by enum_keyblocks. */
90     int secret;      /* working on a secret keyring */
91     PACKET *pkt;     /* ditto */
92     int valid;
93 };
94 typedef struct keyblock_pos_struct KBPOS;
95
96 /* Structure to hold a couple of public key certificates. */
97 typedef struct pk_list *PK_LIST;  /* Deprecated. */
98 typedef struct pk_list *pk_list_t;
99 struct pk_list
100 {
101   PK_LIST next;
102   PKT_public_key *pk;
103   int flags; /* flag bit 1==throw_keyid */
104 };
105
106 /* Structure to hold a list of secret key certificates.  */
107 typedef struct sk_list *SK_LIST;
108 struct sk_list
109 {
110   SK_LIST next;
111   PKT_public_key *pk;
112   int mark; /* not used */
113 };
114
115 /* structure to collect all information which can be used to
116  * identify a public key */
117 typedef struct pubkey_find_info *PUBKEY_FIND_INFO;
118 struct pubkey_find_info {
119     u32  keyid[2];
120     unsigned nbits;
121     byte pubkey_algo;
122     byte fingerprint[MAX_FINGERPRINT_LEN];
123     char userid[1];
124 };
125
126
127 typedef struct keydb_handle *KEYDB_HANDLE;
128
129
130 /* Helper type for preference fucntions. */
131 union pref_hint
132 {
133   int digest_length;
134 };
135
136
137 /*-- keydb.c --*/
138
139 #define KEYDB_RESOURCE_FLAG_PRIMARY  2  /* The primary resource.  */
140 #define KEYDB_RESOURCE_FLAG_DEFAULT  4  /* The default one.  */
141 #define KEYDB_RESOURCE_FLAG_READONLY 8  /* Open in read only mode.  */
142 #define KEYDB_RESOURCE_FLAG_GPGVDEF 16  /* Default file for gpgv.  */
143
144 /* Format a search term for debugging output.  The caller must free
145    the result.  */
146 char *keydb_search_desc_dump (struct keydb_search_desc *desc);
147
148 /* Register a resource (keyring or keybox).  The first keyring or
149    keybox that is added using this function is created if it does not
150    already exist and the KEYDB_RESOURCE_FLAG_READONLY is not set.
151
152    FLAGS are a combination of the KEYDB_RESOURCE_FLAG_* constants.
153
154    URL must have the following form:
155
156      gnupg-ring:filename  = plain keyring
157      gnupg-kbx:filename   = keybox file
158      filename             = check file's type (create as a plain keyring)
159
160    Note: on systems with drive letters (Windows) invalid URLs (i.e.,
161    those with an unrecognized part before the ':' such as "c:\...")
162    will silently be treated as bare filenames.  On other systems, such
163    URLs will cause this function to return GPG_ERR_GENERAL.
164
165    If KEYDB_RESOURCE_FLAG_DEFAULT is set, the resource is a keyring
166    and the file ends in ".gpg", then this function also checks if a
167    file with the same name, but the extension ".kbx" exists, is a
168    keybox and the OpenPGP flag is set.  If so, this function opens
169    that resource instead.
170
171    If the file is not found, KEYDB_RESOURCE_FLAG_GPGVDEF is set and
172    the URL ends in ".kbx", then this function will try opening the
173    same URL, but with the extension ".gpg".  If that file is a keybox
174    with the OpenPGP flag set or it is a keyring, then we use that
175    instead.
176
177    If the file is not found, KEYDB_RESOURCE_FLAG_DEFAULT is set, the
178    file should be created and the file's extension is ".gpg" then we
179    replace the extension with ".kbx".
180
181
182    If the KEYDB_RESOURCE_FLAG_PRIMARY is set and the resource is a
183    keyring (not a keybox), then this resource is considered the
184    primary resource.  This is used by keydb_locate_writable().  If
185    another primary keyring is set, then that keyring is considered the
186    primary.
187
188    If KEYDB_RESOURCE_FLAG_READONLY is set and the resource is a
189    keyring (not a keybox), then the keyring is marked as read only and
190    operations just as keyring_insert_keyblock will return
191    GPG_ERR_ACCESS.  */
192 gpg_error_t keydb_add_resource (const char *url, unsigned int flags);
193
194 /* Dump some statistics to the log.  */
195 void keydb_dump_stats (void);
196
197 /* Create a new database handle.  Returns NULL on error, sets ERRNO,
198    and prints an error diagnostic. */
199 KEYDB_HANDLE keydb_new (void);
200
201 /* Free all resources owned by the database handle.  */
202 void keydb_release (KEYDB_HANDLE hd);
203
204 /* Set a flag on the handle to suppress use of cached results.  This
205    is required for updating a keyring and for key listings.  Fixme:
206    Using a new parameter for keydb_new might be a better solution.  */
207 void keydb_disable_caching (KEYDB_HANDLE hd);
208
209 /* Save the last found state and invalidate the current selection
210    (i.e., the entry selected by keydb_search() is invalidated and
211    something like keydb_get_keyblock() will return an error).  This
212    does not change the file position.  This makes it possible to do
213    something like:
214
215      keydb_search (hd, ...);  // Result 1.
216      keydb_push_found_state (hd);
217        keydb_search_reset (hd);
218        keydb_search (hd, ...);  // Result 2.
219      keydb_pop_found_state (hd);
220      keydb_get_keyblock (hd, ...);  // -> Result 1.
221
222    Note: it is only possible to save a single save state at a time.
223    In other words, the the save stack only has room for a single
224    instance of the state.  */
225 void keydb_push_found_state (KEYDB_HANDLE hd);
226
227 /* Restore the previous save state.  If the saved state is invalid,
228    this is equivalent to */
229 void keydb_pop_found_state (KEYDB_HANDLE hd);
230
231 /* Return the file name of the resource in which the current search
232    result was found or, if there is no search result, the filename of
233    the current resource (i.e., the resource that the file position
234    points to).  Note: the filename is not necessarily the URL used to
235    open it!
236
237    This function only returns NULL if no handle is specified, in all
238    other error cases an empty string is returned.  */
239 const char *keydb_get_resource_name (KEYDB_HANDLE hd);
240
241 /* Return the keyblock last found by keydb_search() in *RET_KB.
242
243    On success, the function returns 0 and the caller must free *RET_KB
244    using release_kbnode().  Otherwise, the function returns an error
245    code.
246
247    The returned keyblock has the kbnode flag bit 0 set for the node
248    with the public key used to locate the keyblock or flag bit 1 set
249    for the user ID node.  */
250 gpg_error_t keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb);
251
252 /* Replace the currently selected keyblock (i.e., the last result
253    returned by keydb_search) with the key block in KB.
254
255    This doesn't do anything if --dry-run was specified.
256
257    Returns 0 on success.  Otherwise, it returns an error code.  */
258 gpg_error_t keydb_update_keyblock (KEYDB_HANDLE hd, kbnode_t kb);
259
260 /* Insert a keyblock into one of the underlying keyrings or keyboxes.
261
262    Be default, the keyring / keybox from which the last search result
263    came is used.  If there was no previous search result (or
264    keydb_search_reset was called), then the keyring / keybox where the
265    next search would start is used (i.e., the current file position).
266
267    Note: this doesn't do anything if --dry-run was specified.
268
269    Returns 0 on success.  Otherwise, it returns an error code.  */
270 gpg_error_t keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb);
271
272 /* Delete the currently selected keyblock.  If you haven't done a
273    search yet on this database handle (or called keydb_search_reset),
274    then this will return an error.
275
276    Returns 0 on success or an error code, if an error occurs.  */
277 gpg_error_t keydb_delete_keyblock (KEYDB_HANDLE hd);
278
279 /* A database may consists of multiple keyrings / key boxes.  This
280    sets the "file position" to the start of the first keyring / key
281    box that is writable (i.e., doesn't have the read-only flag set).
282
283    This first tries the primary keyring (the last keyring (not
284    keybox!) added using keydb_add_resource() and with
285    KEYDB_RESOURCE_FLAG_PRIMARY set).  If that is not writable, then it
286    tries the keyrings / keyboxes in the order in which they were
287    added.  */
288 gpg_error_t keydb_locate_writable (KEYDB_HANDLE hd);
289
290 /* Rebuild the on-disk caches of all key resources.  */
291 void keydb_rebuild_caches (int noisy);
292
293 /* Return the number of skipped blocks (because they were to large to
294    read from a keybox) since the last search reset.  */
295 unsigned long keydb_get_skipped_counter (KEYDB_HANDLE hd);
296
297 /* Clears the current search result and resets the handle's position
298    so that the next search starts at the beginning of the database
299    (the start of the first resource).
300
301    Returns 0 on success and an error code if an error occurred.
302    (Currently, this function always returns 0 if HD is valid.)  */
303 gpg_error_t keydb_search_reset (KEYDB_HANDLE hd);
304
305 /* Search the database for keys matching the search description.  If
306    the DB contains any legacy keys, these are silently ignored.
307
308    DESC is an array of search terms with NDESC entries.  The search
309    terms are or'd together.  That is, the next entry in the DB that
310    matches any of the descriptions will be returned.
311
312    Note: this function resumes searching where the last search left
313    off (i.e., at the current file position).  If you want to search
314    from the start of the database, then you need to first call
315    keydb_search_reset().
316
317    If no key matches the search description, returns
318    GPG_ERR_NOT_FOUND.  If there was a match, returns 0.  If an error
319    occurred, returns an error code.
320
321    The returned key is considered to be selected and the raw data can,
322    for instance, be returned by calling keydb_get_keyblock().  */
323 gpg_error_t keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
324                           size_t ndesc, size_t *descindex);
325
326 /* Return the first non-legacy key in the database.
327
328    If you want the very first key in the database, you can directly
329    call keydb_search with the search description
330    KEYDB_SEARCH_MODE_FIRST.  */
331 gpg_error_t keydb_search_first (KEYDB_HANDLE hd);
332
333 /* Return the next key (not the next matching key!).
334
335    Unlike calling keydb_search with KEYDB_SEARCH_MODE_NEXT, this
336    function silently skips legacy keys.  */
337 gpg_error_t keydb_search_next (KEYDB_HANDLE hd);
338
339 /* This is a convenience function for searching for keys with a long
340    key id.
341
342    Note: this function resumes searching where the last search left
343    off.  If you want to search the whole database, then you need to
344    first call keydb_search_reset().  */
345 gpg_error_t keydb_search_kid (KEYDB_HANDLE hd, u32 *kid);
346
347 /* This is a convenience function for searching for keys with a long
348    (20 byte) fingerprint.
349
350    Note: this function resumes searching where the last search left
351    off.  If you want to search the whole database, then you need to
352    first call keydb_search_reset().  */
353 gpg_error_t keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr);
354
355
356 /*-- pkclist.c --*/
357 void show_revocation_reason( PKT_public_key *pk, int mode );
358 int  check_signatures_trust( PKT_signature *sig );
359
360 void release_pk_list (PK_LIST pk_list);
361 int  build_pk_list (ctrl_t ctrl,
362                     strlist_t rcpts, PK_LIST *ret_pk_list, unsigned use);
363 gpg_error_t find_and_check_key (ctrl_t ctrl,
364                                 const char *name, unsigned int use,
365                                 int mark_hidden, pk_list_t *pk_list_addr);
366
367 int  algo_available( preftype_t preftype, int algo,
368                      const union pref_hint *hint );
369 int  select_algo_from_prefs( PK_LIST pk_list, int preftype,
370                              int request, const union pref_hint *hint);
371 int  select_mdc_from_pklist (PK_LIST pk_list);
372 void warn_missing_mdc_from_pklist (PK_LIST pk_list);
373 void warn_missing_aes_from_pklist (PK_LIST pk_list);
374
375 /*-- skclist.c --*/
376 int  random_is_faked (void);
377 void release_sk_list( SK_LIST sk_list );
378 gpg_error_t build_sk_list (ctrl_t ctrl, strlist_t locusr,
379                            SK_LIST *ret_sk_list, unsigned use);
380
381 /*-- passphrase.h --*/
382 unsigned char encode_s2k_iterations (int iterations);
383 assuan_context_t agent_open (int try, const char *orig_codeset);
384 void agent_close (assuan_context_t ctx);
385 int  have_static_passphrase(void);
386 const char *get_static_passphrase (void);
387 void set_passphrase_from_string(const char *pass);
388 void read_passphrase_from_fd( int fd );
389 void passphrase_clear_cache ( u32 *keyid, const char *cacheid, int algo );
390 DEK *passphrase_to_dek_ext(u32 *keyid, int pubkey_algo,
391                            int cipher_algo, STRING2KEY *s2k, int mode,
392                            const char *tryagain_text,
393                            const char *custdesc, const char *custprompt,
394                            int *canceled);
395 DEK *passphrase_to_dek( u32 *keyid, int pubkey_algo,
396                         int cipher_algo, STRING2KEY *s2k, int mode,
397                         const char *tryagain_text, int *canceled);
398 void set_next_passphrase( const char *s );
399 char *get_last_passphrase(void);
400 void next_to_last_passphrase(void);
401
402 void emit_status_need_passphrase (u32 *keyid, u32 *mainkeyid, int pubkey_algo);
403
404 #define FORMAT_KEYDESC_NORMAL  0
405 #define FORMAT_KEYDESC_IMPORT  1
406 #define FORMAT_KEYDESC_EXPORT  2
407 #define FORMAT_KEYDESC_DELKEY  3
408 char *gpg_format_keydesc (PKT_public_key *pk, int mode, int escaped);
409
410
411 /*-- getkey.c --*/
412
413 /* Cache a copy of a public key in the public key cache.  PK is not
414    cached if caching is disabled (via getkey_disable_caches), if
415    PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id
416    from the public key (e.g., unsupported algorithm), or a key with
417    the key id is already in the cache.
418
419    The public key packet is copied into the cache using
420    copy_public_key.  Thus, any secret parts are not copied, for
421    instance.
422
423    This cache is filled by get_pubkey and is read by get_pubkey and
424    get_pubkey_fast.  */
425 void cache_public_key( PKT_public_key *pk );
426
427 /* Disable and drop the public key cache (which is filled by
428    cache_public_key and get_pubkey).  Note: there is currently no way
429    to reenable this cache.  */
430 void getkey_disable_caches(void);
431
432 /* Return the public key with the key id KEYID and store it in *PK.
433    The resources in *PK should be released using
434    release_public_key_parts().  This function also stores a copy of
435    the public key in the user id cache (see cache_public_key).
436
437    If PK is NULL, this function just stores the public key in the
438    cache and returns the usual return code.
439
440    PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG,
441    PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the
442    lookup function.  If this is non-zero, only keys with the specified
443    usage will be returned.  As such, it is essential that
444    PK->REQ_USAGE be correctly initialized!
445
446    Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key
447    with the specified key id, or another error code if an error
448    occurs.
449
450    If the data was not read from the cache, then the self-signed data
451    has definitely been merged into the public key using
452    merge_selfsigs.  */
453 int get_pubkey( PKT_public_key *pk, u32 *keyid );
454
455 /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into
456    account nor does it merge in the self-signed data.  This function
457    also only considers primary keys.  It is intended to be used as a
458    quick check of the key to avoid recursion.  It should only be used
459    in very certain cases.  Like get_pubkey and unlike any of the other
460    lookup functions, this function also consults the user id cache
461    (see cache_public_key).
462
463    Return the public key in *PK.  The resources in *PK should be
464    released using release_public_key_parts().  */
465 int get_pubkey_fast ( PKT_public_key *pk, u32 *keyid );
466
467 /* Return the key block for the key with key id KEYID or NULL, if an
468    error occurs.  Use release_kbnode() to release the key block.
469
470    The self-signed data has already been merged into the public key
471    using merge_selfsigs.  */
472 KBNODE get_pubkeyblock( u32 *keyid );
473
474 /* Find a public key identified by the name NAME.
475
476    If name appears to be a valid valid RFC822 mailbox (i.e., email
477    address) and auto key lookup is enabled (no_akl == 0), then the
478    specified auto key lookup methods (--auto-key-lookup) are used to
479    import the key into the local keyring.  Otherwise, just the local
480    keyring is consulted.
481
482
483    If RETCTX is not NULL, then the constructed context is returned in
484    *RETCTX so that getpubkey_next can be used to get subsequent
485    results.  In this case, getkey_end() must be used to free the
486    search context.  If RETCTX is not NULL, then RET_KDBHD must be
487    NULL.
488
489    If PK is not NULL, the public key of the first result is returned
490    in *PK.  Note: PK->REQ_USAGE must be valid!!!  PK->REQ_USAGE is
491    passed through to the lookup function and is a mask of
492    PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.  If this
493    is non-zero, only keys with the specified usage will be returned.
494    Note: The self-signed data has already been merged into the public
495    key using merge_selfsigs.  Free *PK by calling
496    release_public_key_parts (or, if PK was allocated using xfree, you
497    can use free_public_key, which calls release_public_key_parts(PK)
498    and then xfree(PK)).
499
500    NAME is a string, which is turned into a search query using
501    classify_user_id.
502
503    If RET_KEYBLOCK is not NULL, the keyblock is returned in
504    *RET_KEYBLOCK.  This should be freed using release_kbnode().
505
506    If RET_KDBHD is not NULL, then the new database handle used to
507    conduct the search is returned in *RET_KDBHD.  This can be used to
508    get subsequent results using keydb_search_next or to modify the
509    returned record.  Note: in this case, no advanced filtering is done
510    for subsequent results (e.g., PK->REQ_USAGE is not respected).
511    Unlike RETCTX, this is always returned.
512
513    If INCLUDE_UNUSABLE is set, then unusable keys (see the
514    documentation for skip_unusable for an exact definition) are
515    skipped unless they are looked up by key id or by fingerprint.
516
517    If NO_AKL is set, then the auto key locate functionality is
518    disabled and only the local key ring is considered.  Note: the
519    local key ring is consulted even if local is not in the
520    --auto-key-locate option list!
521
522    This function returns 0 on success.  Otherwise, an error code is
523    returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
524    (if want_secret is set) is returned if the key is not found.  */
525 int get_pubkey_byname (ctrl_t ctrl,
526                        GETKEY_CTX *retctx, PKT_public_key *pk,
527                        const char *name,
528                        KBNODE *ret_keyblock, KEYDB_HANDLE *ret_kdbhd,
529                        int include_unusable, int no_akl );
530
531 /* Return the public key with the key id KEYID and store it in *PK.
532    The resources should be released using release_public_key_parts().
533
534    Unlike other lookup functions, PK may not be NULL.  PK->REQ_USAGE
535    is passed through to the lookup function and is a mask of
536    PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.  Thus, it
537    must be valid!  If this is non-zero, only keys with the specified
538    usage will be returned.
539
540    Returns 0 on success.  If a public key with the specified key id is
541    not found or a secret key is not available for that public key, an
542    error code is returned.  Note: this function ignores legacy keys.
543    An error code is also return if an error occurs.
544
545    The self-signed data has already been merged into the public key
546    using merge_selfsigs.  */
547 gpg_error_t get_seckey (PKT_public_key *pk, u32 *keyid);
548
549 /* Lookup a key with the specified fingerprint.
550
551    If PK is not NULL, the public key of the first result is returned
552    in *PK.  Note: this function does an exact search and thus the
553    returned public key may be a subkey rather than the primary key.
554    Note: The self-signed data has already been merged into the public
555    key using merge_selfsigs.  Free *PK by calling
556    release_public_key_parts (or, if PK was allocated using xfree, you
557    can use free_public_key, which calls release_public_key_parts(PK)
558    and then xfree(PK)).
559
560    If PK->REQ_USAGE is set, it is used to filter the search results.
561    (Thus, if PK is not NULL, PK->REQ_USAGE must be valid!!!)  See the
562    documentation for finish_lookup to understand exactly how this is
563    used.
564
565    If R_KEYBLOCK is not NULL, then the first result's keyblock is
566    returned in *R_KEYBLOCK.  This should be freed using
567    release_kbnode().
568
569    FPRINT is a byte array whose contents is the fingerprint to use as
570    the search term.  FPRINT_LEN specifies the length of the
571    fingerprint (in bytes).  Currently, only 16 and 20-byte
572    fingerprints are supported.  */
573 int get_pubkey_byfprint (PKT_public_key *pk,  kbnode_t *r_keyblock,
574                          const byte *fprint, size_t fprint_len);
575
576 /* This function is similar to get_pubkey_byfprint, but it doesn't
577    merge the self-signed data into the public key and subkeys or into
578    the user ids.  It also doesn't add the key to the user id cache.
579    Further, this function ignores PK->REQ_USAGE.
580
581    This function is intended to avoid recursion and, as such, should
582    only be used in very specific situations.
583
584    Like get_pubkey_byfprint, PK may be NULL.  In that case, this
585    function effectively just checks for the existence of the key.  */
586 int get_pubkey_byfprint_fast (PKT_public_key *pk,
587                               const byte *fprint, size_t fprint_len);
588
589 /* Returns true if a secret key is available for the public key with
590    key id KEYID.  */
591 int have_secret_key_with_kid (u32 *keyid);
592
593 /* Parse the --default-key parameter.  Returns the last key (in terms
594    of when the option is given) that is available.  */
595 const char *parse_def_secret_key (ctrl_t ctrl);
596
597 /* Look up a secret key.
598
599    If PK is not NULL, the public key of the first result is returned
600    in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
601    set, it is used to filter the search results.  See the
602    documentation for finish_lookup to understand exactly how this is
603    used.  Note: The self-signed data has already been merged into the
604    public key using merge_selfsigs.  Free *PK by calling
605    release_public_key_parts (or, if PK was allocated using xfree, you
606    can use free_public_key, which calls release_public_key_parts(PK)
607    and then xfree(PK)).
608
609    If --default-key was set, then the specified key is looked up.  (In
610    this case, the default key is returned even if it is considered
611    unusable.  See the documentation for skip_unusable for exactly what
612    this means.)
613
614    Otherwise, this initiates a DB scan that returns all keys that are
615    usable (see previous paragraph for exactly what usable means) and
616    for which a secret key is available.
617
618    This function returns the first match.  Additional results can be
619    returned using getkey_next.  */
620 gpg_error_t get_seckey_default (ctrl_t ctrl, PKT_public_key *pk);
621
622 /* Search for keys matching some criteria.
623
624    If RETCTX is not NULL, then the constructed context is returned in
625    *RETCTX so that getpubkey_next can be used to get subsequent
626    results.  In this case, getkey_end() must be used to free the
627    search context.  If RETCTX is not NULL, then RET_KDBHD must be
628    NULL.
629
630    If PK is not NULL, the public key of the first result is returned
631    in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
632    set, it is used to filter the search results.  See the
633    documentation for finish_lookup to understand exactly how this is
634    used.  Note: The self-signed data has already been merged into the
635    public key using merge_selfsigs.  Free *PK by calling
636    release_public_key_parts (or, if PK was allocated using xfree, you
637    can use free_public_key, which calls release_public_key_parts(PK)
638    and then xfree(PK)).
639
640    If NAMES is not NULL, then a search query is constructed using
641    classify_user_id on each of the strings in the list.  (Recall: the
642    database does an OR of the terms, not an AND.)  If NAMES is
643    NULL, then all results are returned.
644
645    If WANT_SECRET is set, then only keys with an available secret key
646    (either locally or via key registered on a smartcard) are returned.
647
648    This function does not skip unusable keys (see the documentation
649    for skip_unusable for an exact definition).
650
651    If RET_KEYBLOCK is not NULL, the keyblock is returned in
652    *RET_KEYBLOCK.  This should be freed using release_kbnode().
653
654    This function returns 0 on success.  Otherwise, an error code is
655    returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
656    (if want_secret is set) is returned if the key is not found.  */
657 gpg_error_t getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
658                             strlist_t names, int want_secret,
659                             kbnode_t *ret_keyblock);
660
661 /* Search for keys matching some criteria.
662
663    If RETCTX is not NULL, then the constructed context is returned in
664    *RETCTX so that getpubkey_next can be used to get subsequent
665    results.  In this case, getkey_end() must be used to free the
666    search context.  If RETCTX is not NULL, then RET_KDBHD must be
667    NULL.
668
669    If PK is not NULL, the public key of the first result is returned
670    in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
671    set, it is used to filter the search results.  See the
672    documentation for finish_lookup to understand exactly how this is
673    used.  Note: The self-signed data has already been merged into the
674    public key using merge_selfsigs.  Free *PK by calling
675    release_public_key_parts (or, if PK was allocated using xfree, you
676    can use free_public_key, which calls release_public_key_parts(PK)
677    and then xfree(PK)).
678
679    If NAME is not NULL, then a search query is constructed using
680    classify_user_id on the string.  In this case, even unusable keys
681    (see the documentation for skip_unusable for an exact definition of
682    unusable) are returned.  Otherwise, if --default-key was set, then
683    that key is returned (even if it is unusable).  If neither of these
684    conditions holds, then the first usable key is returned.
685
686    If WANT_SECRET is set, then only keys with an available secret key
687    (either locally or via key registered on a smartcard) are returned.
688
689    This function does not skip unusable keys (see the documentation
690    for skip_unusable for an exact definition).
691
692    If RET_KEYBLOCK is not NULL, the keyblock is returned in
693    *RET_KEYBLOCK.  This should be freed using release_kbnode().
694
695    This function returns 0 on success.  Otherwise, an error code is
696    returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
697    (if want_secret is set) is returned if the key is not found.
698
699    FIXME: We also have the get_pubkey_byname function which has a
700    different semantic.  Should be merged with this one.  */
701 gpg_error_t getkey_byname (ctrl_t ctrl,
702                            getkey_ctx_t *retctx, PKT_public_key *pk,
703                            const char *name, int want_secret,
704                            kbnode_t *ret_keyblock);
705
706 /* Return the next search result.
707
708    If PK is not NULL, the public key of the next result is returned in
709    *PK.  Note: The self-signed data has already been merged into the
710    public key using merge_selfsigs.  Free *PK by calling
711    release_public_key_parts (or, if PK was allocated using xfree, you
712    can use free_public_key, which calls release_public_key_parts(PK)
713    and then xfree(PK)).
714
715    The self-signed data has already been merged into the public key
716    using merge_selfsigs.  */
717 gpg_error_t getkey_next (getkey_ctx_t ctx, PKT_public_key *pk,
718                          kbnode_t *ret_keyblock);
719
720 /* Release any resources used by a key listing content.  This must be
721    called on the context returned by, e.g., getkey_byname.  */
722 void getkey_end (getkey_ctx_t ctx);
723
724 /* Return the database handle used by this context.  The context still
725    owns the handle.  */
726 KEYDB_HANDLE get_ctx_handle(GETKEY_CTX ctx);
727
728 /* Enumerate some secret keys (specifically, those specified with
729    --default-key and --try-secret-key).  Use the following procedure:
730
731     1) Initialize a void pointer to NULL
732     2) Pass a reference to this pointer to this function (content)
733        and provide space for the secret key (sk)
734     3) Call this function as long as it does not return an error (or
735        until you are done).  The error code GPG_ERR_EOF indicates the
736        end of the listing.
737     4) Call this function a last time with SK set to NULL,
738        so that can free it's context.
739
740    In pseudo-code:
741
742      void *ctx = NULL;
743      PKT_public_key *sk = xmalloc_clear (sizeof (*sk));
744      gpg_error_t err;
745
746      while ((err = enum_secret_keys (&ctx, sk)))
747        {
748          // Process SK.
749
750          if (done)
751            break;
752
753          free_public_key (sk);
754          sk = xmalloc_clear (sizeof (*sk));
755        }
756
757      // Release any resources used by CTX.
758      enum_secret_keys (&ctx, NULL);
759      free_public_key (sk);
760
761      if (gpg_err_code (err) != GPG_ERR_EOF)
762        ; // An error occurred.
763  */
764 gpg_error_t enum_secret_keys (ctrl_t ctrl, void **context, PKT_public_key *pk);
765
766 /* Set the mainkey_id fields for all keys in KEYBLOCK.  This is
767    usually done by merge_selfsigs but at some places we only need the
768    main_kid not a full merge.  The function also guarantees that all
769    pk->keyids are computed. */
770 void setup_main_keyids (kbnode_t keyblock);
771
772 /* KEYBLOCK corresponds to a public key block.  This function merges
773    much of the information from the self-signed data into the public
774    key, public subkey and user id data structures.  If you use the
775    high-level search API (e.g., get_pubkey) for looking up key blocks,
776    then you don't need to call this function.  This function is
777    useful, however, if you change the keyblock, e.g., by adding or
778    removing a self-signed data packet.  */
779 void merge_keys_and_selfsig( KBNODE keyblock );
780
781 char*get_user_id_string_native( u32 *keyid );
782 char*get_long_user_id_string( u32 *keyid );
783 char*get_user_id( u32 *keyid, size_t *rn );
784 char*get_user_id_native( u32 *keyid );
785 char *get_user_id_byfpr (const byte *fpr, size_t *rn);
786 char *get_user_id_byfpr_native (const byte *fpr);
787
788 void release_akl(void);
789 int parse_auto_key_locate(char *options);
790
791 /*-- keyid.c --*/
792 int pubkey_letter( int algo );
793 char *pubkey_string (PKT_public_key *pk, char *buffer, size_t bufsize);
794 #define PUBKEY_STRING_SIZE 32
795 u32 v3_keyid (gcry_mpi_t a, u32 *ki);
796 void hash_public_key( gcry_md_hd_t md, PKT_public_key *pk );
797 const char *format_keyid (u32 *keyid, int format, char *buffer, int len);
798 size_t keystrlen(void);
799 const char *keystr(u32 *keyid);
800 const char *keystr_with_sub (u32 *main_kid, u32 *sub_kid);
801 const char *keystr_from_pk(PKT_public_key *pk);
802 const char *keystr_from_pk_with_sub (PKT_public_key *main_pk,
803                                      PKT_public_key *sub_pk);
804 const char *keystr_from_desc(KEYDB_SEARCH_DESC *desc);
805 u32 keyid_from_pk( PKT_public_key *pk, u32 *keyid );
806 u32 keyid_from_sig( PKT_signature *sig, u32 *keyid );
807 u32 keyid_from_fingerprint(const byte *fprint, size_t fprint_len, u32 *keyid);
808 byte *namehash_from_uid(PKT_user_id *uid);
809 unsigned nbits_from_pk( PKT_public_key *pk );
810 const char *datestr_from_pk( PKT_public_key *pk );
811 const char *datestr_from_sig( PKT_signature *sig );
812 const char *expirestr_from_pk( PKT_public_key *pk );
813 const char *expirestr_from_sig( PKT_signature *sig );
814 const char *revokestr_from_pk( PKT_public_key *pk );
815 const char *usagestr_from_pk (PKT_public_key *pk, int fill);
816 const char *colon_strtime (u32 t);
817 const char *colon_datestr_from_pk (PKT_public_key *pk);
818 const char *colon_datestr_from_sig (PKT_signature *sig);
819 const char *colon_expirestr_from_sig (PKT_signature *sig);
820 byte *fingerprint_from_pk( PKT_public_key *pk, byte *buf, size_t *ret_len );
821 char *hexfingerprint (PKT_public_key *pk, char *buffer, size_t buflen);
822 char *format_hexfingerprint (const char *fingerprint,
823                              char *buffer, size_t buflen);
824 gpg_error_t keygrip_from_pk (PKT_public_key *pk, unsigned char *array);
825 gpg_error_t hexkeygrip_from_pk (PKT_public_key *pk, char **r_grip);
826
827
828 /*-- kbnode.c --*/
829 KBNODE new_kbnode( PACKET *pkt );
830 KBNODE clone_kbnode( KBNODE node );
831 void release_kbnode( KBNODE n );
832 void delete_kbnode( KBNODE node );
833 void add_kbnode( KBNODE root, KBNODE node );
834 void insert_kbnode( KBNODE root, KBNODE node, int pkttype );
835 void move_kbnode( KBNODE *root, KBNODE node, KBNODE where );
836 void remove_kbnode( KBNODE *root, KBNODE node );
837 KBNODE find_prev_kbnode( KBNODE root, KBNODE node, int pkttype );
838 KBNODE find_next_kbnode( KBNODE node, int pkttype );
839 KBNODE find_kbnode( KBNODE node, int pkttype );
840 KBNODE walk_kbnode( KBNODE root, KBNODE *context, int all );
841 void clear_kbnode_flags( KBNODE n );
842 int  commit_kbnode( KBNODE *root );
843 void dump_kbnode( KBNODE node );
844
845 #endif /*G10_KEYDB_H*/