Bump to 2.4.3
[platform/upstream/gpg2.git] / common / util.h
1 /* util.h - Utility functions for GnuPG
2  * Copyright (C) 2001, 2002, 2003, 2004, 2009 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute and/or modify this
7  * part of GnuPG under the terms of either
8  *
9  *   - the GNU Lesser General Public License as published by the Free
10  *     Software Foundation; either version 3 of the License, or (at
11  *     your option) any later version.
12  *
13  * or
14  *
15  *   - the GNU General Public License as published by the Free
16  *     Software Foundation; either version 2 of the License, or (at
17  *     your option) any later version.
18  *
19  * or both in parallel, as here.
20  *
21  * GnuPG is distributed in the hope that it will be useful, but
22  * WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24  * General Public License for more details.
25  *
26  * You should have received a copies of the GNU General Public License
27  * and the GNU Lesser General Public License along with this program;
28  * if not, see <https://www.gnu.org/licenses/>.
29  */
30
31 #ifndef GNUPG_COMMON_UTIL_H
32 #define GNUPG_COMMON_UTIL_H
33
34 #include <gcrypt.h> /* We need this for the memory function protos. */
35 #include <errno.h>  /* We need errno.  */
36 #include <gpg-error.h> /* We need gpg_error_t and estream. */
37
38 /* These error codes are used but not defined in the required
39  * libgpg-error version.  Define them here.
40  * Example: (#if GPG_ERROR_VERSION_NUMBER < 0x011500 // 1.21)
41  */
42
43 #ifndef EXTERN_UNLESS_MAIN_MODULE
44 # if !defined (INCLUDED_BY_MAIN_MODULE)
45 #  define EXTERN_UNLESS_MAIN_MODULE extern
46 # else
47 #  define EXTERN_UNLESS_MAIN_MODULE
48 # endif
49 #endif
50
51 /* Hash function used with libksba. */
52 #define HASH_FNC ((void (*)(void *, const void*,size_t))gcry_md_write)
53
54 /* The length of the keygrip.  This is a SHA-1 hash of the key
55  * parameters as generated by gcry_pk_get_keygrip.  */
56 #define KEYGRIP_LEN 20
57
58 /* The length of the unique blob identifier as used by the keyboxd.
59  * This is the possible truncated fingerprint of the primary key.  */
60 #define UBID_LEN    20
61
62
63 /* Get all the stuff from jnlib. */
64 #include "../common/logging.h"
65 #include "../common/stringhelp.h"
66 #include "../common/mischelp.h"
67 #include "../common/strlist.h"
68 #include "../common/dotlock.h"
69 #include "../common/utf8conv.h"
70 #include "../common/dynload.h"
71 #include "../common/fwddecl.h"
72 #include "../common/utilproto.h"
73
74 #include "gettime.h"
75
76 /* Redefine asprintf by our estream version which uses our own memory
77    allocator..  */
78 #define asprintf gpgrt_asprintf
79 #define vasprintf gpgrt_vasprintf
80
81 /* Due to a bug in mingw32's snprintf related to the 'l' modifier and
82    for increased portability we use our snprintf on all systems. */
83 #undef snprintf
84 #define snprintf gpgrt_snprintf
85
86
87 /* Replacements for macros not available with libgpg-error < 1.20.  */
88
89 /* We need this type even if we are not using libreadline and or we
90    did not include libreadline in the current file. */
91 #ifndef GNUPG_LIBREADLINE_H_INCLUDED
92 typedef char **rl_completion_func_t (const char *, int, int);
93 #endif /*!GNUPG_LIBREADLINE_H_INCLUDED*/
94
95
96 /* Handy malloc macros - please use only them. */
97 #define xtrymalloc(a)    gcry_malloc ((a))
98 #define xtrymalloc_secure(a)  gcry_malloc_secure ((a))
99 #define xtrycalloc(a,b)  gcry_calloc ((a),(b))
100 #define xtrycalloc_secure(a,b)  gcry_calloc_secure ((a),(b))
101 #define xtryrealloc(a,b) gcry_realloc ((a),(b))
102 #define xtryreallocarray(a,b,c,d) gpgrt_reallocarray ((a),(b),(c),(d))
103 #define xtrystrdup(a)    gcry_strdup ((a))
104 #define xfree(a)         gcry_free ((a))
105 #define xfree_fnc        gcry_free
106
107 #define xmalloc(a)       gcry_xmalloc ((a))
108 #define xmalloc_secure(a)  gcry_xmalloc_secure ((a))
109 #define xcalloc(a,b)     gcry_xcalloc ((a),(b))
110 #define xcalloc_secure(a,b) gcry_xcalloc_secure ((a),(b))
111 #define xrealloc(a,b)    gcry_xrealloc ((a),(b))
112 #define xstrdup(a)       gcry_xstrdup ((a))
113 /* See also the xreallocarray prototype below.  */
114
115 /* For compatibility with gpg 1.4 we also define these: */
116 #define xmalloc_clear(a) gcry_xcalloc (1, (a))
117 #define xmalloc_secure_clear(a) gcry_xcalloc_secure (1, (a))
118
119 /* The default error source of the application.  This is different
120    from GPG_ERR_SOURCE_DEFAULT in that it does not depend on the
121    source file and thus is usable in code shared by applications.
122    Defined by init.c.  */
123 extern gpg_err_source_t default_errsource;
124
125 /* Convenience function to return a gpg-error code for memory
126    allocation failures.  This function makes sure that an error will
127    be returned even if accidentally ERRNO is not set.  */
128 static inline gpg_error_t
129 out_of_core (void)
130 {
131   return gpg_error_from_syserror ();
132 }
133
134
135 /*-- yesno.c --*/
136 int answer_is_yes (const char *s);
137 int answer_is_yes_no_default (const char *s, int def_answer);
138 int answer_is_yes_no_quit (const char *s);
139 int answer_is_okay_cancel (const char *s, int def_answer);
140
141 /*-- xreadline.c --*/
142 ssize_t read_line (FILE *fp,
143                    char **addr_of_buffer, size_t *length_of_buffer,
144                    size_t *max_length);
145
146
147 /*-- b64enc.c and b64dec.c --*/
148 struct b64state
149 {
150   unsigned int flags;
151   int idx;
152   int quad_count;
153   FILE *fp;
154   estream_t stream;
155   char *title;
156   unsigned char radbuf[4];
157   u32 crc;
158   int stop_seen:1;
159   int invalid_encoding:1;
160   gpg_error_t lasterr;
161 };
162
163 gpg_error_t b64enc_start (struct b64state *state, FILE *fp, const char *title);
164 gpg_error_t b64enc_start_es (struct b64state *state, estream_t fp,
165                              const char *title);
166 gpg_error_t b64enc_write (struct b64state *state,
167                           const void *buffer, size_t nbytes);
168 gpg_error_t b64enc_finish (struct b64state *state);
169
170 gpg_error_t b64dec_start (struct b64state *state, const char *title);
171 gpg_error_t b64dec_proc (struct b64state *state, void *buffer, size_t length,
172                          size_t *r_nbytes);
173 gpg_error_t b64dec_finish (struct b64state *state);
174
175 /*-- sexputil.c */
176 char *canon_sexp_to_string (const unsigned char *canon, size_t canonlen);
177 void log_printcanon (const char *text,
178                      const unsigned char *sexp, size_t sexplen);
179 void log_printsexp (const char *text, gcry_sexp_t sexp);
180
181 gpg_error_t make_canon_sexp (gcry_sexp_t sexp,
182                              unsigned char **r_buffer, size_t *r_buflen);
183 gpg_error_t make_canon_sexp_pad (gcry_sexp_t sexp, int secure,
184                                  unsigned char **r_buffer, size_t *r_buflen);
185 gpg_error_t keygrip_from_canon_sexp (const unsigned char *key, size_t keylen,
186                                      unsigned char *grip);
187 int cmp_simple_canon_sexp (const unsigned char *a, const unsigned char *b);
188 int cmp_canon_sexp (const unsigned char *a, size_t alen,
189                     const unsigned char *b, size_t blen,
190                     int (*tcmp)(void *ctx, int depth,
191                                 const unsigned char *aval, size_t avallen,
192                                 const unsigned char *bval, size_t bvallen),
193                     void *tcmpctx);
194 unsigned char *make_simple_sexp_from_hexstr (const char *line,
195                                              size_t *nscanned);
196 int hash_algo_from_sigval (const unsigned char *sigval);
197 unsigned char *make_canon_sexp_from_rsa_pk (const void *m, size_t mlen,
198                                             const void *e, size_t elen,
199                                             size_t *r_len);
200 gpg_error_t get_rsa_pk_from_canon_sexp (const unsigned char *keydata,
201                                         size_t keydatalen,
202                                         unsigned char const **r_n,
203                                         size_t *r_nlen,
204                                         unsigned char const **r_e,
205                                         size_t *r_elen);
206 gpg_error_t get_ecc_q_from_canon_sexp (const unsigned char *keydata,
207                                        size_t keydatalen,
208                                        unsigned char const **r_q,
209                                        size_t *r_qlen);
210 gpg_error_t uncompress_ecc_q_in_canon_sexp (const unsigned char *keydata,
211                                             size_t keydatalen,
212                                             unsigned char **r_newkeydata,
213                                             size_t *r_newkeydatalen);
214
215 int get_pk_algo_from_key (gcry_sexp_t key);
216 int get_pk_algo_from_canon_sexp (const unsigned char *keydata,
217                                  size_t keydatalen);
218 char *pubkey_algo_string (gcry_sexp_t s_pkey, enum gcry_pk_algos *r_algoid);
219 const char *pubkey_algo_to_string (int algo);
220 const char *hash_algo_to_string (int algo);
221 const char *cipher_mode_to_string (int mode);
222
223 /*-- convert.c --*/
224 int hex2bin (const char *string, void *buffer, size_t length);
225 int hexcolon2bin (const char *string, void *buffer, size_t length);
226 char *bin2hex (const void *buffer, size_t length, char *stringbuf);
227 char *bin2hexcolon (const void *buffer, size_t length, char *stringbuf);
228 const char *hex2str (const char *hexstring,
229                      char *buffer, size_t bufsize, size_t *buflen);
230 char *hex2str_alloc (const char *hexstring, size_t *r_count);
231 unsigned int hex2fixedbuf (const char *hexstr, void *buffer, size_t bufsize);
232
233 /*-- percent.c --*/
234 char *percent_plus_escape (const char *string);
235 char *percent_data_escape (int plus, const char *prefix,
236                            const void *data, size_t datalen);
237 char *percent_plus_unescape (const char *string, int nulrepl);
238 char *percent_unescape (const char *string, int nulrepl);
239
240 size_t percent_plus_unescape_inplace (char *string, int nulrepl);
241 size_t percent_unescape_inplace (char *string, int nulrepl);
242
243 /*-- openpgp-oid.c --*/
244 gpg_error_t openpgp_oid_from_str (const char *string, gcry_mpi_t *r_mpi);
245 char *openpgp_oidbuf_to_str (const unsigned char *buf, size_t len);
246 char *openpgp_oid_to_str (gcry_mpi_t a);
247 int openpgp_oidbuf_is_ed25519 (const void *buf, size_t len);
248 int openpgp_oid_is_ed25519 (gcry_mpi_t a);
249 int openpgp_oidbuf_is_cv25519 (const void *buf, size_t len);
250 int openpgp_oid_is_cv25519 (gcry_mpi_t a);
251 int openpgp_oid_is_cv448 (gcry_mpi_t a);
252 int openpgp_oid_is_ed448 (gcry_mpi_t a);
253 const char *openpgp_curve_to_oid (const char *name,
254                                   unsigned int *r_nbits, int *r_algo);
255 const char *openpgp_oid_to_curve (const char *oid, int canon);
256 const char *openpgp_oid_or_name_to_curve (const char *oidname, int canon);
257 const char *openpgp_enum_curves (int *idxp);
258 const char *openpgp_is_curve_supported (const char *name,
259                                         int *r_algo, unsigned int *r_nbits);
260 const char *get_keyalgo_string (enum gcry_pk_algos algo,
261                                 unsigned int nbits, const char *curve);
262
263
264 /*-- homedir.c --*/
265 const char *standard_homedir (void);
266 void gnupg_set_homedir (const char *newdir);
267 void gnupg_maybe_make_homedir (const char *fname, int quiet);
268 const char *gnupg_homedir (void);
269 int gnupg_default_homedir_p (void);
270 const char *gnupg_daemon_rootdir (void);
271 const char *gnupg_socketdir (void);
272 const char *gnupg_sysconfdir (void);
273 const char *gnupg_bindir (void);
274 const char *gnupg_libexecdir (void);
275 const char *gnupg_libdir (void);
276 const char *gnupg_datadir (void);
277 const char *gnupg_localedir (void);
278 const char *gpg_agent_socket_name (void);
279 const char *dirmngr_socket_name (void);
280 const char *keyboxd_socket_name (void);
281
282 char *_gnupg_socketdir_internal (int skip_checks, unsigned *r_info);
283
284 /* All module names.  We also include gpg and gpgsm for the sake for
285    gpgconf. */
286 #define GNUPG_MODULE_NAME_AGENT        1
287 #define GNUPG_MODULE_NAME_PINENTRY     2
288 #define GNUPG_MODULE_NAME_SCDAEMON     3
289 #define GNUPG_MODULE_NAME_DIRMNGR      4
290 #define GNUPG_MODULE_NAME_PROTECT_TOOL 5
291 #define GNUPG_MODULE_NAME_CHECK_PATTERN 6
292 #define GNUPG_MODULE_NAME_GPGSM         7
293 #define GNUPG_MODULE_NAME_GPG           8
294 #define GNUPG_MODULE_NAME_CONNECT_AGENT 9
295 #define GNUPG_MODULE_NAME_GPGCONF       10
296 #define GNUPG_MODULE_NAME_DIRMNGR_LDAP  11
297 #define GNUPG_MODULE_NAME_GPGV          12
298 #define GNUPG_MODULE_NAME_KEYBOXD       13
299 #define GNUPG_MODULE_NAME_TPM2DAEMON    14
300 #define GNUPG_MODULE_NAME_CARD          15
301 #define GNUPG_MODULE_NAME_GPGTAR        16
302 const char *gnupg_module_name (int which);
303 void gnupg_module_name_flush_some (void);
304 void gnupg_set_builddir (const char *newdir);
305
306
307 /* A list of constants to identify protocols.  This is used by tools
308  * which need to distinguish between the different protocols
309  * implemented by GnuPG.  May be used as bit flags.  */
310 #define GNUPG_PROTOCOL_OPENPGP    1   /* The one and only (gpg).      */
311 #define GNUPG_PROTOCOL_CMS        2   /* The core of S/MIME (gpgsm)   */
312 #define GNUPG_PROTOCOL_SSH_AGENT  4   /* Out ssh-agent implementation */
313
314
315 /*-- gpgrlhelp.c --*/
316 void gnupg_rl_initialize (void);
317
318 /*-- helpfile.c --*/
319 char *gnupg_get_help_string (const char *key, int only_current_locale);
320
321 /*-- localename.c --*/
322 const char *gnupg_messages_locale_name (void);
323
324 /*-- miscellaneous.c --*/
325
326 /* This function is called at startup to tell libgcrypt to use our own
327    logging subsystem. */
328 void setup_libgcrypt_logging (void);
329
330 /* Print an out of core message and die.  */
331 void xoutofcore (void);
332
333 /* Wrapper aroung gpgrt_reallocarray.  Uses the gpgrt alloc function
334  * which redirects to the Libgcrypt versions via
335  * init_common_subsystems.  Thus this can be used interchangeable with
336  * the other alloc functions. */
337 void *xreallocarray (void *a, size_t oldnmemb, size_t nmemb, size_t size);
338
339 /* Same as estream_asprintf but die on memory failure.  */
340 char *xasprintf (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2);
341 /* This is now an alias to estream_asprintf.  */
342 char *xtryasprintf (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2);
343
344 /* Replacement for gcry_cipher_algo_name.  */
345 const char *gnupg_cipher_algo_name (int algo);
346
347 void obsolete_option (const char *configname, unsigned int configlineno,
348                       const char *name);
349
350 const char *print_fname_stdout (const char *s);
351 const char *print_fname_stdin (const char *s);
352 void print_utf8_buffer3 (estream_t fp, const void *p, size_t n,
353                          const char *delim);
354 void print_utf8_buffer2 (estream_t fp, const void *p, size_t n, int delim);
355 void print_utf8_buffer (estream_t fp, const void *p, size_t n);
356 void print_utf8_string (estream_t stream, const char *p);
357 void print_hexstring (FILE *fp, const void *buffer, size_t length,
358                       int reserved);
359 char *try_make_printable_string (const void *p, size_t n, int delim);
360 char *make_printable_string (const void *p, size_t n, int delim);
361 char *decode_c_string (const char *src);
362
363 int is_file_compressed (const byte *buf, unsigned int buflen);
364
365 int match_multistr (const char *multistr,const char *match);
366
367 int gnupg_compare_version (const char *a, const char *b);
368
369 struct debug_flags_s
370 {
371   unsigned int flag;
372   const char *name;
373 };
374 int parse_debug_flag (const char *string, unsigned int *debugvar,
375                       const struct debug_flags_s *flags);
376
377 struct compatibility_flags_s
378 {
379   unsigned int flag;
380   const char *name;
381   const char *desc;
382 };
383 int parse_compatibility_flags (const char *string, unsigned int *flagvar,
384                                const struct compatibility_flags_s *flags);
385
386
387 /*-- Simple replacement functions. */
388
389 /* We use the gnupg_ttyname macro to be safe not to run into conflicts
390    which an extisting but broken ttyname.  */
391 #if !defined(HAVE_TTYNAME) || defined(HAVE_BROKEN_TTYNAME)
392 # define gnupg_ttyname(n) _gnupg_ttyname ((n))
393 /* Systems without ttyname (W32) will merely return NULL. */
394 static inline char *
395 _gnupg_ttyname (int fd)
396 {
397   (void)fd;
398   return NULL;
399 }
400 #else /*HAVE_TTYNAME*/
401 # define gnupg_ttyname(n) ttyname ((n))
402 #endif /*HAVE_TTYNAME */
403
404 #define gnupg_isatty(a)  isatty ((a))
405
406
407 /*-- Macros to replace ctype ones to avoid locale problems. --*/
408 #define spacep(p)   (*(p) == ' ' || *(p) == '\t')
409 #define digitp(p)   (*(p) >= '0' && *(p) <= '9')
410 #define alphap(p)   ((*(p) >= 'A' && *(p) <= 'Z')       \
411                      || (*(p) >= 'a' && *(p) <= 'z'))
412 #define alnump(p)   (alphap (p) || digitp (p))
413 #define hexdigitp(a) (digitp (a)                     \
414                       || (*(a) >= 'A' && *(a) <= 'F')  \
415                       || (*(a) >= 'a' && *(a) <= 'f'))
416   /* Note this isn't identical to a C locale isspace() without \f and
417      \v, but works for the purposes used here. */
418 #define ascii_isspace(a) ((a)==' ' || (a)=='\n' || (a)=='\r' || (a)=='\t')
419
420 /* The atoi macros assume that the buffer has only valid digits. */
421 #define atoi_1(p)   (*(p) - '0' )
422 #define atoi_2(p)   ((atoi_1(p) * 10) + atoi_1((p)+1))
423 #define atoi_4(p)   ((atoi_2(p) * 100) + atoi_2((p)+2))
424 #define xtoi_1(p)   (*(p) <= '9'? (*(p)- '0'): \
425                      *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10))
426 #define xtoi_2(p)   ((xtoi_1(p) * 16) + xtoi_1((p)+1))
427 #define xtoi_4(p)   ((xtoi_2(p) * 256) + xtoi_2((p)+2))
428
429 #endif /*GNUPG_COMMON_UTIL_H*/