diff --git a/common/homedir.c b/common/homedir.c index d38c94a05..deb6f3616 100644 --- a/common/homedir.c +++ b/common/homedir.c @@ -1,1804 +1,1907 @@ /* homedir.c - Setup the home directory. * Copyright (C) 2004, 2006, 2007, 2010 Free Software Foundation, Inc. * Copyright (C) 2013, 2016 Werner Koch - * Copyright (C) 2021 g10 Code GmbH + * Copyright (C) 2021, 2024 g10 Code GmbH * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * SPDX-License-Identifier: (LGPL-3.0-or-later OR GPL-2.0-or-later) */ #include #include #include #include #include #ifdef HAVE_W32_SYSTEM #include /* Due to the stupid mingw64 requirement to include this header before windows.h which is often implicitly included. */ #include #ifndef CSIDL_APPDATA #define CSIDL_APPDATA 0x001a #endif #ifndef CSIDL_LOCAL_APPDATA #define CSIDL_LOCAL_APPDATA 0x001c #endif #ifndef CSIDL_COMMON_APPDATA #define CSIDL_COMMON_APPDATA 0x0023 #endif #ifndef CSIDL_FLAG_CREATE #define CSIDL_FLAG_CREATE 0x8000 #endif #endif /*HAVE_W32_SYSTEM*/ #ifdef HAVE_STAT #include /* for stat() */ #endif #include "util.h" #include "sysutils.h" #include "i18n.h" #include "zb32.h" /* The name of the symbolic link to the file from which the process * text was read. */ #if __linux__ # define MYPROC_SELF_EXE "/proc/self/exe" #elif defined(__NetBSD__) # define MYPROC_SELF_EXE "/proc/curproc/exe" #elif defined(__illumos__) || defined(__sun) # define MYPROC_SELF_EXE "/proc/self/path/a.out" #else /* Assume other BSDs */ # define MYPROC_SELF_EXE "/proc/curproc/file" #endif /* Mode flags for unix_rootdir. */ enum wantdir_values { WANTDIR_ROOT = 0, WANTDIR_SYSCONF, WANTDIR_SOCKET }; /* The GnuPG homedir. This is only accessed by the functions * gnupg_homedir and gnupg_set_homedir. Malloced. */ static char *the_gnupg_homedir; /* Flag indicating that home directory is not the default one. */ static byte non_default_homedir; /* An object to store information taken from a gpgconf.ctl file. This * is parsed early at startup time and never changed later. */ static struct { unsigned int checked:1; /* True if we have checked for a gpgconf.ctl. */ unsigned int found:1; /* True if a gpgconf.ctl was found. */ unsigned int empty:1; /* The file is empty except for comments. */ unsigned int valid:1; /* The entries in gpgconf.ctl are valid. */ unsigned int portable:1;/* Windows portable installation. */ + char *gnupg; /* The "gnupg" directory part. */ char *rootdir; /* rootdir or NULL */ char *sysconfdir; /* sysconfdir or NULL */ char *socketdir; /* socketdir or NULL */ } gpgconf_ctl; #ifdef HAVE_W32_SYSTEM /* A flag used to indicate that a control file for gpgconf has been * detected. Under Windows the presence of this file indicates a * portable installations and triggers several changes: * * - The GNUGHOME directory is fixed relative to installation * directory. All other means to set the home directory are ignored. * * - All registry variables will be ignored. * * This flag is not used on Unix systems. */ static byte w32_portable_app; #endif /*HAVE_W32_SYSTEM*/ #ifdef HAVE_W32_SYSTEM /* This flag is true if this process's binary has been installed under bin and not in the root directory as often used before GnuPG 2.1. */ static byte w32_bin_is_bin; #endif /*HAVE_W32_SYSTEM*/ #ifdef HAVE_W32_SYSTEM static const char *w32_rootdir (void); #endif +/* Return the name of the gnupg dir. This is usually "gnupg". */ +static const char * +my_gnupg_dirname (void) +{ + if (gpgconf_ctl.valid && gpgconf_ctl.gnupg) + return gpgconf_ctl.gnupg; + return "gnupg"; +} + +/* Return the hardwired home directory which is not anymore so + * hardwired because it may now be modified using the gpgconf.ctl + * "gnupg" keyword. */ +static const char * +my_fixed_default_homedir (void) +{ + if (gpgconf_ctl.valid && gpgconf_ctl.gnupg) + { + static char *name; + char *p; + + if (!name) + { + name = xmalloc (strlen (GNUPG_DEFAULT_HOMEDIR) + + strlen (gpgconf_ctl.gnupg) + 1); + strcpy (name, GNUPG_DEFAULT_HOMEDIR); + p = strrchr (name, '/'); + if (p) + p++; + else + p = name; + if (*p == '.') + p++; /* Keep a leading dot. */ + strcpy (p, gpgconf_ctl.gnupg); + gpgrt_annotate_leaked_object (name); + } + return name; + } + return GNUPG_DEFAULT_HOMEDIR; +} + + + +/* Under Windows we need to modify the standard registry key with the + * "gnupg" keyword from a gpgconf.ctl. */ +#ifdef HAVE_W32_SYSTEM +const char * +gnupg_registry_dir (void) +{ + if (gpgconf_ctl.valid && gpgconf_ctl.gnupg) + { + static char *name; + char *p; + + if (!name) + { + name = xmalloc (strlen (GNUPG_REGISTRY_DIR) + + strlen (gpgconf_ctl.gnupg) + 1); + strcpy (name, GNUPG_REGISTRY_DIR); + p = strrchr (name, '\\'); + if (p) + p++; + else + p = name; + strcpy (p, gpgconf_ctl.gnupg); + if (!strncmp (p, "gnupg", 5)) + { + /* Registry keys are case-insensitive and we use a + * capitalized version of gnupg by default. So, if the + * new value starts with "gnupg" we apply the usual + * capitalization for this first part. */ + p[0] = 'G'; + p[3] = 'P'; + p[4] = 'G'; + } + gpgrt_annotate_leaked_object (name); + } + return name; + } + return GNUPG_REGISTRY_DIR; +} +#endif /*HAVE_W32_SYSTEM*/ /* This is a helper function to load and call a Windows function from * either of one DLLs. On success an UTF-8 file name is returned. * ERRNO is _not_ set on error. */ #ifdef HAVE_W32_SYSTEM static char * w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d) { static int initialized; static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPWSTR); wchar_t wfname[MAX_PATH]; if (!initialized) { static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL }; void *handle; int i; initialized = 1; for (i=0, handle = NULL; !handle && dllnames[i]; i++) { handle = dlopen (dllnames[i], RTLD_LAZY); if (handle) { func = dlsym (handle, "SHGetFolderPathW"); if (!func) { dlclose (handle); handle = NULL; } } } } if (func && func (a,b,c,d,wfname) >= 0) return wchar_to_utf8 (wfname); else return NULL; } #endif /*HAVE_W32_SYSTEM*/ /* Given the directory name DNAME try to create a common.conf and * enable the keyboxd. This should only be called for the standard * home directory and only if that directory has just been created. */ static void create_common_conf (const char *dname) { #ifdef BUILD_WITH_KEYBOXD estream_t fp; char *fcommon; fcommon = make_filename (dname, "common.conf", NULL); fp = es_fopen (fcommon, "wx,mode=-rw-r"); if (!fp) { log_info (_("error creating '%s': %s\n"), fcommon, gpg_strerror (gpg_error_from_syserror ())); } else { if (es_fputs ("use-keyboxd\n", fp) == EOF) { log_info (_("error writing to '%s': %s\n"), fcommon, gpg_strerror (es_ferror (fp) ? gpg_error_from_syserror () : gpg_error (GPG_ERR_EOF))); es_fclose (fp); } else if (es_fclose (fp)) { log_info (_("error closing '%s': %s\n"), fcommon, gpg_strerror (gpg_error_from_syserror ())); } } #endif /* BUILD_WITH_KEYBOXD */ } /* Check whether DIR is the default homedir. */ static int is_gnupg_default_homedir (const char *dir) { int result; char *a = make_absfilename (dir, NULL); char *b = make_absfilename (standard_homedir (), NULL); result = !compare_filenames (a, b); xfree (b); xfree (a); return result; } /* Helper to remove trailing slashes from NEWDIR. Return a new * allocated string if that has been done or NULL if there are no * slashes to remove. Also inserts a missing slash after a Windows * drive letter. */ static char * copy_dir_with_fixup (const char *newdir) { char *result = NULL; char *p; #ifdef HAVE_W32_SYSTEM char *p0; const char *s; #endif if (!*newdir) return NULL; #ifdef HAVE_W32_SYSTEM if (newdir[0] && newdir[1] == ':' && !(newdir[2] == '/' || newdir[2] == '\\')) { /* Drive letter with missing leading slash. */ p = result = xmalloc (strlen (newdir) + 1 + 1); *p++ = newdir[0]; *p++ = newdir[1]; *p++ = '\\'; strcpy (p, newdir+2); /* Remove trailing slashes. */ p = result + strlen (result) - 1; while (p > result+2 && (*p == '/' || *p == '\\')) *p-- = 0; } else if (newdir[strlen (newdir)-1] == '/' || newdir[strlen (newdir)-1] == '\\' ) { result = xstrdup (newdir); p = result + strlen (result) - 1; while (p > result && (*p == '/' || *p == '\\') && (p-1 > result && p[-1] != ':')) /* We keep "c:/". */ *p-- = 0; } /* Hack to mitigate badly doubled backslashes. */ s = result? result : newdir; if (s[0] == '\\' && s[1] == '\\' && s[2] != '\\') { /* UNC (\\Servername\file) or Long UNC (\\?\Servername\file) * Does not seem to be double quoted. */ } else if (strstr (s, "\\\\")) { /* Double quotes detected. Fold them into one because that is * what what Windows does. This way we get a unique hash * regardless of the number of doubled backslashes. */ if (!result) result = xstrdup (newdir); for (p0=p=result; *p; p++) { *p0++ = *p; while (*p == '\\' && p[1] == '\\') p++; } *p0 = 0; } #else /*!HAVE_W32_SYSTEM*/ if (newdir[strlen (newdir)-1] == '/') { result = xstrdup (newdir); p = result + strlen (result) - 1; while (p > result && *p == '/') *p-- = 0; } #endif /*!HAVE_W32_SYSTEM*/ return result; } /* Get the standard home directory. In general this function should not be used as it does not consider a registry value (under W32) or the GNUPGHOME environment variable. It is better to use gnupg_homedir(). */ const char * standard_homedir (void) { #ifdef HAVE_W32_SYSTEM static const char *dir; if (!dir) { const char *rdir; rdir = w32_rootdir (); if (w32_portable_app) { dir = xstrconcat (rdir, DIRSEP_S "home", NULL); gpgrt_annotate_leaked_object (dir); } else { char *path; path = w32_shgetfolderpath (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0); if (path) { - dir = xstrconcat (path, "\\gnupg", NULL); + dir = xstrconcat (path, "\\", my_gnupg_dirname (), NULL); xfree (path); gpgrt_annotate_leaked_object (dir); /* Try to create the directory if it does not yet exists. */ if (gnupg_access (dir, F_OK)) if (!gnupg_mkdir (dir, "-rwx")) create_common_conf (dir); } else - dir = GNUPG_DEFAULT_HOMEDIR; + dir = my_fixed_default_homedir (); } } return dir; #else/*!HAVE_W32_SYSTEM*/ - return GNUPG_DEFAULT_HOMEDIR; + return my_fixed_default_homedir (); #endif /*!HAVE_W32_SYSTEM*/ } /* Set up the default home directory. The usual --homedir option should be parsed later. */ static const char * default_homedir (void) { const char *dir; #ifdef HAVE_W32_SYSTEM /* For a portable application we only use the standard homedir. */ w32_rootdir (); if (w32_portable_app) return standard_homedir (); #endif /*HAVE_W32_SYSTEM*/ dir = getenv ("GNUPGHOME"); #ifdef HAVE_W32_SYSTEM if (!dir || !*dir) { static const char *saved_dir; if (!saved_dir) { if (!dir || !*dir) { char *tmp, *p; /* This is deprecated; gpgconf --list-dirs prints a * warning if the homedir has been taken from the * registry. */ tmp = read_w32_registry_string (NULL, - GNUPG_REGISTRY_DIR, + gnupg_registry_dir (), "HomeDir"); if (tmp && !*tmp) { xfree (tmp); tmp = NULL; } if (tmp) { /* Strip trailing backslashes. */ p = tmp + strlen (tmp) - 1; while (p > tmp && *p == '\\') *p-- = 0; saved_dir = tmp; } } if (!saved_dir) saved_dir = standard_homedir (); } dir = saved_dir; } #endif /*HAVE_W32_SYSTEM*/ if (!dir || !*dir) - dir = GNUPG_DEFAULT_HOMEDIR; + dir = my_fixed_default_homedir (); else { char *p; p = copy_dir_with_fixup (dir); if (p) { /* A new buffer has been allocated with proper semantics. * Assign this to DIR. If DIR is passed again to * copy_dir_with_fixup there will be no need for a fix up * and the function returns NULL. Thus we leak only once. * Setting the homedir is usually a one-off task but might * be called a second time. We also ignore such extra leaks * because we don't know who still references the former * string. */ gpgrt_annotate_leaked_object (p); dir = p; } if (!is_gnupg_default_homedir (dir)) non_default_homedir = 1; } return dir; } /* Return true if S can be inteprtated as true. This is uised for * keywords in gpgconf.ctl. Spaces must have been trimmed. */ static int string_is_true (const char *s) { return (atoi (s) || !ascii_strcasecmp (s, "yes") || !ascii_strcasecmp (s, "true") || !ascii_strcasecmp (s, "fact")); } /* This function is used to parse the gpgconf.ctl file and set the * information ito the gpgconf_ctl structure. This is called once * with the full filename of gpgconf.ctl. There are two callers: One * used on Windows and one on Unix. No error return but diagnostics * are printed. */ static void parse_gpgconf_ctl (const char *fname) { gpg_error_t err; char *p; char *line; size_t linelen; ssize_t length; estream_t fp; const char *name; int anyitem = 0; int ignoreall = 0; + char *gnupgval = NULL; char *rootdir = NULL; char *sysconfdir = NULL; char *socketdir = NULL; if (gpgconf_ctl.checked) return; /* Just in case this is called a second time. */ gpgconf_ctl.checked = 1; gpgconf_ctl.found = 0; gpgconf_ctl.valid = 0; gpgconf_ctl.empty = 0; if (gnupg_access (fname, F_OK)) return; /* No gpgconf.ctl file. */ /* log_info ("detected '%s'\n", buffer); */ fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); log_info ("error opening '%s': %s\n", fname, gpg_strerror (err)); return; } gpgconf_ctl.found = 1; line = NULL; linelen = 0; while ((length = es_read_line (fp, &line, &linelen, NULL)) > 0) { static const char *names[] = { + "gnupg", "rootdir", "sysconfdir", "socketdir", "portable", ".enable" }; int i; size_t n; /* Strip NL and CR, if present. */ while (length > 0 && (line[length - 1] == '\n' || line[length - 1] == '\r')) line[--length] = 0; trim_spaces (line); if (*line == '#' || !*line) continue; anyitem = 1; /* Find the keyword. */ name = NULL; p = NULL; for (i=0; i < DIM (names); i++) { n = strlen (names[i]); if (!strncmp (line, names[i], n)) { while (line[n] == ' ' || line[n] == '\t') n++; if (line[n] == '=') { name = names[i]; p = line + n + 1; break; } } } if (!name) continue; /* Keyword not known. */ trim_spaces (p); p = substitute_envvars (p); if (!p) { err = gpg_error_from_syserror (); log_info ("error getting %s from gpgconf.ctl: %s\n", name, gpg_strerror (err)); } else if (!strcmp (name, ".enable")) { if (string_is_true (p)) ; /* Yes, this file shall be used. */ else ignoreall = 1; /* No, this file shall be ignored. */ xfree (p); } + else if (!strcmp (name, "gnupg")) + { + xfree (gnupgval); + gnupgval = p; + } else if (!strcmp (name, "sysconfdir")) { xfree (sysconfdir); sysconfdir = p; } else if (!strcmp (name, "socketdir")) { xfree (socketdir); socketdir = p; } else if (!strcmp (name, "rootdir")) { xfree (rootdir); rootdir = p; } else if (!strcmp (name, "portable")) { gpgconf_ctl.portable = string_is_true (p); xfree (p); } else /* Unknown keyword. */ xfree (p); } if (es_ferror (fp)) { err = gpg_error_from_syserror (); log_info ("error reading '%s': %s\n", fname, gpg_strerror (err)); ignoreall = 1; /* Force all entries to invalid. */ } es_fclose (fp); xfree (line); if (ignoreall) ; /* Forced error. Note that .found is still set. */ + else if (gnupgval && (!*gnupgval || strpbrk (gnupgval, "/\\"))) + { + /* We don't allow a slash or backslash in the value because our + * code assumes this is a single directory name. */ + log_info ("invalid %s '%s' specified in gpgconf.ctl\n", + "gnupg", gnupgval); + } else if (rootdir && (!*rootdir || *rootdir != '/')) { log_info ("invalid %s '%s' specified in gpgconf.ctl\n", "rootdir", rootdir); } else if (sysconfdir && (!*sysconfdir || *sysconfdir != '/')) { log_info ("invalid %s '%s' specified in gpgconf.ctl\n", "sysconfdir", sysconfdir); } else if (socketdir && (!*socketdir || *socketdir != '/')) { log_info ("invalid %s '%s' specified in gpgconf.ctl\n", "socketdir", socketdir); } else { + if (gnupgval) + { + gpgconf_ctl.gnupg = gnupgval; + gpgrt_annotate_leaked_object (gpgconf_ctl.gnupg); + /* log_info ("want gnupg '%s'\n", dir); */ + } if (rootdir) { while (*rootdir && rootdir[strlen (rootdir)-1] == '/') rootdir[strlen (rootdir)-1] = 0; gpgconf_ctl.rootdir = rootdir; gpgrt_annotate_leaked_object (gpgconf_ctl.rootdir); /* log_info ("want rootdir '%s'\n", dir); */ } if (sysconfdir) { while (*sysconfdir && sysconfdir[strlen (sysconfdir)-1] == '/') sysconfdir[strlen (sysconfdir)-1] = 0; gpgconf_ctl.sysconfdir = sysconfdir; gpgrt_annotate_leaked_object (gpgconf_ctl.sysconfdir); /* log_info ("want sysconfdir '%s'\n", sdir); */ } if (socketdir) { while (*socketdir && socketdir[strlen (socketdir)-1] == '/') socketdir[strlen (socketdir)-1] = 0; gpgconf_ctl.socketdir = socketdir; gpgrt_annotate_leaked_object (gpgconf_ctl.socketdir); /* log_info ("want socketdir '%s'\n", s2dir); */ } gpgconf_ctl.valid = 1; } gpgconf_ctl.empty = !anyitem; if (!gpgconf_ctl.valid) { /* Error reading some entries - clear them all. */ + xfree (gnupgval); xfree (rootdir); xfree (sysconfdir); xfree (socketdir); + gpgconf_ctl.gnupg = NULL; gpgconf_ctl.rootdir = NULL; gpgconf_ctl.sysconfdir = NULL; gpgconf_ctl.socketdir = NULL; } } #ifdef HAVE_W32_SYSTEM /* Check whether gpgconf is installed and if so read the gpgconf.ctl file. */ static void check_portable_app (const char *dir) { char *fname; fname = xstrconcat (dir, DIRSEP_S "gpgconf.exe", NULL); if (!gnupg_access (fname, F_OK)) { strcpy (fname + strlen (fname) - 3, "ctl"); parse_gpgconf_ctl (fname); if ((gpgconf_ctl.found && gpgconf_ctl.empty) || (gpgconf_ctl.valid && gpgconf_ctl.portable)) { unsigned int flags; /* Classic gpgconf.ctl file found. This is a portable * application. Note that if there are any items in that * file we don't consider this a portable application unless * the (later added) ".portable" keyword has also been * seen. */ w32_portable_app = 1; log_get_prefix (&flags); log_set_prefix (NULL, (flags | GPGRT_LOG_NO_REGISTRY)); } } xfree (fname); } #endif /*HAVE_W32_SYSTEM*/ #ifdef HAVE_W32_SYSTEM /* Determine the root directory of the gnupg installation on Windows. */ static const char * w32_rootdir (void) { static int got_dir; static char dir[MAX_PATH+5]; if (!got_dir) { char *p; int rc; wchar_t wdir [MAX_PATH+5]; rc = GetModuleFileNameW (NULL, wdir, MAX_PATH); if (rc && WideCharToMultiByte (CP_UTF8, 0, wdir, -1, dir, MAX_PATH-4, NULL, NULL) < 0) rc = 0; if (!rc) { log_debug ("GetModuleFileName failed: %s\n", w32_strerror (-1)); *dir = 0; } got_dir = 1; p = strrchr (dir, DIRSEP_C); if (p) { *p = 0; check_portable_app (dir); /* If we are installed below "bin" we strip that and use the top directory instead. */ p = strrchr (dir, DIRSEP_C); if (p && !strcmp (p+1, "bin")) { *p = 0; w32_bin_is_bin = 1; } } if (!p) { log_debug ("bad filename '%s' returned for this process\n", dir); *dir = 0; } } if (*dir) return dir; /* Fallback to the hardwired value. */ return GNUPG_LIBEXECDIR; } #endif /*HAVE_W32_SYSTEM*/ #ifndef HAVE_W32_SYSTEM /* Unix */ /* Determine the root directory of the gnupg installation on Unix. * The standard case is that this function returns NULL so that the * root directory as configured at build time is used. However, it * may return a static string with a different root directory, similar * to what we do on Windows. That second mode is triggered by the * existence of a file gpgconf.ctl installed side-by-side to gpgconf. * This file is parsed for keywords describing the actually to be used * root directory. There is no solid standard on Unix to locate the * binary used to create the process, thus we support this currently * only on Linux and BSD where we can look this info up using the proc * file system. If WANT_SYSCONFDIR is true the optional sysconfdir * entry is returned. */ static const char * unix_rootdir (enum wantdir_values wantdir) { if (!gpgconf_ctl.checked) { char *p; char *buffer; size_t bufsize = 256-1; int nread; gpg_error_t err; const char *name; for (;;) { buffer = xmalloc (bufsize+1); nread = readlink (MYPROC_SELF_EXE, buffer, bufsize); if (nread < 0) { err = gpg_error_from_syserror (); buffer[0] = 0; if ((name = getenv ("GNUPG_BUILD_ROOT")) && *name == '/') { /* Try a fallback for systems w/o a supported /proc * file system if we are running a regression test. */ log_info ("error reading symlink '%s': %s\n", MYPROC_SELF_EXE, gpg_strerror (err)); xfree (buffer); buffer = xstrconcat (name, "/bin/gpgconf", NULL); log_info ("trying fallback '%s'\n", buffer); } break; } else if (nread < bufsize) { buffer[nread] = 0; break; /* Got it. */ } else if (bufsize >= 4095) { buffer[0] = 0; log_info ("error reading symlink '%s': %s\n", MYPROC_SELF_EXE, "value too large"); break; } xfree (buffer); bufsize += 256; } if (!*buffer) { xfree (buffer); gpgconf_ctl.checked = 1; return NULL; /* Error - assume no gpgconf.ctl. */ } p = strrchr (buffer, '/'); if (!p) { xfree (buffer); gpgconf_ctl.checked = 1; return NULL; /* Erroneous /proc - assume no gpgconf.ctl. */ } *p = 0; /* BUFFER has the directory. */ if (!(p = strrchr (buffer, '/'))) { /* Installed in the root which is not a good idea. Assume * no gpgconf.ctl. */ xfree (buffer); gpgconf_ctl.checked = 1; return NULL; } /* Strip one part and expect the file below a bin dir. */ *p = 0; p = xstrconcat (buffer, "/bin/gpgconf.ctl", NULL); xfree (buffer); buffer = p; parse_gpgconf_ctl (buffer); xfree (buffer); } if (!gpgconf_ctl.valid) return NULL; /* No valid entries in gpgconf.ctl */ switch (wantdir) { case WANTDIR_ROOT: return gpgconf_ctl.rootdir; case WANTDIR_SYSCONF: return gpgconf_ctl.sysconfdir; case WANTDIR_SOCKET: return gpgconf_ctl.socketdir; } return NULL; /* Not reached. */ } #endif /* Unix */ #ifdef HAVE_W32_SYSTEM static const char * w32_commondir (void) { static char *dir; if (!dir) { const char *rdir; char *path; /* Make sure that w32_rootdir has been called so that we are able to check the portable application flag. The common dir is the identical to the rootdir. In that case there is also no need to strdup its value. */ rdir = w32_rootdir (); if (w32_portable_app) return rdir; path = w32_shgetfolderpath (NULL, CSIDL_COMMON_APPDATA, NULL, 0); if (path) { dir = xstrconcat (path, "\\GNU", NULL); /* No auto create of the directory. Either the installer or * the admin has to create these directories. */ } else { /* Folder not found or defined - probably an old Windows * version. Use the installation directory instead. */ dir = xstrdup (rdir); } gpgrt_annotate_leaked_object (dir); } return dir; } #endif /*HAVE_W32_SYSTEM*/ /* Change the homedir. Some care must be taken to set this early * enough because previous calls to gnupg_homedir may else return a * different string. */ void gnupg_set_homedir (const char *newdir) { char *tmp = NULL; if (!newdir || !*newdir) newdir = default_homedir (); else { tmp = copy_dir_with_fixup (newdir); if (tmp) newdir = tmp; if (!is_gnupg_default_homedir (newdir)) non_default_homedir = 1; } xfree (the_gnupg_homedir); the_gnupg_homedir = make_absfilename (newdir, NULL);; xfree (tmp); /* Fixme: Should we use * gpgrt_annotate_leaked_object(the_gnupg_homedir) * despite that we may free and allocate a new one in some * cases? */ } /* Create the homedir directory only if the supplied directory name is * the same as the default one. This way we avoid to create arbitrary * directories when a non-default home directory is used. To cope * with HOME, we do compare only the suffix if we see that the default * homedir does start with a tilde. If the mkdir fails the function * terminates the process. If QUIET is set not diagnostic is printed * on homedir creation. */ void gnupg_maybe_make_homedir (const char *fname, int quiet) { const char *defhome = standard_homedir (); if ( #ifdef HAVE_W32_SYSTEM ( !compare_filenames (fname, defhome) ) #else ( *defhome == '~' && (strlen(fname) >= strlen (defhome+1) && !strcmp(fname+strlen(fname)-strlen(defhome+1), defhome+1 ) )) || (*defhome != '~' && !compare_filenames( fname, defhome ) ) #endif ) { if (gnupg_mkdir (fname, "-rwx")) log_fatal ( _("can't create directory '%s': %s\n"), fname, strerror(errno) ); else { if (!quiet ) log_info ( _("directory '%s' created\n"), fname ); create_common_conf (fname); } } } /* Return the homedir. The returned string is valid until another * gnupg-set-homedir call. This is always an absolute directory name. * The function replaces the former global var opt.homedir. */ const char * gnupg_homedir (void) { /* If a homedir has not been set, set it to the default. */ if (!the_gnupg_homedir) the_gnupg_homedir = make_absfilename (default_homedir (), NULL); return the_gnupg_homedir; } /* Return whether the home dir is the default one. */ int gnupg_default_homedir_p (void) { return !non_default_homedir; } /* Return the directory name used by daemons for their current working * directory. */ const char * gnupg_daemon_rootdir (void) { #ifdef HAVE_W32_SYSTEM static char *name; if (!name) { char path[MAX_PATH]; size_t n; n = GetSystemDirectoryA (path, sizeof path); if (!n || n >= sizeof path) name = xstrdup ("/"); /* Error - use the curret top dir instead. */ else name = xstrdup (path); gpgrt_annotate_leaked_object (name); } return name; #else /*!HAVE_W32_SYSTEM*/ return "/"; #endif /*!HAVE_W32_SYSTEM*/ } /* Helper for gnupg-socketdir. This is a global function, so that * gpgconf can use it for its --create-socketdir command. If * SKIP_CHECKS is set permission checks etc. are not done. The * function always returns a malloced directory name and stores these * bit flags at R_INFO: * * 1 := Internal error, stat failed, out of core, etc. * 2 := No /run/user directory. * 4 := Directory not owned by the user, not a directory * or wrong permissions. * 8 := Same as 4 but for the subdir. * 16 := mkdir failed * 32 := Non default homedir; checking subdir. * 64 := Subdir does not exist. * 128 := Using homedir as fallback. */ char * _gnupg_socketdir_internal (int skip_checks, unsigned *r_info) { #if defined(HAVE_W32_SYSTEM) char *name; (void)skip_checks; *r_info = 0; /* First make sure that non_default_homedir and w32_portable_app can * be set. */ gnupg_homedir (); if (w32_portable_app) { - name = xstrconcat (w32_rootdir (), DIRSEP_S, "gnupg", NULL); + name = xstrconcat (w32_rootdir (), DIRSEP_S, my_gnupg_dirname (), NULL); } else { char *path; path = w32_shgetfolderpath (NULL, CSIDL_LOCAL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0); if (path) { - name = xstrconcat (path, "\\gnupg", NULL); + name = xstrconcat (path, "\\", my_gnupg_dirname (), NULL); xfree (path); if (gnupg_access (name, F_OK)) gnupg_mkdir (name, "-rwx"); } else { name = xstrdup (gnupg_homedir ()); } } /* If a non default homedir is used, we check whether an * corresponding sub directory below the socket dir is available * and use that. We hash the non default homedir to keep the new * subdir short enough. */ if (non_default_homedir) { char sha1buf[20]; struct stat sb; char *suffix; char *p; *r_info |= 32; /* Testing subdir. */ /* Canonicalize the name to avoid problems with mixed case * names. Note that we use only 10 bytes of the hash because on * Windows the account name is also part of the name. */ suffix = ascii_strlwr (xstrdup (gnupg_homedir ())); for (p=suffix; *p; p++) if ( *p == '\\') *p = '/'; gcry_md_hash_buffer (GCRY_MD_SHA1, sha1buf, suffix, strlen (suffix)); xfree (suffix); suffix = zb32_encode (sha1buf, 8*10); if (!suffix) { *r_info |= 1; /* Out of core etc. */ goto leave_w32; } p = xstrconcat (name, "\\d.", suffix, NULL); xfree (suffix); xfree (name); name = p; /* Stat that directory and check constraints. * The command * gpgconf --remove-socketdir * can be used to remove that directory. */ if (gnupg_stat (name, &sb)) { if (errno != ENOENT) *r_info |= 1; /* stat failed. */ else if (!skip_checks) { /* Try to create the directory and check again. */ if (gnupg_mkdir (name, "-rwx")) *r_info |= 16; /* mkdir failed. */ else if (gnupg_stat (name, &sb)) { if (errno != ENOENT) *r_info |= 1; /* stat failed. */ else *r_info |= 64; /* Subdir does not exist. */ } else goto leave_w32; /* Success! */ } else *r_info |= 64; /* Subdir does not exist. */ if (!skip_checks) { xfree (name); name = NULL; goto leave_w32; } } } leave_w32: /* If nothing works - fall back to the homedir. */ if (!name) { *r_info |= 128; /* Fallback. */ name = xstrdup (gnupg_homedir ()); } #elif !defined(HAVE_STAT) char *name; (void)skip_checks; *r_info = 0; name = xstrdup (gnupg_homedir ()); #else /* Unix and stat(2) available. */ static const char * const bases[] = { #ifdef USE_RUN_GNUPG_USER_SOCKET "/run/gnupg", #endif "/run", #ifdef USE_RUN_GNUPG_USER_SOCKET "/var/run/gnupg", #endif "/var/run", NULL }; int i; struct stat sb; - char prefixbuffer[19 + 1 + 20 + 6 + 1]; + char prefixbuffer[256]; const char *prefix; const char *s; char *name = NULL; + const char *gnupgname = my_gnupg_dirname (); *r_info = 0; /* First make sure that non_default_homedir can be set. */ gnupg_homedir (); /* It has been suggested to first check XDG_RUNTIME_DIR envvar. * However, the specs state that the lifetime of the directory MUST * be bound to the user being logged in. Now GnuPG may also be run * as a background process with no (desktop) user logged in. Thus * we better don't do that. */ prefix = unix_rootdir (WANTDIR_SOCKET); if (!prefix) { /* gpgconf.ctl does not specify a directory. Check whether we * have the usual /run/[gnupg/]user dir. */ for (i=0; bases[i]; i++) { snprintf (prefixbuffer, sizeof prefixbuffer, "%s/user/%u", bases[i], (unsigned int)getuid ()); prefix = prefixbuffer; if (!stat (prefix, &sb) && S_ISDIR(sb.st_mode)) break; } if (!bases[i]) { *r_info |= 2; /* No /run/user directory. */ goto leave; } if (sb.st_uid != getuid ()) { *r_info |= 4; /* Not owned by the user. */ if (!skip_checks) goto leave; } - if (strlen (prefix) + 7 >= sizeof prefixbuffer) + if (strlen (prefix) + strlen (gnupgname) + 2 >= sizeof prefixbuffer) { *r_info |= 1; /* Ooops: Buffer too short to append "/gnupg". */ goto leave; } - strcat (prefixbuffer, "/gnupg"); + strcat (prefixbuffer, "/"); + strcat (prefixbuffer, gnupgname); } /* Check whether the gnupg sub directory (or the specified diretory) * has proper permissions. */ if (stat (prefix, &sb)) { if (errno != ENOENT) { *r_info |= 1; /* stat failed. */ goto leave; } /* Try to create the directory and check again. */ if (gnupg_mkdir (prefix, "-rwx")) { *r_info |= 16; /* mkdir failed. */ goto leave; } if (stat (prefix, &sb)) { *r_info |= 1; /* stat failed. */ goto leave; } } /* Check that it is a directory, owned by the user, and only the * user has permissions to use it. */ if (!S_ISDIR(sb.st_mode) || sb.st_uid != getuid () || (sb.st_mode & (S_IRWXG|S_IRWXO))) { *r_info |= 4; /* Bad permissions or not a directory. */ if (!skip_checks) goto leave; } /* If a non default homedir is used, we check whether an * corresponding sub directory below the socket dir is available * and use that. We hash the non default homedir to keep the new * subdir short enough. */ if (non_default_homedir) { char sha1buf[20]; char *suffix; *r_info |= 32; /* Testing subdir. */ s = gnupg_homedir (); gcry_md_hash_buffer (GCRY_MD_SHA1, sha1buf, s, strlen (s)); suffix = zb32_encode (sha1buf, 8*15); if (!suffix) { *r_info |= 1; /* Out of core etc. */ goto leave; } name = strconcat (prefix, "/d.", suffix, NULL); xfree (suffix); if (!name) { *r_info |= 1; /* Out of core etc. */ goto leave; } /* Stat that directory and check constraints. * The command * gpgconf --remove-socketdir * can be used to remove that directory. */ if (stat (name, &sb)) { if (errno != ENOENT) *r_info |= 1; /* stat failed. */ else if (!skip_checks) { /* Try to create the directory and check again. */ if (gnupg_mkdir (name, "-rwx")) *r_info |= 16; /* mkdir failed. */ else if (stat (prefix, &sb)) { if (errno != ENOENT) *r_info |= 1; /* stat failed. */ else *r_info |= 64; /* Subdir does not exist. */ } else goto leave; /* Success! */ } else *r_info |= 64; /* Subdir does not exist. */ if (!skip_checks) { xfree (name); name = NULL; goto leave; } } else if (!S_ISDIR(sb.st_mode) || sb.st_uid != getuid () || (sb.st_mode & (S_IRWXG|S_IRWXO))) { *r_info |= 8; /* Bad permissions or subdir is not a directory. */ if (!skip_checks) { xfree (name); name = NULL; goto leave; } } } else name = xstrdup (prefix); leave: /* If nothing works fall back to the homedir. */ if (!name) { *r_info |= 128; /* Fallback. */ name = xstrdup (gnupg_homedir ()); } #endif /* Unix */ return name; } /* * Return the name of the socket dir. That is the directory used for * the IPC local sockets. This is an absolute directory name. */ const char * gnupg_socketdir (void) { static char *name; if (!name) { unsigned int dummy; name = _gnupg_socketdir_internal (0, &dummy); gpgrt_annotate_leaked_object (name); } return name; } /* Return the name of the sysconfdir. This is a static string. This function is required because under Windows we can't simply compile it in. */ const char * gnupg_sysconfdir (void) { #ifdef HAVE_W32_SYSTEM static char *name; if (!name) { - const char *s1, *s2; - s1 = w32_commondir (); - s2 = DIRSEP_S "etc" DIRSEP_S "gnupg"; - name = xmalloc (strlen (s1) + strlen (s2) + 1); - strcpy (stpcpy (name, s1), s2); + name = xstrconcat (w32_commondir (), DIRSEP_S, "etc", DIRSEP_S, + my_gnupg_dirname (), NULL); gpgrt_annotate_leaked_object (name); } return name; #else /*!HAVE_W32_SYSTEM*/ const char *dir = unix_rootdir (WANTDIR_SYSCONF); if (dir) return dir; else return GNUPG_SYSCONFDIR; #endif /*!HAVE_W32_SYSTEM*/ } const char * gnupg_bindir (void) { static char *name; const char *rdir; #if defined(HAVE_W32_SYSTEM) rdir = w32_rootdir (); if (w32_bin_is_bin) { if (!name) { name = xstrconcat (rdir, DIRSEP_S "bin", NULL); gpgrt_annotate_leaked_object (name); } return name; } else return rdir; #else /*!HAVE_W32_SYSTEM*/ rdir = unix_rootdir (WANTDIR_ROOT); if (rdir) { if (!name) { name = xstrconcat (rdir, DIRSEP_S "bin", NULL); gpgrt_annotate_leaked_object (name); } return name; } else return GNUPG_BINDIR; #endif /*!HAVE_W32_SYSTEM*/ } /* Return the name of the libexec directory. The name is allocated in a static area on the first use. This function won't fail. */ const char * gnupg_libexecdir (void) { #ifdef HAVE_W32_SYSTEM return gnupg_bindir (); #else /*!HAVE_W32_SYSTEM*/ static char *name; const char *rdir; rdir = unix_rootdir (WANTDIR_ROOT); if (rdir) { if (!name) { name = xstrconcat (rdir, DIRSEP_S "libexec", NULL); gpgrt_annotate_leaked_object (name); } return name; } else return GNUPG_LIBEXECDIR; #endif /*!HAVE_W32_SYSTEM*/ } const char * gnupg_libdir (void) { static char *name; #ifdef HAVE_W32_SYSTEM if (!name) { name = xstrconcat (w32_rootdir (), DIRSEP_S "lib" DIRSEP_S "gnupg", NULL); gpgrt_annotate_leaked_object (name); } return name; #else /*!HAVE_W32_SYSTEM*/ const char *rdir; rdir = unix_rootdir (WANTDIR_ROOT); if (rdir) { if (!name) { name = xstrconcat (rdir, DIRSEP_S "lib", DIRSEP_S, "gnupg", NULL); gpgrt_annotate_leaked_object (name); } return name; } else return GNUPG_LIBDIR; #endif /*!HAVE_W32_SYSTEM*/ } const char * gnupg_datadir (void) { static char *name; #ifdef HAVE_W32_SYSTEM if (!name) { name = xstrconcat (w32_rootdir (), DIRSEP_S "share" DIRSEP_S "gnupg", NULL); gpgrt_annotate_leaked_object (name); } return name; #else /*!HAVE_W32_SYSTEM*/ const char *rdir; rdir = unix_rootdir (WANTDIR_ROOT); if (rdir) { if (!name) { name = xstrconcat (rdir, DIRSEP_S "share" DIRSEP_S "gnupg", NULL); gpgrt_annotate_leaked_object (name); } return name; } else return GNUPG_DATADIR; #endif /*!HAVE_W32_SYSTEM*/ } const char * gnupg_localedir (void) { static char *name; #ifdef HAVE_W32_SYSTEM if (!name) { name = xstrconcat (w32_rootdir (), DIRSEP_S "share" DIRSEP_S "locale", NULL); gpgrt_annotate_leaked_object (name); } return name; #else /*!HAVE_W32_SYSTEM*/ const char *rdir; rdir = unix_rootdir (WANTDIR_ROOT); if (rdir) { if (!name) { name = xstrconcat (rdir, DIRSEP_S "share" DIRSEP_S "locale", NULL); gpgrt_annotate_leaked_object (name); } return name; } else return LOCALEDIR; #endif /*!HAVE_W32_SYSTEM*/ } /* Return the standard socket name used by gpg-agent. */ const char * gpg_agent_socket_name (void) { static char *name; if (!name) { name = make_filename (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL); gpgrt_annotate_leaked_object (name); } return name; } /* Return the user socket name used by DirMngr. */ const char * dirmngr_socket_name (void) { static char *name; if (!name) { name = make_filename (gnupg_socketdir (), DIRMNGR_SOCK_NAME, NULL); gpgrt_annotate_leaked_object (name); } return name; } /* Return the user socket name used by Keyboxd. */ const char * keyboxd_socket_name (void) { static char *name; if (!name) { name = make_filename (gnupg_socketdir (), KEYBOXD_SOCK_NAME, NULL); gpgrt_annotate_leaked_object (name); } return name; } /* Return the default pinentry name. If RESET is true the internal cache is first flushed. */ static const char * get_default_pinentry_name (int reset) { static struct { const char *(*rfnc)(void); const char *name; } names[] = { /* The first entry is what we return in case we found no other pinentry. */ { gnupg_bindir, DIRSEP_S "pinentry" EXEEXT_S }, #ifdef HAVE_W32_SYSTEM /* Try Gpg4win directory (with bin and without.) */ { w32_rootdir, "\\..\\Gpg4win\\bin\\pinentry.exe" }, { w32_rootdir, "\\..\\Gpg4win\\pinentry.exe" }, /* Try a pinentry in a dir above us */ { w32_rootdir, "\\..\\bin\\pinentry.exe" }, /* Try old Gpgwin directory. */ { w32_rootdir, "\\..\\GNU\\GnuPG\\pinentry.exe" }, /* Try a Pinentry from the common GNU dir. */ { w32_rootdir, "\\..\\GNU\\bin\\pinentry.exe" }, #endif /* Last chance is a pinentry-basic (which comes with the GnuPG 2.1 Windows installer). */ { gnupg_bindir, DIRSEP_S "pinentry-basic" EXEEXT_S } }; static char *name; if (reset) { xfree (name); name = NULL; } if (!name) { int i; for (i=0; i < DIM(names); i++) { char *name2; name2 = xstrconcat (names[i].rfnc (), names[i].name, NULL); if (!gnupg_access (name2, F_OK)) { /* Use that pinentry. */ xfree (name); name = name2; break; } if (!i) /* Store the first as fallback return. */ name = name2; else xfree (name2); } if (name) gpgrt_annotate_leaked_object (name); } return name; } /* If set, 'gnupg_module_name' returns modules from that build * directory. */ static char *gnupg_build_directory; /* For sanity checks. */ static int gnupg_module_name_called; /* Set NEWDIR as the new build directory. This will make * 'gnupg_module_name' return modules from that build directory. Must * be called before any invocation of 'gnupg_module_name', and must * not be called twice. It can be used by test suites to make sure * the components from the build directory are used instead of * potentially outdated installed ones. * Fixme: It might be better to make use of the newer gpgconf.ctl feature * for regression testing. */ void gnupg_set_builddir (const char *newdir) { log_assert (! gnupg_module_name_called); log_assert (! gnupg_build_directory); gnupg_build_directory = xtrystrdup (newdir); } /* If no build directory has been configured, try to set it from the * environment. We only do this in development builds to avoid * increasing the set of influential environment variables and hence * the attack surface of production builds. */ static void gnupg_set_builddir_from_env (void) { #if defined(IS_DEVELOPMENT_VERSION) || defined(ENABLE_GNUPG_BUILDDIR_ENVVAR) if (gnupg_build_directory) return; gnupg_build_directory = getenv ("GNUPG_BUILDDIR"); #endif } /* Return the file name of a helper tool. WHICH is one of the GNUPG_MODULE_NAME_foo constants. */ const char * gnupg_module_name (int which) { gnupg_set_builddir_from_env (); gnupg_module_name_called = 1; #define X(a,b,c) do { \ static char *name; \ if (!name) { \ name = gnupg_build_directory \ ? xstrconcat (gnupg_build_directory, \ DIRSEP_S b DIRSEP_S c EXEEXT_S, NULL) \ : xstrconcat (gnupg_ ## a (), DIRSEP_S c EXEEXT_S, NULL); \ gpgrt_annotate_leaked_object (name); \ } \ return name; \ } while (0) switch (which) { case GNUPG_MODULE_NAME_AGENT: #ifdef GNUPG_DEFAULT_AGENT return GNUPG_DEFAULT_AGENT; #else X(bindir, "agent", "gpg-agent"); #endif case GNUPG_MODULE_NAME_PINENTRY: #ifdef GNUPG_DEFAULT_PINENTRY return GNUPG_DEFAULT_PINENTRY; /* (Set by a configure option) */ #else return get_default_pinentry_name (0); #endif case GNUPG_MODULE_NAME_SCDAEMON: #ifdef GNUPG_DEFAULT_SCDAEMON return GNUPG_DEFAULT_SCDAEMON; #else X(libexecdir, "scd", "scdaemon"); #endif case GNUPG_MODULE_NAME_TPM2DAEMON: #ifdef GNUPG_DEFAULT_TPM2DAEMON return GNUPG_DEFAULT_TPM2DAEMON; #else X(libexecdir, "tpm2d", TPM2DAEMON_NAME); #endif case GNUPG_MODULE_NAME_DIRMNGR: #ifdef GNUPG_DEFAULT_DIRMNGR return GNUPG_DEFAULT_DIRMNGR; #else X(bindir, "dirmngr", DIRMNGR_NAME); #endif case GNUPG_MODULE_NAME_KEYBOXD: #ifdef GNUPG_DEFAULT_KEYBOXD return GNUPG_DEFAULT_KEYBOXD; #else X(libexecdir, "kbx", KEYBOXD_NAME); #endif case GNUPG_MODULE_NAME_PROTECT_TOOL: #ifdef GNUPG_DEFAULT_PROTECT_TOOL return GNUPG_DEFAULT_PROTECT_TOOL; #else X(libexecdir, "agent", "gpg-protect-tool"); #endif case GNUPG_MODULE_NAME_DIRMNGR_LDAP: #ifdef GNUPG_DEFAULT_DIRMNGR_LDAP return GNUPG_DEFAULT_DIRMNGR_LDAP; #else X(libexecdir, "dirmngr", "dirmngr_ldap"); #endif case GNUPG_MODULE_NAME_CHECK_PATTERN: X(libexecdir, "tools", "gpg-check-pattern"); case GNUPG_MODULE_NAME_GPGSM: X(bindir, "sm", "gpgsm"); case GNUPG_MODULE_NAME_GPG: #if USE_GPG2_HACK if (! gnupg_build_directory) X(bindir, "g10", GPG_NAME "2"); else #endif X(bindir, "g10", GPG_NAME); case GNUPG_MODULE_NAME_GPGV: #if USE_GPG2_HACK if (! gnupg_build_directory) X(bindir, "g10", GPG_NAME "v2"); else #endif X(bindir, "g10", GPG_NAME "v"); case GNUPG_MODULE_NAME_CONNECT_AGENT: X(bindir, "tools", "gpg-connect-agent"); case GNUPG_MODULE_NAME_GPGCONF: X(bindir, "tools", "gpgconf"); case GNUPG_MODULE_NAME_CARD: X(bindir, "tools", "gpg-card"); case GNUPG_MODULE_NAME_GPGTAR: X(bindir, "tools", "gpgtar"); default: BUG (); } #undef X } /* Flush some of the cached module names. This is for example used by gpg-agent to allow configuring a different pinentry. */ void gnupg_module_name_flush_some (void) { (void)get_default_pinentry_name (1); } diff --git a/common/util.h b/common/util.h index e2d95b1af..851b392a5 100644 --- a/common/util.h +++ b/common/util.h @@ -1,408 +1,409 @@ /* util.h - Utility functions for GnuPG * Copyright (C) 2001, 2002, 2003, 2004, 2009 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute and/or modify this * part of GnuPG under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * GnuPG is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copies of the GNU General Public License * and the GNU Lesser General Public License along with this program; * if not, see . */ #ifndef GNUPG_COMMON_UTIL_H #define GNUPG_COMMON_UTIL_H #include /* We need this for the memory function protos. */ #include /* We need errno. */ #include /* We need gpg_error_t and estream. */ /* These error codes are used but not defined in the required * libgpg-error version. Define them here. * Example: (#if GPG_ERROR_VERSION_NUMBER < 0x011500 // 1.21) */ #if GPG_ERROR_VERSION_NUMBER < 0x012f00 /* 1.47 */ # define GPG_ERR_BAD_PUK 320 # define GPG_ERR_NO_RESET_CODE 321 # define GPG_ERR_BAD_RESET_CODE 322 #endif #ifndef EXTERN_UNLESS_MAIN_MODULE # if !defined (INCLUDED_BY_MAIN_MODULE) # define EXTERN_UNLESS_MAIN_MODULE extern # else # define EXTERN_UNLESS_MAIN_MODULE # endif #endif /* Hash function used with libksba. */ #define HASH_FNC ((void (*)(void *, const void*,size_t))gcry_md_write) /* The length of the keygrip. This is a SHA-1 hash of the key * parameters as generated by gcry_pk_get_keygrip. */ #define KEYGRIP_LEN 20 /* The length of the unique blob identifier as used by the keyboxd. * This is the possible truncated fingerprint of the primary key. */ #define UBID_LEN 20 /* Get all the stuff from jnlib. */ #include "../common/logging.h" #include "../common/stringhelp.h" #include "../common/mischelp.h" #include "../common/strlist.h" #include "../common/dotlock.h" #include "../common/utf8conv.h" #include "../common/dynload.h" #include "../common/fwddecl.h" #include "../common/utilproto.h" #include "gettime.h" /* Redefine asprintf by our estream version which uses our own memory allocator.. */ #define asprintf gpgrt_asprintf #define vasprintf gpgrt_vasprintf /* Due to a bug in mingw32's snprintf related to the 'l' modifier and for increased portability we use our snprintf on all systems. */ #undef snprintf #define snprintf gpgrt_snprintf /* Replacements for macros not available with libgpg-error < 1.20. */ /* We need this type even if we are not using libreadline and or we did not include libreadline in the current file. */ #ifndef GNUPG_LIBREADLINE_H_INCLUDED typedef char **rl_completion_func_t (const char *, int, int); #endif /*!GNUPG_LIBREADLINE_H_INCLUDED*/ /* Handy malloc macros - please use only them. */ #define xtrymalloc(a) gcry_malloc ((a)) #define xtrymalloc_secure(a) gcry_malloc_secure ((a)) #define xtrycalloc(a,b) gcry_calloc ((a),(b)) #define xtrycalloc_secure(a,b) gcry_calloc_secure ((a),(b)) #define xtryrealloc(a,b) gcry_realloc ((a),(b)) #define xtryreallocarray(a,b,c,d) gpgrt_reallocarray ((a),(b),(c),(d)) #define xtrystrdup(a) gcry_strdup ((a)) #define xfree(a) gcry_free ((a)) #define xfree_fnc gcry_free #define xmalloc(a) gcry_xmalloc ((a)) #define xmalloc_secure(a) gcry_xmalloc_secure ((a)) #define xcalloc(a,b) gcry_xcalloc ((a),(b)) #define xcalloc_secure(a,b) gcry_xcalloc_secure ((a),(b)) #define xrealloc(a,b) gcry_xrealloc ((a),(b)) #define xstrdup(a) gcry_xstrdup ((a)) /* See also the xreallocarray prototype below. */ /* For compatibility with gpg 1.4 we also define these: */ #define xmalloc_clear(a) gcry_xcalloc (1, (a)) #define xmalloc_secure_clear(a) gcry_xcalloc_secure (1, (a)) /* The default error source of the application. This is different from GPG_ERR_SOURCE_DEFAULT in that it does not depend on the source file and thus is usable in code shared by applications. Defined by init.c. */ extern gpg_err_source_t default_errsource; /* Convenience function to return a gpg-error code for memory allocation failures. This function makes sure that an error will be returned even if accidentally ERRNO is not set. */ static inline gpg_error_t out_of_core (void) { return gpg_error_from_syserror (); } /*-- yesno.c --*/ int answer_is_yes (const char *s); int answer_is_yes_no_default (const char *s, int def_answer); int answer_is_yes_no_quit (const char *s); int answer_is_okay_cancel (const char *s, int def_answer); /*-- xreadline.c --*/ ssize_t read_line (FILE *fp, char **addr_of_buffer, size_t *length_of_buffer, size_t *max_length); /*-- sexputil.c */ char *canon_sexp_to_string (const unsigned char *canon, size_t canonlen); void log_printcanon (const char *text, const unsigned char *sexp, size_t sexplen); void log_printsexp (const char *text, gcry_sexp_t sexp); gpg_error_t make_canon_sexp (gcry_sexp_t sexp, unsigned char **r_buffer, size_t *r_buflen); gpg_error_t make_canon_sexp_pad (gcry_sexp_t sexp, int secure, unsigned char **r_buffer, size_t *r_buflen); gpg_error_t keygrip_from_canon_sexp (const unsigned char *key, size_t keylen, unsigned char *grip); int cmp_simple_canon_sexp (const unsigned char *a, const unsigned char *b); int cmp_canon_sexp (const unsigned char *a, size_t alen, const unsigned char *b, size_t blen, int (*tcmp)(void *ctx, int depth, const unsigned char *aval, size_t avallen, const unsigned char *bval, size_t bvallen), void *tcmpctx); unsigned char *make_simple_sexp_from_hexstr (const char *line, size_t *nscanned); int hash_algo_from_sigval (const unsigned char *sigval); unsigned char *make_canon_sexp_from_rsa_pk (const void *m, size_t mlen, const void *e, size_t elen, size_t *r_len); gpg_error_t get_rsa_pk_from_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char const **r_n, size_t *r_nlen, unsigned char const **r_e, size_t *r_elen); gpg_error_t get_ecc_q_from_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char const **r_q, size_t *r_qlen); gpg_error_t uncompress_ecc_q_in_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char **r_newkeydata, size_t *r_newkeydatalen); int get_pk_algo_from_key (gcry_sexp_t key); int get_pk_algo_from_canon_sexp (const unsigned char *keydata, size_t keydatalen); char *pubkey_algo_string (gcry_sexp_t s_pkey, enum gcry_pk_algos *r_algoid); const char *pubkey_algo_to_string (int algo); const char *hash_algo_to_string (int algo); const char *cipher_mode_to_string (int mode); /*-- convert.c --*/ int hex2bin (const char *string, void *buffer, size_t length); int hexcolon2bin (const char *string, void *buffer, size_t length); char *bin2hex (const void *buffer, size_t length, char *stringbuf); char *bin2hexcolon (const void *buffer, size_t length, char *stringbuf); const char *hex2str (const char *hexstring, char *buffer, size_t bufsize, size_t *buflen); char *hex2str_alloc (const char *hexstring, size_t *r_count); unsigned int hex2fixedbuf (const char *hexstr, void *buffer, size_t bufsize); /*-- percent.c --*/ char *percent_plus_escape (const char *string); char *percent_data_escape (int plus, const char *prefix, const void *data, size_t datalen); char *percent_plus_unescape (const char *string, int nulrepl); char *percent_unescape (const char *string, int nulrepl); size_t percent_plus_unescape_inplace (char *string, int nulrepl); size_t percent_unescape_inplace (char *string, int nulrepl); /*-- openpgp-oid.c --*/ gpg_error_t openpgp_oid_from_str (const char *string, gcry_mpi_t *r_mpi); char *openpgp_oidbuf_to_str (const unsigned char *buf, size_t len); char *openpgp_oid_to_str (gcry_mpi_t a); int openpgp_oidbuf_is_ed25519 (const void *buf, size_t len); int openpgp_oid_is_ed25519 (gcry_mpi_t a); int openpgp_oidbuf_is_cv25519 (const void *buf, size_t len); int openpgp_oid_is_cv25519 (gcry_mpi_t a); int openpgp_oid_is_cv448 (gcry_mpi_t a); int openpgp_oid_is_ed448 (gcry_mpi_t a); const char *openpgp_curve_to_oid (const char *name, unsigned int *r_nbits, int *r_algo); const char *openpgp_oid_to_curve (const char *oid, int canon); const char *openpgp_oid_or_name_to_curve (const char *oidname, int canon); const char *openpgp_enum_curves (int *idxp); const char *openpgp_is_curve_supported (const char *name, int *r_algo, unsigned int *r_nbits); const char *get_keyalgo_string (enum gcry_pk_algos algo, unsigned int nbits, const char *curve); /*-- homedir.c --*/ const char *standard_homedir (void); void gnupg_set_homedir (const char *newdir); void gnupg_maybe_make_homedir (const char *fname, int quiet); const char *gnupg_homedir (void); int gnupg_default_homedir_p (void); +const char *gnupg_registry_dir (void); const char *gnupg_daemon_rootdir (void); const char *gnupg_socketdir (void); const char *gnupg_sysconfdir (void); const char *gnupg_bindir (void); const char *gnupg_libexecdir (void); const char *gnupg_libdir (void); const char *gnupg_datadir (void); const char *gnupg_localedir (void); const char *gpg_agent_socket_name (void); const char *dirmngr_socket_name (void); const char *keyboxd_socket_name (void); char *_gnupg_socketdir_internal (int skip_checks, unsigned *r_info); /* All module names. We also include gpg and gpgsm for the sake for gpgconf. */ #define GNUPG_MODULE_NAME_AGENT 1 #define GNUPG_MODULE_NAME_PINENTRY 2 #define GNUPG_MODULE_NAME_SCDAEMON 3 #define GNUPG_MODULE_NAME_DIRMNGR 4 #define GNUPG_MODULE_NAME_PROTECT_TOOL 5 #define GNUPG_MODULE_NAME_CHECK_PATTERN 6 #define GNUPG_MODULE_NAME_GPGSM 7 #define GNUPG_MODULE_NAME_GPG 8 #define GNUPG_MODULE_NAME_CONNECT_AGENT 9 #define GNUPG_MODULE_NAME_GPGCONF 10 #define GNUPG_MODULE_NAME_DIRMNGR_LDAP 11 #define GNUPG_MODULE_NAME_GPGV 12 #define GNUPG_MODULE_NAME_KEYBOXD 13 #define GNUPG_MODULE_NAME_TPM2DAEMON 14 #define GNUPG_MODULE_NAME_CARD 15 #define GNUPG_MODULE_NAME_GPGTAR 16 const char *gnupg_module_name (int which); void gnupg_module_name_flush_some (void); void gnupg_set_builddir (const char *newdir); /* A list of constants to identify protocols. This is used by tools * which need to distinguish between the different protocols * implemented by GnuPG. May be used as bit flags. */ #define GNUPG_PROTOCOL_OPENPGP 1 /* The one and only (gpg). */ #define GNUPG_PROTOCOL_CMS 2 /* The core of S/MIME (gpgsm) */ #define GNUPG_PROTOCOL_SSH_AGENT 4 /* Out ssh-agent implementation */ /*-- gpgrlhelp.c --*/ void gnupg_rl_initialize (void); /*-- helpfile.c --*/ char *gnupg_get_help_string (const char *key, int only_current_locale); /*-- localename.c --*/ const char *gnupg_messages_locale_name (void); /*-- miscellaneous.c --*/ /* This function is called at startup to tell libgcrypt to use our own logging subsystem. */ void setup_libgcrypt_logging (void); /* Print an out of core message and die. */ void xoutofcore (void); /* Wrapper aroung gpgrt_reallocarray. Uses the gpgrt alloc function * which redirects to the Libgcrypt versions via * init_common_subsystems. Thus this can be used interchangeable with * the other alloc functions. */ void *xreallocarray (void *a, size_t oldnmemb, size_t nmemb, size_t size); /* Same as estream_asprintf but die on memory failure. */ char *xasprintf (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); /* This is now an alias to estream_asprintf. */ char *xtryasprintf (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); /* Replacement for gcry_cipher_algo_name. */ const char *gnupg_cipher_algo_name (int algo); void obsolete_option (const char *configname, unsigned int configlineno, const char *name); const char *print_fname_stdout (const char *s); const char *print_fname_stdin (const char *s); void print_utf8_buffer3 (estream_t fp, const void *p, size_t n, const char *delim); void print_utf8_buffer2 (estream_t fp, const void *p, size_t n, int delim); void print_utf8_buffer (estream_t fp, const void *p, size_t n); void print_utf8_string (estream_t stream, const char *p); void print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved); char *try_make_printable_string (const void *p, size_t n, int delim); char *make_printable_string (const void *p, size_t n, int delim); char *decode_c_string (const char *src); int match_multistr (const char *multistr,const char *match); int gnupg_compare_version (const char *a, const char *b); struct debug_flags_s { unsigned int flag; const char *name; }; int parse_debug_flag (const char *string, unsigned int *debugvar, const struct debug_flags_s *flags); struct compatibility_flags_s { unsigned int flag; const char *name; const char *desc; }; int parse_compatibility_flags (const char *string, unsigned int *flagvar, const struct compatibility_flags_s *flags); gpg_error_t b64decode (const char *string, const char *title, void **r_buffer, size_t *r_buflen); /*-- Simple replacement functions. */ /* We use the gnupg_ttyname macro to be safe not to run into conflicts with an existing but broken ttyname. */ #if !defined(HAVE_TTYNAME) || defined(HAVE_BROKEN_TTYNAME) # define gnupg_ttyname(n) _gnupg_ttyname ((n)) /* Systems without ttyname (W32) will merely return NULL. */ static inline char * _gnupg_ttyname (int fd) { (void)fd; return NULL; } #else /*HAVE_TTYNAME*/ # define gnupg_ttyname(n) ttyname ((n)) #endif /*HAVE_TTYNAME */ #define gnupg_isatty(a) isatty ((a)) /*-- Macros to replace ctype ones to avoid locale problems. --*/ #define spacep(p) (*(p) == ' ' || *(p) == '\t') #define digitp(p) (*(p) >= '0' && *(p) <= '9') #define alphap(p) ((*(p) >= 'A' && *(p) <= 'Z') \ || (*(p) >= 'a' && *(p) <= 'z')) #define alnump(p) (alphap (p) || digitp (p)) #define hexdigitp(a) (digitp (a) \ || (*(a) >= 'A' && *(a) <= 'F') \ || (*(a) >= 'a' && *(a) <= 'f')) /* Note this isn't identical to a C locale isspace() without \f and \v, but works for the purposes used here. */ #define ascii_isspace(a) ((a)==' ' || (a)=='\n' || (a)=='\r' || (a)=='\t') /* The atoi macros assume that the buffer has only valid digits. */ #define atoi_1(p) (*(p) - '0' ) #define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1)) #define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2)) #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) #define xtoi_4(p) ((xtoi_2(p) * 256) + xtoi_2((p)+2)) #endif /*GNUPG_COMMON_UTIL_H*/ diff --git a/doc/tools.texi b/doc/tools.texi index ae960bdc9..9ce0e6bb8 100644 --- a/doc/tools.texi +++ b/doc/tools.texi @@ -1,2251 +1,2258 @@ @c Copyright (C) 2004, 2008 Free Software Foundation, Inc. @c This is part of the GnuPG manual. @c For copying conditions, see the file GnuPG.texi. @include defs.inc @node Helper Tools @chapter Helper Tools GnuPG comes with a couple of smaller tools: @menu * watchgnupg:: Read logs from a socket. * gpgv:: Verify OpenPGP signatures. * addgnupghome:: Create .gnupg home directories. * gpgconf:: Modify .gnupg home directories. * applygnupgdefaults:: Run gpgconf for all users. * gpg-preset-passphrase:: Put a passphrase into the cache. * gpg-connect-agent:: Communicate with a running agent. * dirmngr-client:: How to use the Dirmngr client tool. * gpgparsemail:: Parse a mail message into an annotated format * gpgtar:: Encrypt or sign files into an archive. * gpg-check-pattern:: Check a passphrase on stdin against the patternfile. @end menu @c @c WATCHGNUPG @c @manpage watchgnupg.1 @node watchgnupg @section Read logs from a socket @ifset manverb .B watchgnupg \- Read and print logs from a socket @end ifset @mansect synopsis @ifset manverb .B watchgnupg .RB [ \-\-force ] .RB [ \-\-verbose ] .I socketname @end ifset @mansect description Most of the main utilities are able to write their log files to a Unix Domain socket if configured that way. @command{watchgnupg} is a simple listener for such a socket. It ameliorates the output with a time stamp and makes sure that long lines are not interspersed with log output from other utilities. This tool is not available for Windows. @noindent @command{watchgnupg} is commonly invoked as @example watchgnupg @end example which is a shorthand for @example watchgnupg --force $(gpgconf --list-dirs socketdir)/S.log @end example To watch GnuPG running with a different home directory, use @example watchgnupg --homedir DIR @end example @manpause @noindent This starts it on the current terminal for listening on the standard logging socket (this is commonly @file{/var/run/user/UID/gnupg/S.log} or if no such user directory hierarchy exists @file{~/.gnupg/S.log}). @mansect options @noindent @command{watchgnupg} understands these options: @table @gnupgtabopt @item --force @opindex force Delete an already existing socket file. This option is implicitly used if no socket name has been given on the command line. @item --homedir @var{DIR} If no socket name is given on the command line, pass @var{DIR} to gpgconf so that the socket for a GnuPG running with DIR has its home directory is used. Note that the environment variable @var{GNUPGHOME} is ignored by watchgnupg. @anchor{option watchgnupg --tcp} @item --tcp @var{n} Instead of reading from a local socket, listen for connects on TCP port @var{n}. A Unix domain socket can optionally also be given as a second source. This option does not use a default socket name. @item --time-only @opindex time-only Do not print the date part of the timestamp. @item --verbose @opindex verbose Enable extra informational output. @item --version @opindex version Print version of the program and exit. @item --help @opindex help Display a brief help page and exit. @end table @noindent @mansect examples @chapheading Examples @example $ watchgnupg --time-only @end example This waits for connections on the local socket (e.g., @file{/var/run/user/1234/gnupg/S.log}) and shows all log entries. To make this work the option @option{log-file} needs to be used with all modules which logs are to be shown. The suggested entry for the configuration files is: @example log-file socket:// @end example If the default socket as given above and returned by @code{"echo $(gpgconf --list-dirs socketdir)/S.log"} is not desired an arbitrary socket name can be specified, for example @file{socket:///home/foo/bar/mysocket}. For debugging purposes it is also possible to do remote logging. Take care if you use this feature because the information is send in the clear over the network. Use this syntax in the conf files: @example log-file tcp://192.168.1.1:4711 @end example You may use any port and not just 4711 as shown above; only IP addresses are supported (v4 and v6) and no host names. You need to start @command{watchgnupg} with the @option{tcp} option. Note that under Windows the registry entry @var{HKCU\Software\GNU\GnuPG:DefaultLogFile} can be used to change the default log output from @code{stderr} to whatever is given by that entry. However the only useful entry is a TCP name for remote debugging. @mansect see also @ifset isman @command{gpg}(1), @command{gpgsm}(1), @command{gpg-agent}(1), @command{scdaemon}(1) @end ifset @include see-also-note.texi @c @c GPGV @c @include gpgv.texi @c @c ADDGNUPGHOME @c @manpage addgnupghome.8 @node addgnupghome @section Create .gnupg home directories @ifset manverb .B addgnupghome \- Create .gnupg home directories @end ifset @mansect synopsis @ifset manverb .B addgnupghome .I account_1 .IR account_2 ... account_n @end ifset @mansect description If GnuPG is installed on a system with existing user accounts, it is sometimes required to populate the GnuPG home directory with existing files. Especially a @file{trustlist.txt} and a keybox with some initial certificates are often desired. This script helps to do this by copying all files from @file{/etc/skel/.gnupg} to the home directories of the accounts given on the command line. It takes care not to overwrite existing GnuPG home directories. @noindent @command{addgnupghome} is invoked by root as: @example addgnupghome account1 account2 ... accountn @end example @c @c GPGCONF @c @manpage gpgconf.1 @node gpgconf @section Modify .gnupg home directories @ifset manverb .B gpgconf \- Modify .gnupg home directories @end ifset @mansect synopsis @ifset manverb .B gpgconf .RI [ options ] .B \-\-list-components .br .B gpgconf .RI [ options ] .B \-\-list-options .I component .br .B gpgconf .RI [ options ] .B \-\-change-options .I component @end ifset @mansect description The @command{gpgconf} is a utility to automatically and reasonable safely query and modify configuration files in the @file{.gnupg} home directory. It is designed not to be invoked manually by the user, but automatically by graphical user interfaces (GUI).@footnote{Please note that currently no locking is done, so concurrent access should be avoided. There are some precautions to avoid corruption with concurrent usage, but results may be inconsistent and some changes may get lost. The stateless design makes it difficult to provide more guarantees.} @command{gpgconf} provides access to the configuration of one or more components of the GnuPG system. These components correspond more or less to the programs that exist in the GnuPG framework, like GPG, GPGSM, DirMngr, etc. But this is not a strict one-to-one relationship. Not all configuration options are available through @command{gpgconf}. @command{gpgconf} provides a generic and abstract method to access the most important configuration options that can feasibly be controlled via such a mechanism. @command{gpgconf} can be used to gather and change the options available in each component, and can also provide their default values. @command{gpgconf} will give detailed type information that can be used to restrict the user's input without making an attempt to commit the changes. @command{gpgconf} provides the backend of a configuration editor. The configuration editor would usually be a graphical user interface program that displays the current options, their default values, and allows the user to make changes to the options. These changes can then be made active with @command{gpgconf} again. Such a program that uses @command{gpgconf} in this way will be called GUI throughout this section. @menu * Invoking gpgconf:: List of all commands and options. * Format conventions:: Formatting conventions relevant for all commands. * Listing components:: List all gpgconf components. * Checking programs:: Check all programs known to gpgconf. * Listing options:: List all options of a component. * Changing options:: Changing options of a component. * Listing global options:: List all global options. * Querying versions:: Get and compare software versions. * Files used by gpgconf:: What files are used by gpgconf. @end menu @manpause @node Invoking gpgconf @subsection Invoking gpgconf @mansect commands One of the following commands must be given: @table @gnupgtabopt @item --list-components List all components. This is the default command used if none is specified. @item --check-programs List all available backend programs and test whether they are runnable. @item --list-options @var{component} List all options of the component @var{component}. @item --change-options @var{component} Change the options of the component @var{component}. @item --check-options @var{component} Check the options for the component @var{component}. @item --apply-profile @var{file} Apply the configuration settings listed in @var{file} to the configuration files. If @var{file} has no suffix and no slashes the command first tries to read a file with the suffix @code{.prf} from the data directory (@code{gpgconf --list-dirs datadir}) before it reads the file verbatim. A profile is divided into sections using the bracketed component name. Each section then lists the option which shall go into the respective configuration file. @item --apply-defaults Update all configuration files with values taken from the global configuration file (usually @file{/etc/gnupg/gpgconf.conf}). Note: This is a legacy mechanism. Please use global configuration files instead. @item --list-dirs [@var{names}] @itemx -L Lists the directories used by @command{gpgconf}. One directory is listed per line, and each line consists of a colon-separated list where the first field names the directory type (for example @code{sysconfdir}) and the second field contains the percent-escaped directory. Although they are not directories, the socket file names used by @command{gpg-agent} and @command{dirmngr} are printed as well. Note that the socket file names and the @code{homedir} lines are the default names and they may be overridden by command line switches. If @var{names} are given only the directories or file names specified by the list names are printed without any escaping. @item --list-config [@var{filename}] List the global configuration file in a colon separated format. If @var{filename} is given, check that file instead. @item --check-config [@var{filename}] Run a syntax check on the global configuration file. If @var{filename} is given, check that file instead. @item --query-swdb @var{package_name} [@var{version_string}] Returns the current version for @var{package_name} and if @var{version_string} is given also an indicator on whether an update is available. The actual file with the software version is automatically downloaded and checked by @command{dirmngr}. @command{dirmngr} uses a thresholds to avoid download the file too often and it does this by default only if it can be done via Tor. To force an update of that file this command can be used: @example gpg-connect-agent --dirmngr 'loadswdb --force' /bye @end example @item --reload [@var{component}] @itemx -R @opindex reload Reload all or the given component. This is basically the same as sending a SIGHUP to the component. Components which don't support reloading are ignored. Without @var{component} or by using "all" for @var{component} all components which are daemons are reloaded. @item --launch [@var{component}] @opindex launch If the @var{component} is not already running, start it. @command{component} must be a daemon. This is in general not required because the system starts these daemons as needed. However, external software making direct use of @command{gpg-agent} or @command{dirmngr} may use this command to ensure that they are started. Using "all" for @var{component} launches all components which are daemons. @item --kill [@var{component}] @itemx -K @opindex kill Kill the given component that runs as a daemon, including @command{gpg-agent}, @command{dirmngr}, and @command{scdaemon}. A @command{component} which does not run as a daemon will be ignored. Using "all" for @var{component} kills all components running as daemons. Note that as of now reload and kill have the same effect for @command{scdaemon}. @item --create-socketdir @opindex create-socketdir Create a directory for sockets below /run/user or /var/run/user. This is command is only required if a non default home directory is used and the /run based sockets shall be used. For the default home directory GnuPG creates a directory on the fly. @item --remove-socketdir @opindex remove-socketdir Remove a directory created with command @option{--create-socketdir}. @item --unlock @var{name} @itemx --lock @var{name} Remove a stale lock file hold for @file{file}. The file is expected in the current GnuPG home directory. This command is usually not required because GnuPG is able to detect and remove stale lock files. Before using the command make sure that the file protected by the lock file is actually not in use. The lock command may be used to lock an accidentally removed lock file. Note that the commands have no effect on Windows because the mere existence of a lock file does not mean that the lock is active. @end table @mansect options The following options may be used: @table @gnupgtabopt @item -o @var{file} @itemx --output @var{file} Write output to @var{file}. Default is to write to stdout. @item -v @itemx --verbose Outputs additional information while running. Specifically, this extends numerical field values by human-readable descriptions. @item -q @itemx --quiet @opindex quiet Try to be as quiet as possible. @include opt-homedir.texi @item --chuid @var{uid} @opindex chuid Change the current user to @var{uid} which may either be a number or a name. This can be used from the root account to get information on the GnuPG environment of the specified user or to start or kill daemons. If @var{uid} is not the current UID a standard PATH is set and the envvar GNUPGHOME is unset. To override the latter the option @option{--homedir} can be used. This option has currently no effect on Windows. @item -n @itemx --dry-run Do not actually change anything. This is currently only implemented for @code{--change-options} and can be used for testing purposes. @item -r @itemx --runtime Only used together with @code{--change-options}. If one of the modified options can be changed in a running daemon process, signal the running daemon to ask it to reparse its configuration file after changing. This means that the changes will take effect at run-time, as far as this is possible. Otherwise, they will take effect at the next start of the respective backend programs. @item --status-fd @var{n} @opindex status-fd Write special status strings to the file descriptor @var{n}. This program returns the status messages SUCCESS or FAILURE which are helpful when the caller uses a double fork approach and can't easily get the return code of the process. @manpause @end table @node Format conventions @subsection Format conventions Some lines in the output of @command{gpgconf} contain a list of colon-separated fields. The following conventions apply: @itemize @bullet @item The GUI program is required to strip off trailing newline and/or carriage return characters from the output. @item @command{gpgconf} will never leave out fields. If a certain version provides a certain field, this field will always be present in all @command{gpgconf} versions from that time on. @item Future versions of @command{gpgconf} might append fields to the list. New fields will always be separated from the previously last field by a colon separator. The GUI should be prepared to parse the last field it knows about up until a colon or end of line. @item Not all fields are defined under all conditions. You are required to ignore the content of undefined fields. @end itemize There are several standard types for the content of a field: @table @asis @item verbatim Some fields contain strings that are not escaped in any way. Such fields are described to be used @emph{verbatim}. These fields will never contain a colon character (for obvious reasons). No de-escaping or other formatting is required to use the field content. This is for easy parsing of the output, when it is known that the content can never contain any special characters. @item percent-escaped Some fields contain strings that are described to be @emph{percent-escaped}. Such strings need to be de-escaped before their content can be presented to the user. A percent-escaped string is de-escaped by replacing all occurrences of @code{%XY} by the byte that has the hexadecimal value @code{XY}. @code{X} and @code{Y} are from the set @code{0-9a-f}. @item localized Some fields contain strings that are described to be @emph{localized}. Such strings are translated to the active language and formatted in the active character set. @item @w{unsigned number} Some fields contain an @emph{unsigned number}. This number will always fit into a 32-bit unsigned integer variable. The number may be followed by a space, followed by a human readable description of that value (if the verbose option is used). You should ignore everything in the field that follows the number. @item @w{signed number} Some fields contain a @emph{signed number}. This number will always fit into a 32-bit signed integer variable. The number may be followed by a space, followed by a human readable description of that value (if the verbose option is used). You should ignore everything in the field that follows the number. @item @w{boolean value} Some fields contain a @emph{boolean value}. This is a number with either the value 0 or 1. The number may be followed by a space, followed by a human readable description of that value (if the verbose option is used). You should ignore everything in the field that follows the number; checking just the first character is sufficient in this case. @item option Some fields contain an @emph{option} argument. The format of an option argument depends on the type of the option and on some flags: @table @asis @item no argument The simplest case is that the option does not take an argument at all (@var{type} @code{0}). Then the option argument is an unsigned number that specifies how often the option occurs. If the @code{list} flag is not set, then the only valid number is @code{1}. Options that do not take an argument never have the @code{default} or @code{optional arg} flag set. @item number If the option takes a number argument (@var{alt-type} is @code{2} or @code{3}), and it can only occur once (@code{list} flag is not set), then the option argument is either empty (only allowed if the argument is optional), or it is a number. A number is a string that begins with an optional minus character, followed by one or more digits. The number must fit into an integer variable (unsigned or signed, depending on @var{alt-type}). @item number list If the option takes a number argument and it can occur more than once, then the option argument is either empty, or it is a comma-separated list of numbers as described above. @item string If the option takes a string argument (@var{alt-type} is 1), and it can only occur once (@code{list} flag is not set) then the option argument is either empty (only allowed if the argument is optional), or it starts with a double quote character (@code{"}) followed by a percent-escaped string that is the argument value. Note that there is only a leading double quote character, no trailing one. The double quote character is only needed to be able to differentiate between no value and the empty string as value. @item string list If the option takes a string argument and it can occur more than once, then the option argument is either empty, or it is a comma-separated list of string arguments as described above. @end table @end table The active language and character set are currently determined from the locale environment of the @command{gpgconf} program. @c FIXME: Document the active language and active character set. Allow @c to change it via the command line? @mansect usage @node Listing components @subsection Listing components The command @code{--list-components} will list all components that can be configured with @command{gpgconf}. Usually, one component will correspond to one GnuPG-related program and contain the options of that program's configuration file that can be modified using @command{gpgconf}. However, this is not necessarily the case. A component might also be a group of selected options from several programs, or contain entirely virtual options that have a special effect rather than changing exactly one option in one configuration file. A component is a set of configuration options that semantically belong together. Furthermore, several changes to a component can be made in an atomic way with a single operation. The GUI could for example provide a menu with one entry for each component, or a window with one tabulator sheet per component. The command @code{--list-components} lists all available components, one per line. The format of each line is: @code{@var{name}:@var{description}:@var{pgmname}:} @table @var @item name This field contains a name tag of the component. The name tag is used to specify the component in all communication with @command{gpgconf}. The name tag is to be used @emph{verbatim}. It is thus not in any escaped format. @item description The @emph{string} in this field contains a human-readable description of the component. It can be displayed to the user of the GUI for informational purposes. It is @emph{percent-escaped} and @emph{localized}. @item pgmname The @emph{string} in this field contains the absolute name of the program's file. It can be used to unambiguously invoke that program. It is @emph{percent-escaped}. @end table Example: @example $ gpgconf --list-components gpg:GPG for OpenPGP:/usr/local/bin/gpg2: gpg-agent:GPG Agent:/usr/local/bin/gpg-agent: scdaemon:Smartcard Daemon:/usr/local/bin/scdaemon: gpgsm:GPG for S/MIME:/usr/local/bin/gpgsm: dirmngr:Directory Manager:/usr/local/bin/dirmngr: @end example @node Checking programs @subsection Checking programs The command @code{--check-programs} is similar to @code{--list-components} but works on backend programs and not on components. It runs each program to test whether it is installed and runnable. This also includes a syntax check of all config file options of the program. The command @code{--check-programs} lists all available programs, one per line. The format of each line is: @code{@var{name}:@var{description}:@var{pgmname}:@var{avail}:@var{okay}:@var{cfgfile}:@var{line}:@var{error}:} @table @var @item name This field contains a name tag of the program which is identical to the name of the component. The name tag is to be used @emph{verbatim}. It is thus not in any escaped format. This field may be empty to indicate a continuation of error descriptions for the last name. The description and pgmname fields are then also empty. @item description The @emph{string} in this field contains a human-readable description of the component. It can be displayed to the user of the GUI for informational purposes. It is @emph{percent-escaped} and @emph{localized}. @item pgmname The @emph{string} in this field contains the absolute name of the program's file. It can be used to unambiguously invoke that program. It is @emph{percent-escaped}. @item avail The @emph{boolean value} in this field indicates whether the program is installed and runnable. @item okay The @emph{boolean value} in this field indicates whether the program's config file is syntactically okay. @item cfgfile If an error occurred in the configuration file (as indicated by a false value in the field @code{okay}), this field has the name of the failing configuration file. It is @emph{percent-escaped}. @item line If an error occurred in the configuration file, this field has the line number of the failing statement in the configuration file. It is an @emph{unsigned number}. @item error If an error occurred in the configuration file, this field has the error text of the failing statement in the configuration file. It is @emph{percent-escaped} and @emph{localized}. @end table @noindent In the following example the @command{dirmngr} is not runnable and the configuration file of @command{scdaemon} is not okay. @example $ gpgconf --check-programs gpg:GPG for OpenPGP:/usr/local/bin/gpg2:1:1: gpg-agent:GPG Agent:/usr/local/bin/gpg-agent:1:1: scdaemon:Smartcard Daemon:/usr/local/bin/scdaemon:1:0: gpgsm:GPG for S/MIME:/usr/local/bin/gpgsm:1:1: dirmngr:Directory Manager:/usr/local/bin/dirmngr:0:0: @end example @noindent The command @w{@code{--check-options @var{component}}} will verify the configuration file in the same manner as @code{--check-programs}, but only for the component @var{component}. @node Listing options @subsection Listing options Every component contains one or more options. Options may be gathered into option groups to allow the GUI to give visual hints to the user about which options are related. The command @code{@w{--list-options @var{component}}} lists all options (and the groups they belong to) in the component @var{component}, one per line. @var{component} must be the string in the field @var{name} in the output of the @code{--list-components} command. There is one line for each option and each group. First come all options that are not in any group. Then comes a line describing a group. Then come all options that belong into each group. Then comes the next group and so on. There does not need to be any group (and in this case the output will stop after the last non-grouped option). The format of each line is: @code{@var{name}:@var{flags}:@var{level}:@var{description}:@var{type}:@var{alt-type}:@var{argname}:@var{default}:@var{argdef}:@var{value}} @table @var @item name This field contains a name tag for the group or option. The name tag is used to specify the group or option in all communication with @command{gpgconf}. The name tag is to be used @emph{verbatim}. It is thus not in any escaped format. @item flags The flags field contains an @emph{unsigned number}. Its value is the OR-wise combination of the following flag values: @table @code @item group (1) If this flag is set, this is a line describing a group and not an option. @end table The following flag values are only defined for options (that is, if the @code{group} flag is not used). @table @code @item optional arg (2) If this flag is set, the argument is optional. This is never set for @var{type} @code{0} (none) options. @item list (4) If this flag is set, the option can be given multiple times. @item runtime (8) If this flag is set, the option can be changed at runtime. @item default (16) If this flag is set, a default value is available. @item default desc (32) If this flag is set, a (runtime) default is available. This and the @code{default} flag are mutually exclusive. @item no arg desc (64) If this flag is set, and the @code{optional arg} flag is set, then the option has a special meaning if no argument is given. @item no change (128) If this flag is set, @command{gpgconf} ignores requests to change the value. GUI frontends should grey out this option. Note, that manual changes of the configuration files are still possible. @end table @item level This field is defined for options and for groups. It contains an @emph{unsigned number} that specifies the expert level under which this group or option should be displayed. The following expert levels are defined for options (they have analogous meaning for groups): @table @code @item basic (0) This option should always be offered to the user. @item advanced (1) This option may be offered to advanced users. @item expert (2) This option should only be offered to expert users. @item invisible (3) This option should normally never be displayed, not even to expert users. @item internal (4) This option is for internal use only. Ignore it. @end table The level of a group will always be the lowest level of all options it contains. @item description This field is defined for options and groups. The @emph{string} in this field contains a human-readable description of the option or group. It can be displayed to the user of the GUI for informational purposes. It is @emph{percent-escaped} and @emph{localized}. @item type This field is only defined for options. It contains an @emph{unsigned number} that specifies the type of the option's argument, if any. The following types are defined: Basic types: @table @code @item none (0) No argument allowed. @item string (1) An @emph{unformatted string}. @item int32 (2) A @emph{signed number}. @item uint32 (3) An @emph{unsigned number}. @end table Complex types: @table @code @item pathname (32) A @emph{string} that describes the pathname of a file. The file does not necessarily need to exist. @item ldap server (33) A @emph{string} that describes an LDAP server in the format: @code{@var{hostname}:@var{port}:@var{username}:@var{password}:@var{base_dn}} @item key fingerprint (34) A @emph{string} with a 40 digit fingerprint specifying a certificate. @item pub key (35) A @emph{string} that describes a certificate by user ID, key ID or fingerprint. @item sec key (36) A @emph{string} that describes a certificate with a key by user ID, key ID or fingerprint. @item alias list (37) A @emph{string} that describes an alias list, like the one used with gpg's group option. The list consists of a key, an equal sign and space separated values. @end table More types will be added in the future. Please see the @var{alt-type} field for information on how to cope with unknown types. @item alt-type This field is identical to @var{type}, except that only the types @code{0} to @code{31} are allowed. The GUI is expected to present the user the option in the format specified by @var{type}. But if the argument type @var{type} is not supported by the GUI, it can still display the option in the more generic basic type @var{alt-type}. The GUI must support all the defined basic types to be able to display all options. More basic types may be added in future versions. If the GUI encounters a basic type it doesn't support, it should report an error and abort the operation. @item argname This field is only defined for options with an argument type @var{type} that is not @code{0}. In this case it may contain a @emph{percent-escaped} and @emph{localized string} that gives a short name for the argument. The field may also be empty, though, in which case a short name is not known. @item default This field is defined only for options for which the @code{default} or @code{default desc} flag is set. If the @code{default} flag is set, its format is that of an @emph{option argument} (@pxref{Format conventions}, for details). If the default value is empty, then no default is known. Otherwise, the value specifies the default value for this option. If the @code{default desc} flag is set, the field is either empty or contains a description of the effect if the option is not given. @item argdef This field is defined only for options for which the @code{optional arg} flag is set. If the @code{no arg desc} flag is not set, its format is that of an @emph{option argument} (@pxref{Format conventions}, for details). If the default value is empty, then no default is known. Otherwise, the value specifies the default argument for this option. If the @code{no arg desc} flag is set, the field is either empty or contains a description of the effect of this option if no argument is given. @item value This field is defined only for options. Its format is that of an @emph{option argument}. If it is empty, then the option is not explicitly set in the current configuration, and the default applies (if any). Otherwise, it contains the current value of the option. Note that this field is also meaningful if the option itself does not take a real argument (in this case, it contains the number of times the option appears). @end table @node Changing options @subsection Changing options The command @w{@code{--change-options @var{component}}} will attempt to change the options of the component @var{component} to the specified values. @var{component} must be the string in the field @var{name} in the output of the @code{--list-components} command. You have to provide the options that shall be changed in the following format on standard input: @code{@var{name}:@var{flags}:@var{new-value}} @table @var @item name This is the name of the option to change. @var{name} must be the string in the field @var{name} in the output of the @code{--list-options} command. @item flags The flags field contains an @emph{unsigned number}. Its value is the OR-wise combination of the following flag values: @table @code @item default (16) If this flag is set, the option is deleted and the default value is used instead (if applicable). @end table @item new-value The new value for the option. This field is only defined if the @code{default} flag is not set. The format is that of an @emph{option argument}. If it is empty (or the field is omitted), the default argument is used (only allowed if the argument is optional for this option). Otherwise, the option will be set to the specified value. @end table @noindent The output of the command is the same as that of @code{--check-options} for the modified configuration file. Examples: To set the force option, which is of basic type @code{none (0)}: @example $ echo 'force:0:1' | gpgconf --change-options dirmngr @end example To delete the force option: @example $ echo 'force:16:' | gpgconf --change-options dirmngr @end example The @code{--runtime} option can influence when the changes take effect. @node Listing global options @subsection Listing global options Some legacy applications look at the global configuration file for the gpgconf tool itself; this is the file @file{gpgconf.conf}. Modern applications should not use it but use per component global configuration files which are more flexible than the @file{gpgconf.conf}. Using both files is not suggested. The colon separated listing format is record oriented and uses the first field to identify the record type: @table @code @item k This describes a key record to start the definition of a new ruleset for a user/group. The format of a key record is: @code{k:@var{user}:@var{group}:} @table @var @item user This is the user field of the key. It is percent escaped. See the definition of the gpgconf.conf format for details. @item group This is the group field of the key. It is percent escaped. @end table @item r This describes a rule record. All rule records up to the next key record make up a rule set for that key. The format of a rule record is: @code{r:::@var{component}:@var{option}:@var{flag}:@var{value}:} @table @var @item component This is the component part of a rule. It is a plain string. @item option This is the option part of a rule. It is a plain string. @item flag This is the flags part of a rule. There may be only one flag per rule but by using the same component and option, several flags may be assigned to an option. It is a plain string. @item value This is the optional value for the option. It is a percent escaped string with a single quotation mark to indicate a string. The quotation mark is only required to distinguish between no value specified and an empty string. @end table @end table @noindent Unknown record types should be ignored. Note that there is intentionally no feature to change the global option file through @command{gpgconf}. @node Querying versions @subsection Get and compare software versions. The GnuPG Project operates a server to query the current versions of software packages related to GnuPG. @command{gpgconf} can be used to access this online database. To allow for offline operations, this feature works by having @command{dirmngr} download a file from @code{https://versions.gnupg.org}, checking the signature of that file and storing the file in the GnuPG home directory. If @command{gpgconf} is used and @command{dirmngr} is running, it may ask @command{dirmngr} to refresh that file before itself uses the file. The command @option{--query-swdb} returns information for the given package in a colon delimited format: @table @var @item name This is the name of the package as requested. Note that "gnupg" is a special name which is replaced by the actual package implementing this version of GnuPG. For this name it is also not required to specify a version because @command{gpgconf} takes its own version in this case. @item iversion The currently installed version or an empty string. The value is taken from the command line argument but may be provided by gpg if not given. @item status The status of the software package according to this table: @table @code @item - No information available. This is either because no current version has been specified or due to an error. @item ? The given name is not known in the online database. @item u An update of the software is available. @item c The installed version of the software is current. @item n The installed version is already newer than the released version. @end table @item urgency If the value (the empty string should be considered as zero) is greater than zero an important update is available. @item error This returns an @command{gpg-error} error code to distinguish between various failure modes. @item filedate This gives the date of the file with the version numbers in standard ISO format (@code{yyyymmddThhmmss}). The date has been extracted by @command{dirmngr} from the signature of the file. @item verified This gives the date in ISO format the file was downloaded. This value can be used to evaluate the freshness of the information. @item version This returns the version string for the requested software from the file. @item reldate This returns the release date in ISO format. @item size This returns the size of the package as decimal number of bytes. @item hash This returns a hexified SHA-2 hash of the package. @end table @noindent More fields may be added in future to the output. @mansect files @node Files used by gpgconf @subsection Files used by gpgconf @table @file @item gpgconf.ctl @cindex gpgconf.ctl Under Unix @file{gpgconf.ctl} may be used to change some of the compiled in directories where the GnuPG components are expected. This file is expected in the same directory as @file{gpgconf}. The physical installation directories are evaluated and no symlinks. Blank lines and lines starting with pound sign are ignored in the file. The keywords must be followed by optional white space, an equal sign, optional white space, and the value. Environment variables are substituted in standard shell manner, the final value must start with a slash, trailing slashes are stripped. Valid keywords are @code{rootdir}, @code{sysconfdir}, @code{socketdir}, and @code{.enable}. No errors are printed for unknown keywords. The @code{.enable} keyword is special: if the keyword is used and its value evaluates to true the entire file is ignored. Under Windows this file is used to install GnuPG as a portable application. An empty file named @file{gpgconf.ctl} is expected in the same directory as the tool @file{gpgconf.exe} or the file must have a keyword @code{portable} with the value true. The root of the installation is then that directory; or, if @file{gpgconf.exe} has been installed directly below a directory named @file{bin}, its parent directory. You also need to make sure that the following directories exist and are writable: @file{ROOT/home} for the GnuPG home and @file{ROOT@value{LOCALCACHEDIR}} for internal cache files. + On both platforms the keyword @code{gnupg} can be used to change the + standard home directory. For example a value of "gnupg-vsd" will + change the default home directory on unix from @file{~/.gnupg} to + @file{~/.gnupg-vsd}. The socket directory is changed accordingly + unless the @code{socketdir} keyword has been used. On Windows the + Registry keys are modified as well. + @item /etc/gnupg/gpgconf.conf @cindex gpgconf.conf If this file exists, it is processed as a global configuration file. This is a legacy mechanism which should not be used together with the modern global per component configuration files. A commented example can be found in the @file{examples} directory of the distribution. @item @var{GNUPGHOME}/swdb.lst @cindex swdb.lst A file with current software versions. @command{dirmngr} creates this file on demand from an online resource. @end table @mansect see also @ifset isman @command{gpg}(1), @command{gpgsm}(1), @command{gpg-agent}(1), @command{scdaemon}(1), @command{dirmngr}(1) @end ifset @include see-also-note.texi @c @c APPLYGNUPGDEFAULTS @c @manpage applygnupgdefaults.8 @node applygnupgdefaults @section Run gpgconf for all users @ifset manverb .B applygnupgdefaults \- Run gpgconf --apply-defaults for all users. @end ifset @mansect synopsis @ifset manverb .B applygnupgdefaults @end ifset @mansect description This is a legacy script. Modern application should use the per component global configuration files under @file{/etc/gnupg/}. This script is a wrapper around @command{gpgconf} to run it with the command @code{--apply-defaults} for all real users with an existing GnuPG home directory. Admins might want to use this script to update he GnuPG configuration files for all users after @file{/etc/gnupg/gpgconf.conf} has been changed. This allows enforcing certain policies for all users. Note, that this is not a bulletproof way to force a user to use certain options. A user may always directly edit the configuration files and bypass gpgconf. @noindent @command{applygnupgdefaults} is invoked by root as: @example applygnupgdefaults @end example @c @c GPG-PRESET-PASSPHRASE @c @node gpg-preset-passphrase @section Put a passphrase into the cache @manpage gpg-preset-passphrase.1 @ifset manverb .B gpg-preset-passphrase \- Put a passphrase into gpg-agent's cache @end ifset @mansect synopsis @ifset manverb .B gpg-preset-passphrase .RI [ options ] .RI [ command ] .I cache-id @end ifset @mansect description The @command{gpg-preset-passphrase} is a utility to seed the internal cache of a running @command{gpg-agent} with passphrases. It is mainly useful for unattended machines, where the usual @command{pinentry} tool may not be used and the passphrases for the to be used keys are given at machine startup. This program works with GnuPG 2 and later. GnuPG 1.x is not supported. Passphrases set with this utility don't expire unless the @option{--forget} option is used to explicitly clear them from the cache --- or @command{gpg-agent} is either restarted or reloaded (by sending a SIGHUP to it). Note that the maximum cache time as set with @option{--max-cache-ttl} is still honored. It is necessary to allow this passphrase presetting by starting @command{gpg-agent} with the @option{--allow-preset-passphrase}. @menu * Invoking gpg-preset-passphrase:: List of all commands and options. @end menu @manpause @node Invoking gpg-preset-passphrase @subsection List of all commands and options @mancont @noindent @command{gpg-preset-passphrase} is invoked this way: @example gpg-preset-passphrase [options] [command] @var{cacheid} @end example @var{cacheid} is either a 40 character keygrip of hexadecimal characters identifying the key for which the passphrase should be set or cleared. The keygrip is listed along with the key when running the command: @code{gpgsm --with-keygrip --list-secret-keys}. Alternatively an arbitrary string may be used to identify a passphrase; it is suggested that such a string is prefixed with the name of the application (e.g @code{foo:12346}). Scripts should always use the option @option{--with-colons}, which provides the keygrip in a "grp" line (cf.@: @file{doc/DETAILS})/ @noindent One of the following command options must be given: @table @gnupgtabopt @item --preset @opindex preset Preset a passphrase. This is what you usually will use. @command{gpg-preset-passphrase} will then read the passphrase from @code{stdin}. @item --forget @opindex forget Flush the passphrase for the given cache ID from the cache. @end table @noindent The following additional options may be used: @table @gnupgtabopt @item -v @itemx --verbose @opindex verbose Output additional information while running. @item -P @var{string} @itemx --passphrase @var{string} @opindex passphrase Instead of reading the passphrase from @code{stdin}, use the supplied @var{string} as passphrase. Note that this makes the passphrase visible for other users. @end table @mansect see also @ifset isman @command{gpg}(1), @command{gpgsm}(1), @command{gpg-agent}(1), @command{scdaemon}(1) @end ifset @include see-also-note.texi @c @c GPG-CONNECT-AGENT @c @node gpg-connect-agent @section Communicate with a running agent @manpage gpg-connect-agent.1 @ifset manverb .B gpg-connect-agent \- Communicate with a running agent @end ifset @mansect synopsis @ifset manverb .B gpg-connect-agent .RI [ options ] [commands] @end ifset @mansect description The @command{gpg-connect-agent} is a utility to communicate with a running @command{gpg-agent}. It is useful to check out the commands @command{gpg-agent} provides using the Assuan interface. It might also be useful for scripting simple applications. Input is expected at stdin and output gets printed to stdout. It is very similar to running @command{gpg-agent} in server mode; but here we connect to a running instance. @menu * Invoking gpg-connect-agent:: List of all options. * Controlling gpg-connect-agent:: Control commands. @end menu @manpause @node Invoking gpg-connect-agent @subsection List of all options @noindent @command{gpg-connect-agent} is invoked this way: @example gpg-connect-agent [options] [commands] @end example @mancont @noindent The following options may be used: @table @gnupgtabopt @item --dirmngr @opindex dirmngr Connect to a running directory manager (keyserver client) instead of to the gpg-agent. If a dirmngr is not running, start it. @item --keyboxd @opindex keyboxd Connect to a running keybox daemon instead of to the gpg-agent. If a keyboxd is not running, start it. @item -S @itemx --raw-socket @var{name} @opindex raw-socket Connect to socket @var{name} assuming this is an Assuan style server. Do not run any special initializations or environment checks. This may be used to directly connect to any Assuan style socket server. @item -E @itemx --exec @opindex exec Take the rest of the command line as a program and it's arguments and execute it as an Assuan server. Here is how you would run @command{gpgsm}: @smallexample gpg-connect-agent --exec gpgsm --server @end smallexample Note that you may not use options on the command line in this case. @item -v @itemx --verbose @opindex verbose Output additional information while running. @item -q @item --quiet @opindex q @opindex quiet Try to be as quiet as possible. @include opt-homedir.texi @item --chuid @var{uid} @opindex chuid Change the current user to @var{uid} which may either be a number or a name. This can be used from the root account to run gpg-connect-agent for another user. If @var{uid} is not the current UID a standard PATH is set and the envvar GNUPGHOME is unset. To override the latter the option @option{--homedir} can be used. This option has only an effect when used on the command line. This option has currently no effect at all on Windows. @item --no-ext-connect @opindex no-ext-connect When using @option{-S} or @option{--exec}, @command{gpg-connect-agent} connects to the Assuan server in extended mode to allow descriptor passing. This option makes it use the old mode. @item --no-autostart @opindex no-autostart Do not start the gpg-agent or the dirmngr if it has not yet been started. @item --no-history @opindex --no-history In interactive mode the command line history is usually saved and restored to and from a file below the GnuPG home directory. This option inhibits the use of that file. @item --agent-program @var{file} @opindex agent-program Specify the agent program to be started if none is running. The default value is determined by running @command{gpgconf} with the option @option{--list-dirs}. Note that the pipe symbol (@code{|}) is used for a regression test suite hack and may thus not be used in the file name. @item --dirmngr-program @var{file} @opindex dirmngr-program Specify the directory manager (keyserver client) program to be started if none is running. This has only an effect if used together with the option @option{--dirmngr}. @item --keyboxd-program @var{file} @opindex keyboxd-program Specify the keybox daemon program to be started if none is running. This has only an effect if used together with the option @option{--keyboxd}. @item -r @var{file} @itemx --run @var{file} @opindex run Run the commands from @var{file} at startup and then continue with the regular input method. Note, that commands given on the command line are executed after this file. @item -s @itemx --subst @opindex subst Run the command @code{/subst} at startup. @item --hex @opindex hex Print data lines in a hex format and the ASCII representation of non-control characters. @item --decode @opindex decode Decode data lines. That is to remove percent escapes but make sure that a new line always starts with a D and a space. @item -u @itemx --unbuffered @opindex unbuffered Set stdin and stdout into unbuffered I/O mode. This this sometimes useful for scripting. @end table @mansect control commands @node Controlling gpg-connect-agent @subsection Control commands While reading Assuan commands, gpg-agent also allows a few special commands to control its operation. These control commands all start with a slash (@code{/}). @table @code @item /echo @var{args} Just print @var{args}. @item /let @var{name} @var{value} Set the variable @var{name} to @var{value}. Variables are only substituted on the input if the @command{/subst} has been used. Variables are referenced by prefixing the name with a dollar sign and optionally include the name in curly braces. The rules for a valid name are identically to those of the standard bourne shell. This is not yet enforced but may be in the future. When used with curly braces no leading or trailing white space is allowed. If a variable is not found, it is searched in the environment and if found copied to the table of variables. Variable functions are available: The name of the function must be followed by at least one space and the at least one argument. The following functions are available: @table @code @item get Return a value described by the argument. Available arguments are: @table @code @item cwd The current working directory. @item homedir The gnupg homedir. @item sysconfdir GnuPG's system configuration directory. @item bindir GnuPG's binary directory. @item libdir GnuPG's library directory. @item libexecdir GnuPG's library directory for executable files. @item datadir GnuPG's data directory. @item serverpid The PID of the current server. Command @command{/serverpid} must have been given to return a useful value. @end table @item unescape @var{args} Remove C-style escapes from @var{args}. Note that @code{\0} and @code{\x00} terminate the returned string implicitly. The string to be converted are the entire arguments right behind the delimiting space of the function name. @item unpercent @var{args} @itemx unpercent+ @var{args} Remove percent style escaping from @var{args}. Note that @code{%00} terminates the string implicitly. The string to be converted are the entire arguments right behind the delimiting space of the function name. @code{unpercent+} also maps plus signs to a spaces. @item percent @var{args} @itemx percent+ @var{args} Escape the @var{args} using percent style escaping. Tabs, formfeeds, linefeeds, carriage returns and colons are escaped. @code{percent+} also maps spaces to plus signs. @item errcode @var{arg} @itemx errsource @var{arg} @itemx errstring @var{arg} Assume @var{arg} is an integer and evaluate it using @code{strtol}. Return the gpg-error error code, error source or a formatted string with the error code and error source. @item + @itemx - @itemx * @itemx / @itemx % Evaluate all arguments as long integers using @code{strtol} and apply this operator. A division by zero yields an empty string. @item ! @itemx | @itemx & Evaluate all arguments as long integers using @code{strtol} and apply the logical operators NOT, OR or AND. The NOT operator works on the last argument only. @end table @item /definq @var{name} @var{var} Use content of the variable @var{var} for inquiries with @var{name}. @var{name} may be an asterisk (@code{*}) to match any inquiry. @item /definqfile @var{name} @var{file} Use content of @var{file} for inquiries with @var{name}. @var{name} may be an asterisk (@code{*}) to match any inquiry. @item /definqprog @var{name} @var{prog} Run @var{prog} for inquiries matching @var{name} and pass the entire line to it as command line arguments. @item /datafile @var{name} Write all data lines from the server to the file @var{name}. The file is opened for writing and created if it does not exists. An existing file is first truncated to 0. The data written to the file fully decoded. Using a single dash for @var{name} writes to stdout. The file is kept open until a new file is set using this command or this command is used without an argument. @item /showdef Print all definitions @item /cleardef Delete all definitions @item /sendfd @var{file} @var{mode} Open @var{file} in @var{mode} (which needs to be a valid @code{fopen} mode string) and send the file descriptor to the server. This is usually followed by a command like @code{INPUT FD} to set the input source for other commands. @item /recvfd Not yet implemented. @item /open @var{var} @var{file} [@var{mode}] Open @var{file} and assign the file descriptor to @var{var}. Warning: This command is experimental and might change in future versions. @item /close @var{fd} Close the file descriptor @var{fd}. Warning: This command is experimental and might change in future versions. @item /showopen Show a list of open files. @item /serverpid Send the Assuan command @command{GETINFO pid} to the server and store the returned PID for internal purposes. @item /sleep Sleep for a second. @item /hex @itemx /nohex Same as the command line option @option{--hex}. @item /decode @itemx /nodecode Same as the command line option @option{--decode}. @item /subst @itemx /nosubst Enable and disable variable substitution. It defaults to disabled unless the command line option @option{--subst} has been used. If /subst as been enabled once, leading whitespace is removed from input lines which makes scripts easier to read. @item /while @var{condition} @itemx /end These commands provide a way for executing loops. All lines between the @code{while} and the corresponding @code{end} are executed as long as the evaluation of @var{condition} yields a non-zero value or is the string @code{true} or @code{yes}. The evaluation is done by passing @var{condition} to the @code{strtol} function. Example: @smallexample /subst /let i 3 /while $i /echo loop counter is $i /let i $@{- $i 1@} /end @end smallexample @item /if @var{condition} @itemx /end These commands provide a way for conditional execution. All lines between the @code{if} and the corresponding @code{end} are executed only if the evaluation of @var{condition} yields a non-zero value or is the string @code{true} or @code{yes}. The evaluation is done by passing @var{condition} to the @code{strtol} function. @item /run @var{file} Run commands from @var{file}. @item /history --clear Clear the command history. @item /bye Terminate the connection and the program. @item /help Print a list of available control commands. @end table @ifset isman @mansect see also @command{gpg-agent}(1), @command{scdaemon}(1) @include see-also-note.texi @end ifset @c @c DIRMNGR-CLIENT @c @node dirmngr-client @section The Dirmngr Client Tool @manpage dirmngr-client.1 @ifset manverb .B dirmngr-client \- Tool to access the Dirmngr services @end ifset @mansect synopsis @ifset manverb .B dirmngr-client .RI [ options ] .RI [ certfile | pattern ] @end ifset @mansect description The @command{dirmngr-client} is a simple tool to contact a running dirmngr and test whether a certificate has been revoked --- either by being listed in the corresponding CRL or by running the OCSP protocol. If no dirmngr is running, a new instances will be started but this is in general not a good idea due to the huge performance overhead. @noindent The usual way to run this tool is either: @example dirmngr-client @var{acert} @end example @noindent or @example dirmngr-client <@var{acert} @end example Where @var{acert} is one DER encoded (binary) X.509 certificates to be tested. @ifclear isman The return value of this command is @end ifclear @mansect return value @ifset isman @command{dirmngr-client} returns these values: @end ifset @table @code @item 0 The certificate under question is valid; i.e., there is a valid CRL available and it is not listed there or the OCSP request returned that that certificate is valid. @item 1 The certificate has been revoked @item 2 (and other values) There was a problem checking the revocation state of the certificate. A message to stderr has given more detailed information. Most likely this is due to a missing or expired CRL or due to a network problem. @end table @mansect options @noindent @command{dirmngr-client} may be called with the following options: @table @gnupgtabopt @item --version @opindex version Print the program version and licensing information. Note that you cannot abbreviate this command. @item --help, -h @opindex help Print a usage message summarizing the most useful command-line options. Note that you cannot abbreviate this command. @item --quiet, -q @opindex quiet Make the output extra brief by suppressing any informational messages. @item -v @item --verbose @opindex v @opindex verbose Outputs additional information while running. You can increase the verbosity by giving several verbose commands to @sc{dirmngr}, such as @samp{-vv}. @item --pem @opindex pem Assume that the given certificate is in PEM (armored) format. @item --ocsp @opindex ocsp Do the check using the OCSP protocol and ignore any CRLs. @item --force-default-responder @opindex force-default-responder When checking using the OCSP protocol, force the use of the default OCSP responder. That is not to use the Reponder as given by the certificate. @item --ping @opindex ping Check whether the dirmngr daemon is up and running. @item --cache-cert @opindex cache-cert Put the given certificate into the cache of a running dirmngr. This is mainly useful for debugging. @item --validate @opindex validate Validate the given certificate using dirmngr's internal validation code. This is mainly useful for debugging. @item --load-crl @opindex load-crl This command expects a list of filenames with DER encoded CRL files. With the option @option{--url} URLs are expected in place of filenames and they are loaded directly from the given location. All CRLs will be validated and then loaded into dirmngr's cache. @item --lookup @opindex lookup Take the remaining arguments and run a lookup command on each of them. The results are Base-64 encoded outputs (without header lines). This may be used to retrieve certificates from a server. However the output format is not very well suited if more than one certificate is returned. @item --url @itemx -u @opindex url Modify the @command{lookup} and @command{load-crl} commands to take an URL. @item --local @itemx -l @opindex url Let the @command{lookup} command only search the local cache. @item --squid-mode @opindex squid-mode Run @sc{dirmngr-client} in a mode suitable as a helper program for Squid's @option{external_acl_type} option. @end table @ifset isman @mansect see also @command{dirmngr}(8), @command{gpgsm}(1) @include see-also-note.texi @end ifset @c @c GPGPARSEMAIL @c @node gpgparsemail @section Parse a mail message into an annotated format @manpage gpgparsemail.1 @ifset manverb .B gpgparsemail \- Parse a mail message into an annotated format @end ifset @mansect synopsis @ifset manverb .B gpgparsemail .RI [ options ] .RI [ file ] @end ifset @mansect description The @command{gpgparsemail} is a utility currently only useful for debugging. Run it with @code{--help} for usage information. @c @c GPGTAR @c @manpage gpgtar.1 @node gpgtar @section Encrypt or sign files into an archive @ifset manverb .B gpgtar \- Encrypt or sign files into an archive @end ifset @mansect synopsis @ifset manverb .B gpgtar .RI [ options ] .I filename1 .I [ filename2, ... ] .I directory1 .I [ directory2, ... ] @end ifset @mansect description @command{gpgtar} encrypts or signs files into an archive. It is an gpg-ized tar using the same format as used by PGP's PGP Zip. @manpause @noindent @command{gpgtar} is invoked this way: @example gpgtar [options] @var{filename1} [@var{filename2}, ...] @var{directory} [@var{directory2}, ...] @end example @mansect options @noindent @command{gpgtar} understands these options: @table @gnupgtabopt @item --create @opindex create Put given files and directories into a vanilla ``ustar'' archive. @item --extract @opindex extract Extract all files from a vanilla ``ustar'' archive. If no file name is given (or it is "-") the archive is taken from stdin. @item --encrypt @itemx -e @opindex encrypt Encrypt given files and directories into an archive. This option may be combined with option @option{--symmetric} for an archive that may be decrypted via a secret key or a passphrase. @item --decrypt @itemx -d @opindex decrypt Extract all files from an encrypted archive. If no file name is given (or it is "-") the archive is taken from stdin. @item --sign @itemx -s Make a signed archive from the given files and directories. This can be combined with option @option{--encrypt} to create a signed and then encrypted archive. @item --list-archive @itemx -t @opindex list-archive List the contents of the specified archive. If no file name is given (or it is "-") the archive is taken from stdin. @item --symmetric @itemx -c Encrypt with a symmetric cipher using a passphrase. The default symmetric cipher used is @value{GPGSYMENCALGO}, but may be chosen with the @option{--cipher-algo} option to @command{gpg}. @item --recipient @var{user} @itemx -r @var{user} @opindex recipient Encrypt for user id @var{user}. For details see @command{gpg}. @item --local-user @var{user} @itemx -u @var{user} @opindex local-user Use @var{user} as the key to sign with. For details see @command{gpg}. @item --output @var{file} @itemx -o @var{file} @opindex output Write the archive to the specified file @var{file}. @item --verbose @itemx -v @opindex verbose Enable extra informational output. @item --quiet @itemx -q @opindex quiet Try to be as quiet as possible. @item --skip-crypto @opindex skip-crypto Skip all crypto operations and create or extract vanilla ``ustar'' archives. @item --dry-run @opindex dry-run Do not actually output the extracted files. @item --directory @var{dir} @itemx -C @var{dir} @opindex directory Extract the files into the directory @var{dir}. The default is to take the directory name from the input filename. If no input filename is known a directory named @file{GPGARCH} is used. For tarball creation, switch to directory @var{dir} before performing any operations. @item --files-from @var{file} @itemx -T @var{file} Take the file names to work from the file @var{file}; one file per line. @item --null @opindex null Modify option @option{--files-from} to use a binary nul instead of a linefeed to separate file names. @item --utf8-strings @opindex utf8-strings Assume that the file names read by @option{--files-from} are UTF-8 encoded. This option has an effect only on Windows where the active code page is otherwise assumed. @item --openpgp @opindex openpgp This option has no effect because OpenPGP encryption and signing is the default. @item --cms @opindex cms This option is reserved and shall not be used. It will eventually be used to encrypt or sign using the CMS protocol; but that is not yet implemented. @item --batch @opindex batch Use batch mode. Never ask but use the default action. This option is passed directly to @command{gpg}. @item --yes @opindex yes Assume "yes" on most questions. Often used together with @option{--batch} to overwrite existing files. This option is passed directly to @command{gpg}. @item --no @opindex no Assume "no" on most questions. This option is passed directly to @command{gpg}. @item --require-compliance @opindex require-compliance This option is passed directly to @command{gpg}. @item --status-fd @var{n} @opindex status-fd Write special status strings to the file descriptor @var{n}. See the file DETAILS in the documentation for a listing of them. @item --with-log @opindex with-log When extracting an encrypted tarball also write a log file with the gpg output to a file named after the extraction directory with the suffix ".log". @item --set-filename @var{file} @opindex set-filename Use the last component of @var{file} as the output directory. The default is to take the directory name from the input filename. If no input filename is known a directory named @file{GPGARCH} is used. This option is deprecated in favor of option @option{--directory}. @item --no-compress @opindex no-compress This option tells gpg to disable compression (i.e., using option -z0). It is useful for archiving only large files which are are already compressed (e.g., a set of videos). @item --gpg @var{gpgcmd} @opindex gpg Use the specified command @var{gpgcmd} instead of @command{gpg}. @item --gpg-args @var{args} @opindex gpg-args Pass the specified extra options to @command{gpg}. @item --tar-args @var{args} @opindex tar-args Assume @var{args} are standard options of the command @command{tar} and parse them. The only supported tar options are @option{--directory}, @option{--files-from}, and @option{--null}. This is an obsolete options because those supported tar options can also be given directly. @item --tar @var{command} @opindex tar This is a dummy option for backward compatibility. @c ... to the gpg-zip script we provided in the past @item --version @opindex version Print version of the program and exit. @item --help @opindex help Display a brief help page and exit. @end table @mansect diagnostics @noindent The program returns 0 if everything was fine, 1 otherwise. @mansect examples @ifclear isman @noindent Some examples: @end ifclear @noindent Encrypt the contents of directory @file{mydocs} for user Bob to file @file{test1}: @example gpgtar --encrypt --output test1 -r Bob mydocs @end example @noindent List the contents of archive @file{test1}: @example gpgtar --list-archive test1 @end example @mansect see also @ifset isman @command{gpg}(1), @command{tar}(1), @end ifset @include see-also-note.texi @c @c GPG-CHECK-PATTERN @c @manpage gpg-check-pattern.1 @node gpg-check-pattern @section Check a passphrase on stdin against the patternfile @ifset manverb .B gpg-check-pattern \- Check a passphrase on stdin against the patternfile @end ifset @mansect synopsis @ifset manverb .B gpg\-check\-pattern .RI [ options ] .I patternfile @end ifset @mansect description @command{gpg-check-pattern} checks a passphrase given on stdin against a specified pattern file. The pattern file is line based with comment lines beginning on the @emph{first} position with a @code{#}. Empty lines and lines with only white spaces are ignored. The actual pattern lines may either be verbatim string pattern and match as they are (trailing spaces are ignored) or extended regular expressions indicated by a @code{/} or @code{!/} in the first column and terminated by another @code{/} or end of line. If a regular expression starts with @code{!/} the match result is reversed. By default all comparisons are case insensitive. Tag lines may be used to further control the operation of this tool. The currently defined tags are: @table @code @item [icase] Switch to case insensitive comparison for all further patterns. This is the default. @item [case] Switch to case sensitive comparison for all further patterns. @item [reject] Switch to reject mode. This is the default mode. @item [accept] Switch to accept mode. @end table In the future more tags may be introduced and thus it is advisable not to start a plain pattern string with an open bracket. The tags must be given verbatim on the line with no spaces to the left or any non white space characters to the right. In reject mode the program exits on the first match with an exit code of 1 (failure). If at the end of the pattern list the reject mode is still active the program exits with code 0 (success). In accept mode blocks of patterns are used. A block starts at the next pattern after an "accept" tag and ends with the last pattern before the next "accept" or "reject" tag or at the end of the pattern list. If all patterns in a block match the program exits with an exit code of 0 (success). If any pattern in a block do not match the next pattern block is evaluated. If at the end of the pattern list the accept mode is still active the program exits with code 1 (failure). @mansect options @noindent @table @gnupgtabopt @item --verbose @opindex verbose Enable extra informational output. @item --check @opindex check Run only a syntax check on the patternfile. @item --null @opindex null Input is expected to be null delimited. @end table @mansect see also @ifset isman @command{gpg-agent}(1), @end ifset @include see-also-note.texi diff --git a/tools/gpgconf.c b/tools/gpgconf.c index 22569a870..a24c60f92 100644 --- a/tools/gpgconf.c +++ b/tools/gpgconf.c @@ -1,1778 +1,1786 @@ /* gpgconf.c - Configuration utility for GnuPG * Copyright (C) 2003, 2007, 2009, 2011 Free Software Foundation, Inc. * Copyright (C) 2016 g10 Code GmbH. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #define INCLUDED_BY_MAIN_MODULE 1 #include "gpgconf.h" #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/init.h" #include "../common/status.h" #include "../common/exechelp.h" #include "../common/dotlock.h" #ifdef HAVE_W32_SYSTEM #include #endif /* Constants to identify the commands and options. */ enum cmd_and_opt_values { aNull = 0, oDryRun = 'n', oOutput = 'o', oQuiet = 'q', oVerbose = 'v', oRuntime = 'r', oComponent = 'c', oNull = '0', aListDirs = 'L', aKill = 'K', aReload = 'R', aShowVersions = 'V', aShowConfigs = 'X', oNoVerbose = 500, oHomedir, oBuilddir, oStatusFD, oShowSocket, oChUid, aListComponents, aCheckPrograms, aListOptions, aChangeOptions, aCheckOptions, aApplyDefaults, aListConfig, aCheckConfig, aQuerySWDB, aLaunch, aCreateSocketDir, aRemoveSocketDir, aApplyProfile, aShowCodepages, aDotlockLock, aDotlockUnlock }; /* The list of commands and options. */ static gpgrt_opt_t opts[] = { ARGPARSE_group (300, N_("@Commands:\n ")), ARGPARSE_c (aListComponents, "list-components", N_("list all components")), ARGPARSE_c (aCheckPrograms, "check-programs", N_("check all programs")), ARGPARSE_c (aListOptions, "list-options", N_("|COMPONENT|list options")), ARGPARSE_c (aChangeOptions, "change-options", N_("|COMPONENT|change options")), ARGPARSE_c (aCheckOptions, "check-options", N_("|COMPONENT|check options")), ARGPARSE_c (aApplyDefaults, "apply-defaults", N_("apply global default values")), ARGPARSE_c (aApplyProfile, "apply-profile", N_("|FILE|update configuration files using FILE")), ARGPARSE_c (aListDirs, "list-dirs", N_("get the configuration directories for @GPGCONF@")), ARGPARSE_c (aListConfig, "list-config", N_("list global configuration file")), ARGPARSE_c (aCheckConfig, "check-config", N_("check global configuration file")), ARGPARSE_c (aQuerySWDB, "query-swdb", N_("query the software version database")), ARGPARSE_c (aReload, "reload", N_("reload all or a given component")), ARGPARSE_c (aLaunch, "launch", N_("launch a given component")), ARGPARSE_c (aKill, "kill", N_("kill a given component")), ARGPARSE_c (aCreateSocketDir, "create-socketdir", "@"), ARGPARSE_c (aRemoveSocketDir, "remove-socketdir", "@"), ARGPARSE_c (aShowVersions, "show-versions", ""), ARGPARSE_c (aShowConfigs, "show-configs", ""), /* hidden commands: for debugging */ ARGPARSE_c (aShowCodepages, "show-codepages", "@"), ARGPARSE_c (aDotlockLock, "lock", "@"), ARGPARSE_c (aDotlockUnlock, "unlock", "@"), ARGPARSE_header (NULL, N_("@\nOptions:\n ")), ARGPARSE_s_s (oOutput, "output", N_("use as output file")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("quiet")), ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")), ARGPARSE_s_n (oRuntime, "runtime", N_("activate changes at runtime, if possible")), ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")), /* hidden options */ ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_s (oBuilddir, "build-prefix", "@"), ARGPARSE_s_n (oNull, "null", "@"), ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"), ARGPARSE_s_n (oShowSocket, "show-socket", "@"), ARGPARSE_s_s (oChUid, "chuid", "@"), ARGPARSE_end () }; #define CUTLINE_FMT \ "--8<---------------cut here---------------%s------------->8---\n" /* The stream to output the status information. Status Output is disabled if * this is NULL. */ static estream_t statusfp; static void show_versions (estream_t fp); static void show_configs (estream_t fp); /* Print usage information and provide strings for help. */ static const char * my_strusage( int level ) { const char *p; switch (level) { case 9: p = "GPL-3.0-or-later"; break; case 11: p = "@GPGCONF@ (@GNUPG@)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: @GPGCONF@ [options] (-h for help)"); break; case 41: p = _("Syntax: @GPGCONF@ [options]\n" "Manage configuration options for tools of the @GNUPG@ system\n"); break; default: p = NULL; break; } return p; } /* Return the fp for the output. This is usually stdout unless --output has been used. In the latter case this function opens that file. */ static estream_t get_outfp (estream_t *fp) { if (!*fp) { if (opt.outfile) { *fp = es_fopen (opt.outfile, "w"); if (!*fp) gc_error (1, errno, "can not open '%s'", opt.outfile); } else *fp = es_stdout; } return *fp; } /* Set the status FD. */ static void set_status_fd (int fd) { static int last_fd = -1; if (fd != -1 && last_fd == fd) return; if (statusfp && statusfp != es_stdout && statusfp != es_stderr) es_fclose (statusfp); statusfp = NULL; if (fd == -1) return; if (fd == 1) statusfp = es_stdout; else if (fd == 2) statusfp = es_stderr; else statusfp = es_fdopen (fd, "w"); if (!statusfp) { log_fatal ("can't open fd %d for status output: %s\n", fd, gpg_strerror (gpg_error_from_syserror ())); } last_fd = fd; } /* Write a status line with code NO followed by the output of the * printf style FORMAT. The caller needs to make sure that LFs and * CRs are not printed. */ void gpgconf_write_status (int no, const char *format, ...) { va_list arg_ptr; if (!statusfp) return; /* Not enabled. */ es_fputs ("[GNUPG:] ", statusfp); es_fputs (get_status_string (no), statusfp); if (format) { es_putc (' ', statusfp); va_start (arg_ptr, format); es_vfprintf (statusfp, format, arg_ptr); va_end (arg_ptr); } es_putc ('\n', statusfp); } static void list_dirs (estream_t fp, char **names, int special) { static struct { const char *name; const char *(*fnc)(void); const char *extra; } list[] = { { "sysconfdir", gnupg_sysconfdir, NULL }, { "bindir", gnupg_bindir, NULL }, { "libexecdir", gnupg_libexecdir, NULL }, { "libdir", gnupg_libdir, NULL }, { "datadir", gnupg_datadir, NULL }, { "localedir", gnupg_localedir, NULL }, { "socketdir", gnupg_socketdir, NULL }, { "dirmngr-socket", dirmngr_socket_name, NULL,}, { "keyboxd-socket", keyboxd_socket_name, NULL,}, { "agent-ssh-socket", gnupg_socketdir, GPG_AGENT_SSH_SOCK_NAME }, { "agent-extra-socket", gnupg_socketdir, GPG_AGENT_EXTRA_SOCK_NAME }, { "agent-browser-socket",gnupg_socketdir, GPG_AGENT_BROWSER_SOCK_NAME }, { "agent-socket", gnupg_socketdir, GPG_AGENT_SOCK_NAME }, { "homedir", gnupg_homedir, NULL } }; int idx, j; char *tmp; const char *s; for (idx = 0; idx < DIM (list); idx++) { s = list[idx].fnc (); if (list[idx].extra) { tmp = make_filename (s, list[idx].extra, NULL); s = tmp; } else tmp = NULL; if (!names) es_fprintf (fp, "%s:%s\n", list[idx].name, gc_percent_escape (s)); else { for (j=0; names[j]; j++) if (!strcmp (names[j], list[idx].name)) { es_fputs (s, fp); es_putc (opt.null? '\0':'\n', fp); } } xfree (tmp); } #ifdef HAVE_W32_SYSTEM tmp = read_w32_registry_string (NULL, - GNUPG_REGISTRY_DIR, + gnupg_registry_dir (), "HomeDir"); if (tmp) { int hkcu = 0; int hklm = 0; xfree (tmp); if ((tmp = read_w32_registry_string ("HKEY_CURRENT_USER", - GNUPG_REGISTRY_DIR, + gnupg_registry_dir (), "HomeDir"))) { xfree (tmp); hkcu = 1; } if ((tmp = read_w32_registry_string ("HKEY_LOCAL_MACHINE", - GNUPG_REGISTRY_DIR, + gnupg_registry_dir (), "HomeDir"))) { xfree (tmp); hklm = 1; } es_fflush (fp); if (special) es_fprintf (fp, "\n" "### Note: homedir taken from registry key %s%s\\%s:%s\n" "\n", hkcu?"HKCU":"", hklm?"HKLM":"", - GNUPG_REGISTRY_DIR, "HomeDir"); + gnupg_registry_dir (), "HomeDir"); else log_info ("Warning: homedir taken from registry key (%s:%s) in%s%s\n", - GNUPG_REGISTRY_DIR, "HomeDir", + gnupg_registry_dir (), "HomeDir", hkcu?" HKCU":"", hklm?" HKLM":""); } else if ((tmp = read_w32_registry_string (NULL, - GNUPG_REGISTRY_DIR, + gnupg_registry_dir (), NULL))) { xfree (tmp); es_fflush (fp); if (special) es_fprintf (fp, "\n" "### Note: registry %s without value in HKCU or HKLM\n" - "\n", GNUPG_REGISTRY_DIR); + "\n", gnupg_registry_dir ()); else log_info ("Warning: registry key (%s) without value in HKCU or HKLM\n", - GNUPG_REGISTRY_DIR); + gnupg_registry_dir ()); } #else /*!HAVE_W32_SYSTEM*/ (void)special; #endif /*!HAVE_W32_SYSTEM*/ } /* Check whether NAME is valid argument for query_swdb(). Valid names * start with a letter and contain only alphanumeric characters or an * underscore. */ static int valid_swdb_name_p (const char *name) { if (!name || !*name || !alphap (name)) return 0; for (name++; *name; name++) if (!alnump (name) && *name != '_') return 0; return 1; } /* Query the SWDB file. If necessary and possible this functions asks * the dirmngr to load an updated version of that file. The caller * needs to provide the NAME to query (e.g. "gnupg", "libgcrypt") and * optional the currently installed version in CURRENT_VERSION. The * output written to OUT is a colon delimited line with these fields: * * name :: The name of the package * curvers:: The installed version if given. * status :: This value tells the status of the software package * '-' :: No information available * (error or CURRENT_VERSION not given) * '?' :: Unknown NAME * 'u' :: Update available * 'c' :: The version is Current * 'n' :: The current version is already Newer than the * available one. * urgency :: If the value is greater than zero an urgent update is required. * error :: 0 on success or an gpg_err_code_t * Common codes seen: * GPG_ERR_TOO_OLD :: The SWDB file is to old to be used. * GPG_ERR_ENOENT :: The SWDB file is not available. * GPG_ERR_BAD_SIGNATURE :: Corrupted SWDB file. * filedate:: Date of the swdb file (yyyymmddThhmmss) * verified:: Date we checked the validity of the file (yyyyymmddThhmmss) * version :: The version string from the swdb. * reldate :: Release date of that version (yyyymmddThhmmss) * size :: Size of the package in bytes. * hash :: SHA-2 hash of the package. * */ static void query_swdb (estream_t out, const char *name, const char *current_version) { gpg_error_t err; const char *search_name; char *fname = NULL; estream_t fp = NULL; char *line = NULL; char *self_version = NULL; size_t length_of_line = 0; size_t maxlen; ssize_t len; const char *fields[2]; char *p; gnupg_isotime_t filedate = {0}; gnupg_isotime_t verified = {0}; char *value_ver = NULL; gnupg_isotime_t value_date = {0}; char *value_size = NULL; char *value_sha2 = NULL; unsigned long value_size_ul = 0; int status, i; if (!valid_swdb_name_p (name)) { log_error ("error in package name '%s': %s\n", name, gpg_strerror (GPG_ERR_INV_NAME)); goto leave; } if (!strcmp (name, "gnupg")) search_name = GNUPG_SWDB_TAG; else if (!strcmp (name, "gnupg1")) search_name = "gnupg1"; else search_name = name; if (!current_version && !strcmp (name, "gnupg")) { /* Use our own version but string a possible beta string. */ self_version = xstrdup (PACKAGE_VERSION); p = strchr (self_version, '-'); if (p) *p = 0; current_version = self_version; } if (current_version && (strchr (current_version, ':') || compare_version_strings (current_version, NULL))) { log_error ("error in version string '%s': %s\n", current_version, gpg_strerror (GPG_ERR_INV_ARG)); goto leave; } fname = make_filename (gnupg_homedir (), "swdb.lst", NULL); fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); es_fprintf (out, "%s:%s:-::%u:::::::\n", name, current_version? current_version : "", gpg_err_code (err)); if (gpg_err_code (err) != GPG_ERR_ENOENT) log_error (_("error opening '%s': %s\n"), fname, gpg_strerror (err)); goto leave; } /* Note that the parser uses the first occurrence of a matching * values and ignores possible duplicated values. */ maxlen = 2048; /* Set limit. */ while ((len = es_read_line (fp, &line, &length_of_line, &maxlen)) > 0) { if (!maxlen) { err = gpg_error (GPG_ERR_LINE_TOO_LONG); log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err)); goto leave; } /* Strip newline and carriage return, if present. */ while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) line[--len] = '\0'; if (split_fields (line, fields, DIM (fields)) < DIM(fields)) continue; /* Skip empty lines and names w/o a value. */ if (*fields[0] == '#') continue; /* Skip comments. */ /* Record the meta data. */ if (!*filedate && !strcmp (fields[0], ".filedate")) { string2isotime (filedate, fields[1]); continue; } if (!*verified && !strcmp (fields[0], ".verified")) { string2isotime (verified, fields[1]); continue; } /* Tokenize the name. */ p = strrchr (fields[0], '_'); if (!p) continue; /* Name w/o an underscore. */ *p++ = 0; /* Wait for the requested name. */ if (!strcmp (fields[0], search_name)) { if (!strcmp (p, "ver") && !value_ver) value_ver = xstrdup (fields[1]); else if (!strcmp (p, "date") && !*value_date) string2isotime (value_date, fields[1]); else if (!strcmp (p, "size") && !value_size) value_size = xstrdup (fields[1]); else if (!strcmp (p, "sha2") && !value_sha2) value_sha2 = xstrdup (fields[1]); } } if (len < 0 || es_ferror (fp)) { err = gpg_error_from_syserror (); log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err)); goto leave; } if (!*filedate || !*verified) { err = gpg_error (GPG_ERR_INV_TIME); es_fprintf (out, "%s:%s:-::%u:::::::\n", name, current_version? current_version : "", gpg_err_code (err)); goto leave; } if (!value_ver) { es_fprintf (out, "%s:%s:?:::::::::\n", name, current_version? current_version : ""); goto leave; } if (value_size) { gpg_err_set_errno (0); value_size_ul = strtoul (value_size, &p, 10); if (errno) value_size_ul = 0; else if (*p == 'k') value_size_ul *= 1024; } err = 0; status = '-'; if (compare_version_strings (value_ver, NULL)) err = gpg_error (GPG_ERR_INV_VALUE); else if (!current_version) ; else if (!(i = compare_version_strings (value_ver, current_version))) status = 'c'; else if (i > 0) status = 'u'; else status = 'n'; es_fprintf (out, "%s:%s:%c::%d:%s:%s:%s:%s:%lu:%s:\n", name, current_version? current_version : "", status, err, filedate, verified, value_ver, value_date, value_size_ul, value_sha2? value_sha2 : ""); leave: xfree (value_ver); xfree (value_size); xfree (value_sha2); xfree (line); es_fclose (fp); xfree (fname); xfree (self_version); } #if !defined(HAVE_W32_SYSTEM) /* dotlock tool to handle dotlock by command line DO_LOCK: 1 for to lock, 0 for unlock FILENAME: filename for the dotlock */ static void dotlock_tool (int do_lock, const char *filename) { dotlock_t h; unsigned int flags = DOTLOCK_LOCK_BY_PARENT; if (!do_lock) flags |= DOTLOCK_LOCKED; h = dotlock_create (filename, flags); if (!h) { if (do_lock) log_error ("error creating the lock file\n"); else log_error ("no lock file found\n"); return; } if (do_lock) { if (dotlock_take (h, 0)) log_error ("error taking the lock\n"); } else dotlock_release (h); dotlock_destroy (h); } #endif /* gpgconf main. */ int main (int argc, char **argv) { gpg_error_t err; gpgrt_argparse_t pargs; const char *fname; int no_more_options = 0; enum cmd_and_opt_values cmd = 0; estream_t outfp = NULL; int show_socket = 0; const char *changeuser = NULL; early_system_init (); gnupg_reopen_std (GPGCONF_NAME); gpgrt_set_strusage (my_strusage); log_set_prefix (GPGCONF_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_NO_REGISTRY); /* Make sure that our subsystems are ready. */ i18n_init(); init_common_subsystems (&argc, &argv); gc_components_init (); /* Parse the command line. */ pargs.argc = &argc; pargs.argv = &argv; pargs.flags = ARGPARSE_FLAG_KEEP; while (!no_more_options && gpgrt_argparse (NULL, &pargs, opts)) { switch (pargs.r_opt) { case oOutput: opt.outfile = pargs.r.ret_str; break; case oQuiet: opt.quiet = 1; break; case oDryRun: opt.dry_run = 1; break; case oRuntime: opt.runtime = 1; break; case oVerbose: opt.verbose++; break; case oNoVerbose: opt.verbose = 0; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oBuilddir: gnupg_set_builddir (pargs.r.ret_str); break; case oNull: opt.null = 1; break; case oStatusFD: set_status_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1)); break; case oShowSocket: show_socket = 1; break; case oChUid: changeuser = pargs.r.ret_str; break; case aListDirs: case aListComponents: case aCheckPrograms: case aListOptions: case aChangeOptions: case aCheckOptions: case aApplyDefaults: case aApplyProfile: case aListConfig: case aCheckConfig: case aQuerySWDB: case aReload: case aLaunch: case aKill: case aCreateSocketDir: case aRemoveSocketDir: case aShowVersions: case aShowConfigs: case aShowCodepages: case aDotlockLock: case aDotlockUnlock: cmd = pargs.r_opt; break; default: pargs.err = 2; break; } } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (log_get_errorcount (0)) gpgconf_failure (GPG_ERR_USER_2); /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } fname = argc ? *argv : NULL; /* If requested switch to the requested user or die. */ if (changeuser && (err = gnupg_chuid (changeuser, 0))) gpgconf_failure (err); /* Set the configuraton directories for use by gpgrt_argparser. We * don't have a configuration file for this program but we have code * which reads the component's config files. */ gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ()); gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ()); switch (cmd) { case aListComponents: default: /* List all components. */ gc_component_list_components (get_outfp (&outfp)); break; case aCheckPrograms: /* Check all programs. */ gc_check_programs (get_outfp (&outfp)); break; case aListOptions: case aChangeOptions: case aCheckOptions: if (!fname) { es_fprintf (es_stderr, _("usage: %s [options] "), GPGCONF_NAME); es_putc ('\n', es_stderr); es_fputs (_("Need one component argument"), es_stderr); es_putc ('\n', es_stderr); gpgconf_failure (GPG_ERR_USER_2); } else { int idx = gc_component_find (fname); if (idx < 0) { es_fputs (_("Component not found"), es_stderr); es_putc ('\n', es_stderr); gpgconf_failure (0); } if (cmd == aCheckOptions) gc_component_check_options (idx, get_outfp (&outfp), NULL); else { gc_component_retrieve_options (idx); if (gc_process_gpgconf_conf (NULL, 1, 0, NULL)) gpgconf_failure (0); if (cmd == aListOptions) gc_component_list_options (idx, get_outfp (&outfp)); else if (cmd == aChangeOptions) gc_component_change_options (idx, es_stdin, get_outfp (&outfp), 0); } } break; case aLaunch: case aKill: if (!fname) { es_fprintf (es_stderr, _("usage: %s [options] "), GPGCONF_NAME); es_putc ('\n', es_stderr); es_fputs (_("Need one component argument"), es_stderr); es_putc ('\n', es_stderr); gpgconf_failure (GPG_ERR_USER_2); } else if (!strcmp (fname, "all")) { if (cmd == aLaunch) { if (gc_component_launch (-1)) gpgconf_failure (0); } else { gc_component_kill (-1); } } else { /* Launch/Kill a given component. */ int idx; idx = gc_component_find (fname); if (idx < 0) { es_fputs (_("Component not found"), es_stderr); es_putc ('\n', es_stderr); gpgconf_failure (0); } else if (cmd == aLaunch) { err = gc_component_launch (idx); if (show_socket) { char *names[2]; if (idx == GC_COMPONENT_GPG_AGENT) names[0] = "agent-socket"; else if (idx == GC_COMPONENT_DIRMNGR) names[0] = "dirmngr-socket"; else if (idx == GC_COMPONENT_KEYBOXD) names[0] = "keyboxd-socket"; else names[0] = NULL; names[1] = NULL; get_outfp (&outfp); list_dirs (outfp, names, 0); } if (err) gpgconf_failure (0); } else { /* We don't error out if the kill failed because this command should do nothing if the component is not running. */ gc_component_kill (idx); } } break; case aReload: if (!fname || !strcmp (fname, "all")) { /* Reload all. */ gc_component_reload (-1); } else { /* Reload given component. */ int idx; idx = gc_component_find (fname); if (idx < 0) { es_fputs (_("Component not found"), es_stderr); es_putc ('\n', es_stderr); gpgconf_failure (0); } else { gc_component_reload (idx); } } break; case aListConfig: if (gc_process_gpgconf_conf (fname, 0, 0, get_outfp (&outfp))) gpgconf_failure (0); break; case aCheckConfig: if (gc_process_gpgconf_conf (fname, 0, 0, NULL)) gpgconf_failure (0); break; case aApplyDefaults: if (fname) { es_fprintf (es_stderr, _("usage: %s [options] "), GPGCONF_NAME); es_putc ('\n', es_stderr); es_fputs (_("No argument allowed"), es_stderr); es_putc ('\n', es_stderr); gpgconf_failure (GPG_ERR_USER_2); } if (!opt.dry_run && gnupg_access (gnupg_homedir (), F_OK)) gnupg_maybe_make_homedir (gnupg_homedir (), opt.quiet); gc_component_retrieve_options (-1); if (gc_process_gpgconf_conf (NULL, 1, 1, NULL)) gpgconf_failure (0); break; case aApplyProfile: if (!opt.dry_run && gnupg_access (gnupg_homedir (), F_OK)) gnupg_maybe_make_homedir (gnupg_homedir (), opt.quiet); gc_component_retrieve_options (-1); if (gc_apply_profile (fname)) gpgconf_failure (0); break; case aListDirs: /* Show the system configuration directories for gpgconf. */ get_outfp (&outfp); list_dirs (outfp, argc? argv : NULL, 0); break; case aQuerySWDB: /* Query the software version database. */ if (!fname || argc > 2) { es_fprintf (es_stderr, "usage: %s --query-swdb NAME [VERSION]\n", GPGCONF_NAME); gpgconf_failure (GPG_ERR_USER_2); } get_outfp (&outfp); query_swdb (outfp, fname, argc > 1? argv[1] : NULL); break; case aCreateSocketDir: { char *socketdir; unsigned int flags; /* Make sure that the top /run/user/UID/gnupg dir has been * created. */ gnupg_socketdir (); /* Check the /var/run dir. */ socketdir = _gnupg_socketdir_internal (1, &flags); if ((flags & 64) && !opt.dry_run) { /* No sub dir - create it. */ if (gnupg_mkdir (socketdir, "-rwx")) gc_error (1, errno, "error creating '%s'", socketdir); /* Try again. */ xfree (socketdir); socketdir = _gnupg_socketdir_internal (1, &flags); } /* Give some info. */ if ( (flags & ~32) || opt.verbose || opt.dry_run) { log_info ("socketdir is '%s'\n", socketdir); if ((flags & 1)) log_info ("\tgeneral error\n"); if ((flags & 2)) log_info ("\tno /run/user dir\n"); if ((flags & 4)) log_info ("\tbad permissions\n"); if ((flags & 8)) log_info ("\tbad permissions (subdir)\n"); if ((flags & 16)) log_info ("\tmkdir failed\n"); if ((flags & 32)) log_info ("\tnon-default homedir\n"); if ((flags & 64)) log_info ("\tno such subdir\n"); if ((flags & 128)) log_info ("\tusing homedir as fallback\n"); } if ((flags & ~32) && !opt.dry_run) gc_error (1, 0, "error creating socket directory"); xfree (socketdir); } break; case aRemoveSocketDir: { char *socketdir; unsigned int flags; /* Check the /var/run dir. */ socketdir = _gnupg_socketdir_internal (1, &flags); if ((flags & 128)) log_info ("ignoring request to remove non /run/user socket dir\n"); else if (opt.dry_run) ; else if (gnupg_rmdir (socketdir)) { /* If the director is not empty we first try to delete * socket files. */ err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_ENOTEMPTY || gpg_err_code (err) == GPG_ERR_EEXIST) { static const char * const names[] = { GPG_AGENT_SOCK_NAME, GPG_AGENT_EXTRA_SOCK_NAME, GPG_AGENT_BROWSER_SOCK_NAME, GPG_AGENT_SSH_SOCK_NAME, SCDAEMON_SOCK_NAME, KEYBOXD_SOCK_NAME, DIRMNGR_SOCK_NAME, TPM2DAEMON_SOCK_NAME }; int i; char *p; for (i=0; i < DIM(names); i++) { p = strconcat (socketdir , "/", names[i], NULL); if (p) gnupg_remove (p); xfree (p); } if (gnupg_rmdir (socketdir)) { err = gpg_error_from_syserror (); gc_error (1, 0, "error removing '%s': %s", socketdir, gpg_strerror (err)); } } else if (gpg_err_code (err) == GPG_ERR_ENOENT) gc_error (0, 0, "warning: removing '%s' failed: %s", socketdir, gpg_strerror (err)); else gc_error (1, 0, "error removing '%s': %s", socketdir, gpg_strerror (err)); } xfree (socketdir); } break; case aShowVersions: { get_outfp (&outfp); show_versions (outfp); } break; case aShowConfigs: { get_outfp (&outfp); show_configs (outfp); } break; case aShowCodepages: #ifdef HAVE_W32_SYSTEM { get_outfp (&outfp); if (GetConsoleCP () != GetConsoleOutputCP ()) es_fprintf (outfp, "Console: CP%u/CP%u\n", GetConsoleCP (), GetConsoleOutputCP ()); else es_fprintf (outfp, "Console: CP%u\n", GetConsoleCP ()); es_fprintf (outfp, "ANSI: CP%u\n", GetACP ()); es_fprintf (outfp, "OEM: CP%u\n", GetOEMCP ()); } #endif break; case aDotlockLock: case aDotlockUnlock: #if !defined(HAVE_W32_SYSTEM) if (!fname) { es_fprintf (es_stderr, "usage: %s --%slock NAME", GPGCONF_NAME, cmd==aDotlockUnlock?"un":""); es_putc ('\n', es_stderr); es_fputs ("Need name of file protected by the lock", es_stderr); es_putc ('\n', es_stderr); gpgconf_failure (GPG_ERR_SYNTAX); } else { char *filename; /* Keybox pubring.db lock is under public-keys.d. */ if (!strcmp (fname, "pubring.db")) fname = "public-keys.d/pubring.db"; filename = make_absfilename (gnupg_homedir (), fname, NULL); dotlock_tool (cmd == aDotlockLock, filename); xfree (filename); } #endif break; } if (outfp != es_stdout) if (es_fclose (outfp)) gc_error (1, errno, "error closing '%s'", opt.outfile); if (log_get_errorcount (0)) gpgconf_failure (0); else gpgconf_write_status (STATUS_SUCCESS, NULL); return 0; } void gpgconf_failure (gpg_error_t err) { log_flush (); if (!err) err = gpg_error (GPG_ERR_GENERAL); gpgconf_write_status (STATUS_FAILURE, "- %u", gpg_err_code (err) == GPG_ERR_USER_2? GPG_ERR_EINVAL : err); exit (gpg_err_code (err) == GPG_ERR_USER_2? 2 : 1); } /* Parse the revision part from the extended version blurb. */ static const char * get_revision_from_blurb (const char *blurb, int *r_len) { const char *s = blurb? blurb : ""; int n; for (; *s; s++) if (*s == '\n' && s[1] == '(') break; if (s) { s += 2; for (n=0; s[n] && s[n] != ' '; n++) ; } else { s = "?"; n = 1; } *r_len = n; return s; } static void show_version_gnupg (estream_t fp, const char *prefix) { char *fname, *p, *p0; size_t n; estream_t verfp; char *line = NULL; size_t line_len = 0; ssize_t length; es_fprintf (fp, "%s%sGnuPG %s (%s)\n%s%s\n", prefix, *prefix?"":"* ", gpgrt_strusage (13), BUILD_REVISION, prefix, gpgrt_strusage (17)); /* Show the GnuPG VS-Desktop version in --show-configs mode */ if (prefix && *prefix == '#') { fname = make_filename (gnupg_bindir (), NULL); n = strlen (fname); if (n > 10 && (!ascii_strcasecmp (fname + n - 10, "/GnuPG/bin") || !ascii_strcasecmp (fname + n - 10, "\\GnuPG\\bin"))) { /* Append VERSION to the ../../ direcory. Note that VERSION * is only 7 bytes and thus fits. */ strcpy (fname + n - 9, "VERSION"); verfp = es_fopen (fname, "r"); if (!verfp) es_fprintf (fp, "%s[VERSION file not found]\n", prefix); else { int lnr = 0; p0 = NULL; while ((length = es_read_line (verfp, &line, &line_len, NULL))>0) { lnr++; trim_spaces (line); if (lnr == 1 && *line != '[') { /* Old file format where we look only at the * first line. */ p0 = line; break; } else if (!strncmp (line, "version=", 8)) { p0 = line + 8; break; } } if (length < 0 || es_ferror (verfp)) es_fprintf (fp, "%s[VERSION file read error]\n", prefix); else if (p0) { for (p=p0; *p; p++) if (*p < ' ' || *p > '~' || *p == '[') *p = '?'; es_fprintf (fp, "%s%s\n", prefix, p0); } else es_fprintf (fp, "%s[VERSION file is empty]\n", prefix); es_fclose (verfp); } } xfree (fname); } xfree (line); #ifdef HAVE_W32_SYSTEM { OSVERSIONINFO osvi = { sizeof (osvi) }; GetVersionEx (&osvi); es_fprintf (fp, "%sWindows %lu.%lu build %lu%s%s%s\n", prefix, (unsigned long)osvi.dwMajorVersion, (unsigned long)osvi.dwMinorVersion, (unsigned long)osvi.dwBuildNumber, *osvi.szCSDVersion? " (":"", osvi.szCSDVersion, *osvi.szCSDVersion? ")":"" ); } #endif /*HAVE_W32_SYSTEM*/ } static void show_version_libgcrypt (estream_t fp) { const char *s; int n; s = get_revision_from_blurb (gcry_check_version ("\x01\x01"), &n); es_fprintf (fp, "* Libgcrypt %s (%.*s)\n", gcry_check_version (NULL), n, s); s = gcry_get_config (0, NULL); if (s) es_fputs (s, fp); } static void show_version_gpgrt (estream_t fp) { const char *s; int n; s = get_revision_from_blurb (gpg_error_check_version ("\x01\x01"), &n); es_fprintf (fp, "* GpgRT %s (%.*s)\n", gpg_error_check_version (NULL), n, s); } /* Printing version information for other libraries is problematic * because we don't want to link gpgconf to all these libraries. The * best solution is delegating this to dirmngr which uses libassuan, * libksba, libnpth and ntbtls anyway. */ static void show_versions_via_dirmngr (estream_t fp) { gpg_error_t err; const char *pgmname; const char *argv[2]; estream_t outfp; gnupg_process_t proc; char *line = NULL; size_t line_len = 0; ssize_t length; pgmname = gnupg_module_name (GNUPG_MODULE_NAME_DIRMNGR); argv[0] = "--gpgconf-versions"; argv[1] = NULL; err = gnupg_process_spawn (pgmname, argv, GNUPG_PROCESS_STDOUT_PIPE, NULL, NULL, &proc); if (err) { log_error ("error spawning %s: %s", pgmname, gpg_strerror (err)); es_fprintf (fp, "[error: can't get further info]\n"); return; } gnupg_process_get_streams (proc, 0, NULL, &outfp, NULL); while ((length = es_read_line (outfp, &line, &line_len, NULL)) > 0) { /* Strip newline and carriage return, if present. */ while (length > 0 && (line[length - 1] == '\n' || line[length - 1] == '\r')) line[--length] = '\0'; es_fprintf (fp, "%s\n", line); } if (length < 0 || es_ferror (outfp)) { err = gpg_error_from_syserror (); log_error ("error reading from %s: %s\n", pgmname, gpg_strerror (err)); } if (es_fclose (outfp)) { err = gpg_error_from_syserror (); log_error ("error closing output stream of %s: %s\n", pgmname, gpg_strerror (err)); } err = gnupg_process_wait (proc, 1); if (!err) { int exitcode; gnupg_process_ctl (proc, GNUPG_PROCESS_GET_EXIT_ID, &exitcode); log_error ("running %s failed (exitcode=%d): %s\n", pgmname, exitcode, gpg_strerror (err)); es_fprintf (fp, "[error: can't get further info]\n"); } gnupg_process_release (proc); xfree (line); } /* Show all kind of version information. */ static void show_versions (estream_t fp) { show_version_gnupg (fp, ""); es_fputc ('\n', fp); show_version_libgcrypt (fp); es_fputc ('\n', fp); show_version_gpgrt (fp); es_fputc ('\n', fp); show_versions_via_dirmngr (fp); } /* Copy data from file SRC to DST. Returns 0 on success or an error * code on failure. If LISTP is not NULL, that strlist is updated * with the variabale or registry key names detected. Flag bit 0 * indicates a registry entry. */ static gpg_error_t my_copy_file (estream_t src, estream_t dst, strlist_t *listp) { gpg_error_t err; char *line = NULL; size_t line_len = 0; ssize_t length; int written; while ((length = es_read_line (src, &line, &line_len, NULL)) > 0) { /* Strip newline and carriage return, if present. */ written = gpgrt_fwrite (line, 1, length, dst); if (written != length) return gpg_error_from_syserror (); trim_spaces (line); if (*line == '[' && listp) { char **tokens; char *p; for (p=line+1; *p; p++) if (*p != ' ' && *p != '\t') break; if (*p && p[strlen (p)-1] == ']') p[strlen (p)-1] = 0; tokens = strtokenize (p, " \t"); if (!tokens) { err = gpg_error_from_syserror (); log_error ("strtokenize failed: %s\n", gpg_strerror (err)); return err; } /* Check whether we have a getreg or getenv statement and * store the third token to later retrieval. */ if (tokens[0] && tokens[1] && tokens[2] && (!strcmp (tokens[0], "getreg") || !strcmp (tokens[0], "getenv"))) { int isreg = (tokens[0][3] == 'r'); strlist_t sl = *listp; for (sl = *listp; sl; sl = sl->next) if (!strcmp (sl->d, tokens[2]) && (sl->flags & 1) == isreg) break; if (!sl) /* Not yet in the respective list. */ { sl = add_to_strlist (listp, tokens[2]); if (isreg) sl->flags = 1; } } xfree (tokens); } } if (length < 0 || es_ferror (src)) return gpg_error_from_syserror (); if (gpgrt_fflush (dst)) return gpg_error_from_syserror (); return 0; } /* Helper for show_configs */ static void show_configs_one_file (const char *fname, int global, estream_t outfp, strlist_t *listp) { gpg_error_t err; estream_t fp; fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); es_fprintf (outfp, "###\n### %s config \"%s\": %s\n###\n", global? "global":"local", fname, (gpg_err_code (err) == GPG_ERR_ENOENT)? "not installed" : gpg_strerror (err)); } else { es_fprintf (outfp, "###\n### %s config \"%s\"\n###\n", global? "global":"local", fname); es_fprintf (outfp, CUTLINE_FMT, "start"); err = my_copy_file (fp, outfp, listp); if (err) log_error ("error copying file \"%s\": %s\n", fname, gpg_strerror (err)); es_fprintf (outfp, CUTLINE_FMT, "end--"); es_fclose (fp); } } #ifdef HAVE_W32_SYSTEM /* Print registry entries relevant to the GnuPG system and related * software. */ static void show_other_registry_entries (estream_t outfp) { static struct { int group; const char *name; + unsigned int prependregkey:1; } names[] = { { 1, "HKLM\\Software\\Gpg4win:Install Directory" }, { 1, "HKLM\\Software\\Gpg4win:Desktop-Version" }, { 1, "HKLM\\Software\\Gpg4win:VS-Desktop-Version" }, - { 1, "\\" GNUPG_REGISTRY_DIR ":HomeDir" }, - { 1, "\\" GNUPG_REGISTRY_DIR ":DefaultLogFile" }, + { 1, ":HomeDir", 1 }, + { 1, ":DefaultLogFile", 1 }, { 2, "\\Software\\Microsoft\\Office\\Outlook\\Addins\\GNU.GpgOL" ":LoadBehavior" }, { 2, "HKCU\\Software\\Microsoft\\Office\\16.0\\Outlook\\Options\\Mail:" "ReadAsPlain" }, { 2, "HKCU\\Software\\Policies\\Microsoft\\Office\\16.0\\Outlook\\" "Options\\Mail:ReadAsPlain" }, { 3, "logFile" }, { 3, "enableDebug" }, { 3, "searchSmimeServers" }, { 3, "smimeInsecureReplyAllowed" }, { 3, "enableSmime" }, { 3, "preferSmime" }, { 3, "encryptDefault" }, { 3, "signDefault" }, { 3, "inlinePGP" }, { 3, "replyCrypt" }, { 3, "autoresolve" }, { 3, "autoretrieve" }, { 3, "automation" }, { 3, "autosecure" }, { 3, "autotrust" }, { 3, "autoencryptUntrusted" }, { 3, "autoimport" }, { 3, "splitBCCMails" }, { 3, "combinedOpsEnabled" }, { 3, "encryptSubject" }, { 0, NULL } }; int idx; int group = 0; char *namebuf = NULL; const char *name; int from_hklm; for (idx=0; (name = names[idx].name); idx++) { char *value; if (names[idx].group == 3) { xfree (namebuf); namebuf = xstrconcat ("\\Software\\GNU\\GpgOL", ":", names[idx].name, NULL); name = namebuf; } + else if (names[idx].prependregkey) + { + xfree (namebuf); + namebuf = xstrconcat ("\\", gnupg_registry_dir (), + names[idx].name, NULL); + name = namebuf; + } value = read_w32_reg_string (name, &from_hklm); if (!value) continue; if (names[idx].group != group) { group = names[idx].group; es_fprintf (outfp, "###\n### %s related:\n", group == 1 ? "GnuPG Desktop" : group == 2 ? "Outlook" : group == 3 ? "\\Software\\GNU\\GpgOL" : "System" ); } if (group == 3) es_fprintf (outfp, "### %s=%s%s\n", names[idx].name, value, from_hklm? " [hklm]":""); else es_fprintf (outfp, "### %s\n### ->%s<-%s\n", name, value, from_hklm? " [hklm]":""); xfree (value); } es_fprintf (outfp, "###\n"); xfree (namebuf); } /* Print registry entries take from a configuration file. */ static void show_registry_entries_from_file (estream_t outfp) { gpg_error_t err; char *fname; estream_t fp; char *line = NULL; size_t length_of_line = 0; size_t maxlen; ssize_t len; char *value = NULL; int from_hklm; int any = 0; fname = make_filename (gnupg_datadir (), "gpgconf.rnames", NULL); fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); if (gpg_err_code (err) != GPG_ERR_ENOENT) log_error ("error opening '%s': %s\n", fname, gpg_strerror (err)); goto leave; } maxlen = 2048; /* Set limit. */ while ((len = es_read_line (fp, &line, &length_of_line, &maxlen)) > 0) { if (!maxlen) { err = gpg_error (GPG_ERR_LINE_TOO_LONG); log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); goto leave; } trim_spaces (line); if (*line == '#') continue; xfree (value); value = read_w32_reg_string (line, &from_hklm); if (!value) continue; if (!any) { any = 1; es_fprintf (outfp, "### Taken from gpgconf.rnames:\n"); } es_fprintf (outfp, "### %s\n### ->%s<-%s\n", line, value, from_hklm? " [hklm]":""); } if (len < 0 || es_ferror (fp)) { err = gpg_error_from_syserror (); log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); } leave: if (any) es_fprintf (outfp, "###\n"); xfree (value); xfree (line); es_fclose (fp); xfree (fname); } #endif /*HAVE_W32_SYSTEM*/ /* Show all config files. */ static void show_configs (estream_t outfp) { static const char *names[] = { "common.conf", "gpg-agent.conf", "scdaemon.conf", "dirmngr.conf", "gpg.conf", "gpgsm.conf" }; static const char *envvars[] = { "PATH", "http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY", "LD_LIBRARY_PATH", "LD_PRELOAD", "LD_AUDIT", "LD_ORIGIN_PATH" }; gpg_error_t err; int idx; char *fname; gnupg_dir_t dir; gnupg_dirent_t dir_entry; size_t n; int any; strlist_t list = NULL; strlist_t sl; const char *s; int got_gpgconfconf = 0; es_fprintf (outfp, "### Dump of all standard config files\n"); show_version_gnupg (outfp, "### "); es_fprintf (outfp, "### Libgcrypt %s\n", gcry_check_version (NULL)); es_fprintf (outfp, "### GpgRT %s\n", gpg_error_check_version (NULL)); #ifdef HAVE_W32_SYSTEM es_fprintf (outfp, "### Codepages:"); if (GetConsoleCP () != GetConsoleOutputCP ()) es_fprintf (outfp, " %u/%u", GetConsoleCP (), GetConsoleOutputCP ()); else es_fprintf (outfp, " %u", GetConsoleCP ()); es_fprintf (outfp, " %u", GetACP ()); es_fprintf (outfp, " %u\n", GetOEMCP ()); #endif es_fprintf (outfp, "###\n\n"); list_dirs (outfp, NULL, 1); es_fprintf (outfp, "\n"); for (idx=0; idx < DIM(envvars); idx++) if ((s = getenv (envvars[idx]))) es_fprintf (outfp, "%s=%s\n", envvars[idx], s); es_fprintf (outfp, "\n"); fname = make_filename (gnupg_sysconfdir (), "gpgconf.conf", NULL); if (!gnupg_access (fname, F_OK)) { got_gpgconfconf = 1; show_configs_one_file (fname, 1, outfp, &list); es_fprintf (outfp, "\n"); } xfree (fname); for (idx = 0; idx < DIM (names); idx++) { fname = make_filename (gnupg_sysconfdir (), names[idx], NULL); show_configs_one_file (fname, 1, outfp, &list); xfree (fname); fname = make_filename (gnupg_homedir (), names[idx], NULL); show_configs_one_file (fname, 0, outfp, &list); xfree (fname); es_fprintf (outfp, "\n"); } /* Print the encountered registry values and envvars. */ if (list) { any = 0; for (sl = list; sl; sl = sl->next) if (!(sl->flags & 1)) { if (!any) { any = 1; es_fprintf (outfp, "###\n" "### List of encountered environment variables:\n"); } if ((s = getenv (sl->d))) es_fprintf (outfp, "### %-12s ->%s<-\n", sl->d, s); else es_fprintf (outfp, "### %-12s [not set]\n", sl->d); } if (any) es_fprintf (outfp, "###\n"); } #ifdef HAVE_W32_SYSTEM es_fprintf (outfp, "###\n### Registry entries:\n"); any = 0; if (list) { for (sl = list; sl; sl = sl->next) if ((sl->flags & 1)) { char *p; int from_hklm; if (!any) { any = 1; es_fprintf (outfp, "###\n### Encountered in config files:\n"); } if ((p = read_w32_reg_string (sl->d, &from_hklm))) es_fprintf (outfp, "### %s ->%s<-%s\n", sl->d, p, from_hklm? " [hklm]":""); else es_fprintf (outfp, "### %s [not set]\n", sl->d); xfree (p); } } if (!any) es_fprintf (outfp, "###\n"); show_other_registry_entries (outfp); show_registry_entries_from_file (outfp); #endif /*HAVE_W32_SYSTEM*/ free_strlist (list); any = 0; /* Additional warning. */ if (got_gpgconfconf) { es_fprintf (outfp, "###\n" "### Warning: legacy config file \"gpgconf.conf\" found\n"); any = 1; } /* Check for uncommon files in the home directory. */ dir = gnupg_opendir (gnupg_homedir ()); if (!dir) { err = gpg_error_from_syserror (); log_error ("error reading directory \"%s\": %s\n", gnupg_homedir (), gpg_strerror (err)); return; } while ((dir_entry = gnupg_readdir (dir))) { for (idx = 0; idx < DIM (names); idx++) { n = strlen (names[idx]); if (!ascii_strncasecmp (dir_entry->d_name, names[idx], n) && dir_entry->d_name[n] == '-' && ascii_strncasecmp (dir_entry->d_name, "gpg.conf-1", 10)) { if (!any) { any = 1; es_fprintf (outfp, "###\n" "### Warning: suspicious files in \"%s\":\n", gnupg_homedir ()); } es_fprintf (outfp, "### %s\n", dir_entry->d_name); } } } if (any) es_fprintf (outfp, "###\n"); gnupg_closedir (dir); }