Imported Upstream version 2.1.23
[platform/upstream/gpg2.git] / common / homedir.c
1 /* homedir.c - Setup the home directory.
2  * Copyright (C) 2004, 2006, 2007, 2010 Free Software Foundation, Inc.
3  * Copyright (C) 2013, 2016 Werner Koch
4  *
5  * This file is part of GnuPG.
6  *
7  * This file is free software; you can redistribute it and/or modify
8  * it under the terms of either
9  *
10  *   - the GNU Lesser General Public License as published by the Free
11  *     Software Foundation; either version 3 of the License, or (at
12  *     your option) any later version.
13  *
14  * or
15  *
16  *   - the GNU General Public License as published by the Free
17  *     Software Foundation; either version 2 of the License, or (at
18  *     your option) any later version.
19  *
20  * or both in parallel, as here.
21  *
22  * This file is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program; if not, see <https://www.gnu.org/licenses/>.
29  */
30
31 #include <config.h>
32 #include <stdlib.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <unistd.h>
36
37 #ifdef HAVE_W32_SYSTEM
38 #include <winsock2.h>   /* Due to the stupid mingw64 requirement to
39                            include this header before windows.h which
40                            is often implicitly included.  */
41 #include <shlobj.h>
42 #ifndef CSIDL_APPDATA
43 #define CSIDL_APPDATA 0x001a
44 #endif
45 #ifndef CSIDL_LOCAL_APPDATA
46 #define CSIDL_LOCAL_APPDATA 0x001c
47 #endif
48 #ifndef CSIDL_COMMON_APPDATA
49 #define CSIDL_COMMON_APPDATA 0x0023
50 #endif
51 #ifndef CSIDL_FLAG_CREATE
52 #define CSIDL_FLAG_CREATE 0x8000
53 #endif
54 #endif /*HAVE_W32_SYSTEM*/
55
56 #ifdef HAVE_STAT
57 #include <sys/stat.h> /* for stat() */
58 #endif
59
60
61
62 #include "util.h"
63 #include "sysutils.h"
64 #include "zb32.h"
65
66 /* The GnuPG homedir.  This is only accessed by the functions
67  * gnupg_homedir and gnupg_set_homedir.  Malloced.  */
68 static char *the_gnupg_homedir;
69
70 /* Flag indicating that home directory is not the default one.  */
71 static byte non_default_homedir;
72
73
74 #ifdef HAVE_W32_SYSTEM
75 /* A flag used to indicate that a control file for gpgconf has been
76    detected.  Under Windows the presence of this file indicates a
77    portable installations and triggers several changes:
78
79    - The GNUGHOME directory is fixed relative to installation
80      directory.  All other means to set the home directory are ignore.
81
82    - All registry variables will be ignored.
83
84    This flag is not used on Unix systems.
85  */
86 static byte w32_portable_app;
87 #endif /*HAVE_W32_SYSTEM*/
88
89 #ifdef HAVE_W32_SYSTEM
90 /* This flag is true if this process' binary has been installed under
91    bin and not in the root directory as often used before GnuPG 2.1. */
92 static byte w32_bin_is_bin;
93 #endif /*HAVE_W32_SYSTEM*/
94
95
96 #ifdef HAVE_W32_SYSTEM
97 static const char *w32_rootdir (void);
98 #endif
99
100
101
102 #ifdef HAVE_W32_SYSTEM
103 static void
104 w32_try_mkdir (const char *dir)
105 {
106 #ifdef HAVE_W32CE_SYSTEM
107   wchar_t *wdir = utf8_to_wchar (dir);
108   if (wdir)
109     {
110       CreateDirectory (wdir, NULL);
111       xfree (wdir);
112     }
113 #else
114   CreateDirectory (dir, NULL);
115 #endif
116 }
117 #endif
118
119
120 /* This is a helper function to load a Windows function from either of
121    one DLLs. */
122 #ifdef HAVE_W32_SYSTEM
123 static HRESULT
124 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
125 {
126   static int initialized;
127   static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
128
129   if (!initialized)
130     {
131       static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
132       void *handle;
133       int i;
134
135       initialized = 1;
136
137       for (i=0, handle = NULL; !handle && dllnames[i]; i++)
138         {
139           handle = dlopen (dllnames[i], RTLD_LAZY);
140           if (handle)
141             {
142               func = dlsym (handle, "SHGetFolderPathA");
143               if (!func)
144                 {
145                   dlclose (handle);
146                   handle = NULL;
147                 }
148             }
149         }
150     }
151
152   if (func)
153     return func (a,b,c,d,e);
154   else
155     return -1;
156 }
157 #endif /*HAVE_W32_SYSTEM*/
158
159
160 /* Check whether DIR is the default homedir.  */
161 static int
162 is_gnupg_default_homedir (const char *dir)
163 {
164   int result;
165   char *a = make_absfilename (dir, NULL);
166   char *b = make_absfilename (GNUPG_DEFAULT_HOMEDIR, NULL);
167   result = !compare_filenames (a, b);
168   xfree (b);
169   xfree (a);
170   return result;
171 }
172
173
174 /* Get the standard home directory.  In general this function should
175    not be used as it does not consider a registry value (under W32) or
176    the GNUPGHOME environment variable.  It is better to use
177    default_homedir(). */
178 const char *
179 standard_homedir (void)
180 {
181 #ifdef HAVE_W32_SYSTEM
182   static const char *dir;
183
184   if (!dir)
185     {
186       const char *rdir;
187
188       rdir = w32_rootdir ();
189       if (w32_portable_app)
190         {
191           dir = xstrconcat (rdir, DIRSEP_S "home", NULL);
192         }
193       else
194         {
195           char path[MAX_PATH];
196
197           /* It might be better to use LOCAL_APPDATA because this is
198              defined as "non roaming" and thus more likely to be kept
199              locally.  For private keys this is desired.  However,
200              given that many users copy private keys anyway forth and
201              back, using a system roaming services might be better
202              than to let them do it manually.  A security conscious
203              user will anyway use the registry entry to have better
204              control.  */
205           if (w32_shgetfolderpath (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
206                                    NULL, 0, path) >= 0)
207             {
208               char *tmp = xmalloc (strlen (path) + 6 +1);
209               strcpy (stpcpy (tmp, path), "\\gnupg");
210               dir = tmp;
211
212               /* Try to create the directory if it does not yet exists.  */
213               if (access (dir, F_OK))
214                 w32_try_mkdir (dir);
215             }
216           else
217             dir = GNUPG_DEFAULT_HOMEDIR;
218         }
219     }
220   return dir;
221 #else/*!HAVE_W32_SYSTEM*/
222   return GNUPG_DEFAULT_HOMEDIR;
223 #endif /*!HAVE_W32_SYSTEM*/
224 }
225
226 /* Set up the default home directory.  The usual --homedir option
227    should be parsed later. */
228 const char *
229 default_homedir (void)
230 {
231   const char *dir;
232
233 #ifdef HAVE_W32_SYSTEM
234   /* For a portable application we only use the standard homedir.  */
235   w32_rootdir ();
236   if (w32_portable_app)
237     return standard_homedir ();
238 #endif /*HAVE_W32_SYSTEM*/
239
240   dir = getenv ("GNUPGHOME");
241 #ifdef HAVE_W32_SYSTEM
242   if (!dir || !*dir)
243     {
244       static const char *saved_dir;
245
246       if (!saved_dir)
247         {
248           if (!dir || !*dir)
249             {
250               char *tmp, *p;
251
252               tmp = read_w32_registry_string (NULL,
253                                               GNUPG_REGISTRY_DIR,
254                                               "HomeDir");
255               if (tmp && !*tmp)
256                 {
257                   xfree (tmp);
258                   tmp = NULL;
259                 }
260               if (tmp)
261                 {
262                   /* Strip trailing backslashes.  */
263                   p = tmp + strlen (tmp) - 1;
264                   while (p > tmp && *p == '\\')
265                     *p-- = 0;
266                   saved_dir = tmp;
267                 }
268             }
269
270           if (!saved_dir)
271             saved_dir = standard_homedir ();
272         }
273       dir = saved_dir;
274     }
275 #endif /*HAVE_W32_SYSTEM*/
276
277   if (!dir || !*dir)
278     dir = GNUPG_DEFAULT_HOMEDIR;
279   else
280     {
281       /* Strip trailing slashes if any.  */
282       if (dir[strlen (dir)-1] == '/')
283         {
284           char *tmp, *p;
285
286           tmp = xstrdup (dir);
287           p = tmp + strlen (tmp) - 1;
288           while (p > tmp && *p == '/')
289             *p-- = 0;
290
291           dir = tmp;
292         }
293
294       if (!is_gnupg_default_homedir (dir))
295         non_default_homedir = 1;
296     }
297
298   return dir;
299 }
300
301
302 #ifdef HAVE_W32_SYSTEM
303 /* Check whether gpgconf is installed and if so read the gpgconf.ctl
304    file. */
305 static void
306 check_portable_app (const char *dir)
307 {
308   char *fname;
309
310   fname = xstrconcat (dir, DIRSEP_S "gpgconf.exe", NULL);
311   if (!access (fname, F_OK))
312     {
313       strcpy (fname + strlen (fname) - 3, "ctl");
314       if (!access (fname, F_OK))
315         {
316           /* gpgconf.ctl file found.  Record this fact.  */
317           w32_portable_app = 1;
318           {
319             unsigned int flags;
320             log_get_prefix (&flags);
321             log_set_prefix (NULL, (flags | GPGRT_LOG_NO_REGISTRY));
322           }
323           /* FIXME: We should read the file to detect special flags
324              and print a warning if we don't understand them  */
325         }
326     }
327   xfree (fname);
328 }
329
330
331 /* Determine the root directory of the gnupg installation on Windows.  */
332 static const char *
333 w32_rootdir (void)
334 {
335   static int got_dir;
336   static char dir[MAX_PATH+5];
337
338   if (!got_dir)
339     {
340       char *p;
341       int rc;
342       wchar_t wdir [MAX_PATH+5];
343
344       rc = GetModuleFileNameW (NULL, wdir, MAX_PATH);
345       if (rc && WideCharToMultiByte (CP_UTF8, 0, wdir, -1, dir, MAX_PATH-4,
346                                      NULL, NULL) < 0)
347         rc = 0;
348       if (!rc)
349         {
350           log_debug ("GetModuleFileName failed: %s\n", w32_strerror (-1));
351           *dir = 0;
352         }
353       got_dir = 1;
354       p = strrchr (dir, DIRSEP_C);
355       if (p)
356         {
357           *p = 0;
358
359           check_portable_app (dir);
360
361           /* If we are installed below "bin" we strip that and use
362              the top directory instead.  */
363           p = strrchr (dir, DIRSEP_C);
364           if (p && !strcmp (p+1, "bin"))
365             {
366               *p = 0;
367               w32_bin_is_bin = 1;
368             }
369         }
370       if (!p)
371         {
372           log_debug ("bad filename '%s' returned for this process\n", dir);
373           *dir = 0;
374         }
375     }
376
377   if (*dir)
378     return dir;
379   /* Fallback to the hardwired value. */
380   return GNUPG_LIBEXECDIR;
381 }
382
383 static const char *
384 w32_commondir (void)
385 {
386   static char *dir;
387
388   if (!dir)
389     {
390       const char *rdir;
391       char path[MAX_PATH];
392
393       /* Make sure that w32_rootdir has been called so that we are
394          able to check the portable application flag.  The common dir
395          is the identical to the rootdir.  In that case there is also
396          no need to strdup its value.  */
397       rdir = w32_rootdir ();
398       if (w32_portable_app)
399         return rdir;
400
401       if (w32_shgetfolderpath (NULL, CSIDL_COMMON_APPDATA,
402                                NULL, 0, path) >= 0)
403         {
404           char *tmp = xmalloc (strlen (path) + 4 +1);
405           strcpy (stpcpy (tmp, path), "\\GNU");
406           dir = tmp;
407           /* No auto create of the directory.  Either the installer or
408              the admin has to create these directories.  */
409         }
410       else
411         {
412           /* Ooops: Not defined - probably an old Windows version.
413              Use the installation directory instead.  */
414           dir = xstrdup (rdir);
415         }
416     }
417
418   return dir;
419 }
420 #endif /*HAVE_W32_SYSTEM*/
421
422
423 /* Change the homedir.  Some care must be taken to set this early
424  * enough because previous calls to gnupg_homedir may else return a
425  * different string.  */
426 void
427 gnupg_set_homedir (const char *newdir)
428 {
429   char *tmp = NULL;
430
431   if (!newdir || !*newdir)
432     newdir = default_homedir ();
433   else
434     {
435       /* Remove trailing slashes from NEWSDIR.  */
436       if (newdir[strlen (newdir)-1] == '/'
437 #ifdef HAVE_W32_SYSTEM
438           || newdir[strlen (newdir)-1] == '\\'
439 #endif
440           )
441         {
442           char *p;
443
444           tmp = xstrdup (newdir);
445           p = tmp + strlen (tmp) - 1;
446           while (p > tmp
447                  && (*p == '/'
448 #ifdef HAVE_W32_SYSTEM
449                      || *p == '\\'
450 #endif
451                      )
452                  )
453             *p-- = 0;
454
455           newdir = tmp;
456         }
457       if (!is_gnupg_default_homedir (newdir))
458         non_default_homedir = 1;
459     }
460   xfree (the_gnupg_homedir);
461   the_gnupg_homedir = make_absfilename (newdir, NULL);;
462   xfree (tmp);
463 }
464
465
466 /* Return the homedir.  The returned string is valid until another
467  * gnupg-set-homedir call.  This is always an absolute directory name.
468  * The function replaces the former global var opt.homedir.  */
469 const char *
470 gnupg_homedir (void)
471 {
472   /* If a homedir has not been set, set it to the default.  */
473   if (!the_gnupg_homedir)
474     the_gnupg_homedir = make_absfilename (default_homedir (), NULL);
475   return the_gnupg_homedir;
476 }
477
478
479 /* Return whether the home dir is the default one.  */
480 int
481 gnupg_default_homedir_p (void)
482 {
483   return !non_default_homedir;
484 }
485
486
487 /* Return the directory name used by daemons for their current working
488  * directory.  */
489 const char *
490 gnupg_daemon_rootdir (void)
491 {
492 #ifdef HAVE_W32_SYSTEM
493   static char *name;
494
495   if (!name)
496     {
497       char path[MAX_PATH];
498       size_t n;
499
500       n = GetSystemDirectoryA (path, sizeof path);
501       if (!n || n >= sizeof path)
502         name = xstrdup ("/"); /* Error - use the curret top dir instead.  */
503       else
504         name = xstrdup (path);
505     }
506
507   return name;
508
509 #else /*!HAVE_W32_SYSTEM*/
510   return "/";
511 #endif /*!HAVE_W32_SYSTEM*/
512 }
513
514
515 /* Helper for gnupg-socketdir.  This is a global function, so that
516  * gpgconf can use it for its --create-socketdir command.  If
517  * SKIP_CHECKS is set permission checks etc. are not done.  The
518  * function always returns a malloced directory name and stores these
519  * bit flags at R_INFO:
520  *
521  *   1 := Internal error, stat failed, out of core, etc.
522  *   2 := No /run/user directory.
523  *   4 := Directory not owned by the user, not a directory
524  *        or wrong permissions.
525  *   8 := Same as 4 but for the subdir.
526  *  16 := mkdir failed
527  *  32 := Non default homedir; checking subdir.
528  *  64 := Subdir does not exist.
529  * 128 := Using homedir as fallback.
530  */
531 char *
532 _gnupg_socketdir_internal (int skip_checks, unsigned *r_info)
533 {
534 #if defined(HAVE_W32_SYSTEM) || !defined(HAVE_STAT)
535
536   char *name;
537
538   (void)skip_checks;
539   *r_info = 0;
540   name = xstrdup (gnupg_homedir ());
541
542 #else /* Unix and stat(2) available. */
543
544   static const char * const bases[] = { "/run", "/var/run", NULL};
545   int i;
546   struct stat sb;
547   char prefix[13 + 1 + 20 + 6 + 1];
548   const char *s;
549   char *name = NULL;
550
551   *r_info = 0;
552
553   /* First make sure that non_default_homedir can be set.  */
554   gnupg_homedir ();
555
556   /* It has been suggested to first check XDG_RUNTIME_DIR envvar.
557    * However, the specs state that the lifetime of the directory MUST
558    * be bound to the user being logged in.  Now GnuPG may also be run
559    * as a background process with no (desktop) user logged in.  Thus
560    * we better don't do that.  */
561
562   /* Check whether we have a /run/user dir.  */
563   for (i=0; bases[i]; i++)
564     {
565       snprintf (prefix, sizeof prefix, "%s/user/%u",
566                 bases[i], (unsigned int)getuid ());
567       if (!stat (prefix, &sb) && S_ISDIR(sb.st_mode))
568         break;
569     }
570   if (!bases[i])
571     {
572       *r_info |= 2; /* No /run/user directory.  */
573       goto leave;
574     }
575
576   if (sb.st_uid != getuid ())
577     {
578       *r_info |= 4; /* Not owned by the user.  */
579       if (!skip_checks)
580         goto leave;
581     }
582
583   if (strlen (prefix) + 7 >= sizeof prefix)
584     {
585       *r_info |= 1; /* Ooops: Buffer too short to append "/gnupg".  */
586       goto leave;
587     }
588   strcat (prefix, "/gnupg");
589
590   /* Check whether the gnupg sub directory has proper permissions.  */
591   if (stat (prefix, &sb))
592     {
593       if (errno != ENOENT)
594         {
595           *r_info |= 1; /* stat failed.  */
596           goto leave;
597         }
598
599       /* Try to create the directory and check again.  */
600       if (gnupg_mkdir (prefix, "-rwx"))
601         {
602           *r_info |= 16; /* mkdir failed.  */
603           goto leave;
604         }
605       if (stat (prefix, &sb))
606         {
607           *r_info |= 1; /* stat failed.  */
608           goto leave;
609         }
610     }
611   /* Check that it is a directory, owned by the user, and only the
612    * user has permissions to use it.  */
613   if (!S_ISDIR(sb.st_mode)
614       || sb.st_uid != getuid ()
615       || (sb.st_mode & (S_IRWXG|S_IRWXO)))
616     {
617       *r_info |= 4; /* Bad permissions or not a directory. */
618       if (!skip_checks)
619         goto leave;
620     }
621
622   /* If a non default homedir is used, we check whether an
623    * corresponding sub directory below the socket dir is available
624    * and use that.  We hash the non default homedir to keep the new
625    * subdir short enough.  */
626   if (non_default_homedir)
627     {
628       char sha1buf[20];
629       char *suffix;
630
631       *r_info |= 32; /* Testing subdir.  */
632       s = gnupg_homedir ();
633       gcry_md_hash_buffer (GCRY_MD_SHA1, sha1buf, s, strlen (s));
634       suffix = zb32_encode (sha1buf, 8*15);
635       if (!suffix)
636         {
637           *r_info |= 1; /* Out of core etc. */
638           goto leave;
639         }
640       name = strconcat (prefix, "/d.", suffix, NULL);
641       xfree (suffix);
642       if (!name)
643         {
644           *r_info |= 1; /* Out of core etc. */
645           goto leave;
646         }
647
648       /* Stat that directory and check constraints.
649        * The command
650        *    gpgconf --remove-socketdir
651        * can be used to remove that directory.  */
652       if (stat (name, &sb))
653         {
654           if (errno != ENOENT)
655             *r_info |= 1; /* stat failed. */
656           else if (!skip_checks)
657             {
658               /* Try to create the directory and check again.  */
659               if (gnupg_mkdir (name, "-rwx"))
660                 *r_info |= 16; /* mkdir failed.  */
661               else if (stat (prefix, &sb))
662                 {
663                   if (errno != ENOENT)
664                     *r_info |= 1; /* stat failed. */
665                   else
666                     *r_info |= 64; /* Subdir does not exist.  */
667                 }
668               else
669                 goto leave; /* Success!  */
670             }
671           else
672             *r_info |= 64; /* Subdir does not exist.  */
673           if (!skip_checks)
674             {
675               xfree (name);
676               name = NULL;
677               goto leave;
678             }
679         }
680       else if (!S_ISDIR(sb.st_mode)
681                || sb.st_uid != getuid ()
682                || (sb.st_mode & (S_IRWXG|S_IRWXO)))
683         {
684           *r_info |= 8; /* Bad permissions or subdir is not a directory.  */
685           if (!skip_checks)
686             {
687               xfree (name);
688               name = NULL;
689               goto leave;
690             }
691         }
692     }
693   else
694     name = xstrdup (prefix);
695
696  leave:
697   /* If nothing works fall back to the homedir.  */
698   if (!name)
699     {
700       *r_info |= 128; /* Fallback.  */
701       name = xstrdup (gnupg_homedir ());
702     }
703
704 #endif /* Unix */
705
706   return name;
707 }
708
709
710 /*
711  * Return the name of the socket dir.  That is the directory used for
712  * the IPC local sockets.  This is an absolute directory name.
713  */
714 const char *
715 gnupg_socketdir (void)
716 {
717   static char *name;
718
719   if (!name)
720     {
721       unsigned int dummy;
722       name = _gnupg_socketdir_internal (0, &dummy);
723     }
724
725   return name;
726 }
727
728
729 /* Return the name of the sysconfdir.  This is a static string.  This
730    function is required because under Windows we can't simply compile
731    it in.  */
732 const char *
733 gnupg_sysconfdir (void)
734 {
735 #ifdef HAVE_W32_SYSTEM
736   static char *name;
737
738   if (!name)
739     {
740       const char *s1, *s2;
741       s1 = w32_commondir ();
742       s2 = DIRSEP_S "etc" DIRSEP_S "gnupg";
743       name = xmalloc (strlen (s1) + strlen (s2) + 1);
744       strcpy (stpcpy (name, s1), s2);
745     }
746   return name;
747 #else /*!HAVE_W32_SYSTEM*/
748   return GNUPG_SYSCONFDIR;
749 #endif /*!HAVE_W32_SYSTEM*/
750 }
751
752
753 const char *
754 gnupg_bindir (void)
755 {
756 #if defined (HAVE_W32CE_SYSTEM)
757   static char *name;
758
759   if (!name)
760     name = xstrconcat (w32_rootdir (), DIRSEP_S "bin", NULL);
761   return name;
762 #elif defined(HAVE_W32_SYSTEM)
763   const char *rdir;
764
765   rdir = w32_rootdir ();
766   if (w32_bin_is_bin)
767     {
768       static char *name;
769
770       if (!name)
771         name = xstrconcat (rdir, DIRSEP_S "bin", NULL);
772       return name;
773     }
774   else
775     return rdir;
776 #else /*!HAVE_W32_SYSTEM*/
777   return GNUPG_BINDIR;
778 #endif /*!HAVE_W32_SYSTEM*/
779 }
780
781
782 /* Return the name of the libexec directory.  The name is allocated in
783    a static area on the first use.  This function won't fail. */
784 const char *
785 gnupg_libexecdir (void)
786 {
787 #ifdef HAVE_W32_SYSTEM
788   return gnupg_bindir ();
789 #else /*!HAVE_W32_SYSTEM*/
790   return GNUPG_LIBEXECDIR;
791 #endif /*!HAVE_W32_SYSTEM*/
792 }
793
794 const char *
795 gnupg_libdir (void)
796 {
797 #ifdef HAVE_W32_SYSTEM
798   static char *name;
799
800   if (!name)
801     name = xstrconcat (w32_rootdir (), DIRSEP_S "lib" DIRSEP_S "gnupg", NULL);
802   return name;
803 #else /*!HAVE_W32_SYSTEM*/
804   return GNUPG_LIBDIR;
805 #endif /*!HAVE_W32_SYSTEM*/
806 }
807
808 const char *
809 gnupg_datadir (void)
810 {
811 #ifdef HAVE_W32_SYSTEM
812   static char *name;
813
814   if (!name)
815     name = xstrconcat (w32_rootdir (), DIRSEP_S "share" DIRSEP_S "gnupg", NULL);
816   return name;
817 #else /*!HAVE_W32_SYSTEM*/
818   return GNUPG_DATADIR;
819 #endif /*!HAVE_W32_SYSTEM*/
820 }
821
822
823 const char *
824 gnupg_localedir (void)
825 {
826 #ifdef HAVE_W32_SYSTEM
827   static char *name;
828
829   if (!name)
830     name = xstrconcat (w32_rootdir (), DIRSEP_S "share" DIRSEP_S "locale",
831                        NULL);
832   return name;
833 #else /*!HAVE_W32_SYSTEM*/
834   return LOCALEDIR;
835 #endif /*!HAVE_W32_SYSTEM*/
836 }
837
838
839 /* Return the name of the cache directory.  The name is allocated in a
840    static area on the first use.  Windows only: If the directory does
841    not exist it is created.  */
842 const char *
843 gnupg_cachedir (void)
844 {
845 #ifdef HAVE_W32_SYSTEM
846   static const char *dir;
847
848   if (!dir)
849     {
850       const char *rdir;
851
852       rdir = w32_rootdir ();
853       if (w32_portable_app)
854         {
855           dir = xstrconcat (rdir,
856                             DIRSEP_S, "var",
857                             DIRSEP_S, "cache",
858                             DIRSEP_S, "gnupg", NULL);
859         }
860       else
861         {
862           char path[MAX_PATH];
863           const char *s1[] = { "GNU", "cache", "gnupg", NULL };
864           int s1_len;
865           const char **comp;
866
867           s1_len = 0;
868           for (comp = s1; *comp; comp++)
869             s1_len += 1 + strlen (*comp);
870
871           if (w32_shgetfolderpath (NULL, CSIDL_LOCAL_APPDATA|CSIDL_FLAG_CREATE,
872                                    NULL, 0, path) >= 0)
873             {
874               char *tmp = xmalloc (strlen (path) + s1_len + 1);
875               char *p;
876
877               p = stpcpy (tmp, path);
878               for (comp = s1; *comp; comp++)
879                 {
880                   p = stpcpy (p, "\\");
881                   p = stpcpy (p, *comp);
882
883                   if (access (tmp, F_OK))
884                     w32_try_mkdir (tmp);
885                 }
886
887               dir = tmp;
888             }
889           else
890             {
891               dir = "c:\\temp\\cache\\gnupg";
892 #ifdef HAVE_W32CE_SYSTEM
893               dir += 2;
894               w32_try_mkdir ("\\temp\\cache");
895               w32_try_mkdir ("\\temp\\cache\\gnupg");
896 #endif
897             }
898         }
899     }
900   return dir;
901 #else /*!HAVE_W32_SYSTEM*/
902   return GNUPG_LOCALSTATEDIR "/cache/" PACKAGE_NAME;
903 #endif /*!HAVE_W32_SYSTEM*/
904 }
905
906
907 /* Return the user socket name used by DirMngr.  */
908 const char *
909 dirmngr_socket_name (void)
910 {
911   static char *name;
912
913   if (!name)
914     name = make_filename (gnupg_socketdir (), DIRMNGR_SOCK_NAME, NULL);
915   return name;
916 }
917
918
919 /* Return the default pinentry name.  If RESET is true the internal
920    cache is first flushed.  */
921 static const char *
922 get_default_pinentry_name (int reset)
923 {
924   static struct {
925     const char *(*rfnc)(void);
926     const char *name;
927   } names[] = {
928     /* The first entry is what we return in case we found no
929        other pinentry.  */
930     { gnupg_bindir, DIRSEP_S "pinentry" EXEEXT_S },
931 #ifdef HAVE_W32_SYSTEM
932     /* Try Gpg4win directory (with bin and without.) */
933     { w32_rootdir, "\\..\\Gpg4win\\bin\\pinentry.exe" },
934     { w32_rootdir, "\\..\\Gpg4win\\pinentry.exe" },
935     /* Try old Gpgwin directory.  */
936     { w32_rootdir, "\\..\\GNU\\GnuPG\\pinentry.exe" },
937     /* Try a Pinentry from the common GNU dir.  */
938     { w32_rootdir, "\\..\\GNU\\bin\\pinentry.exe" },
939 #endif
940     /* Last chance is a pinentry-basic (which comes with the
941        GnuPG 2.1 Windows installer).  */
942     { gnupg_bindir, DIRSEP_S "pinentry-basic" EXEEXT_S }
943   };
944   static char *name;
945
946   if (reset)
947     {
948       xfree (name);
949       name = NULL;
950     }
951
952   if (!name)
953     {
954       int i;
955
956       for (i=0; i < DIM(names); i++)
957         {
958           char *name2;
959
960           name2 = xstrconcat (names[i].rfnc (), names[i].name, NULL);
961           if (!access (name2, F_OK))
962             {
963               /* Use that pinentry.  */
964               xfree (name);
965               name = name2;
966               break;
967             }
968           if (!i) /* Store the first as fallback return.  */
969             name = name2;
970           else
971             xfree (name2);
972         }
973     }
974
975   return name;
976 }
977
978
979 /* If set, 'gnupg_module_name' returns modules from that build
980  * directory.  */
981 static char *gnupg_build_directory;
982
983 /* For sanity checks.  */
984 static int gnupg_module_name_called;
985
986
987 /* Set NEWDIR as the new build directory.  This will make
988  * 'gnupg_module_name' return modules from that build directory.  Must
989  * be called before any invocation of 'gnupg_module_name', and must
990  * not be called twice.  It can be used by test suites to make sure
991  * the components from the build directory are used instead of
992  * potentially outdated installed ones.  */
993 void
994 gnupg_set_builddir (const char *newdir)
995 {
996   log_assert (! gnupg_module_name_called);
997   log_assert (! gnupg_build_directory);
998   gnupg_build_directory = xtrystrdup (newdir);
999 }
1000
1001
1002 /* If no build directory has been configured, try to set it from the
1003  * environment.  We only do this in development builds to avoid
1004  * increasing the set of influential environment variables and hence
1005  * the attack surface of production builds.  */
1006 static void
1007 gnupg_set_builddir_from_env (void)
1008 {
1009 #if defined(IS_DEVELOPMENT_VERSION) || defined(ENABLE_GNUPG_BUILDDIR_ENVVAR)
1010   if (gnupg_build_directory)
1011     return;
1012
1013   gnupg_build_directory = getenv ("GNUPG_BUILDDIR");
1014 #endif
1015 }
1016
1017
1018 /* Return the file name of a helper tool.  WHICH is one of the
1019    GNUPG_MODULE_NAME_foo constants.  */
1020 const char *
1021 gnupg_module_name (int which)
1022 {
1023   gnupg_set_builddir_from_env ();
1024   gnupg_module_name_called = 1;
1025
1026 #define X(a,b,c) do {                                                   \
1027     static char *name;                                                  \
1028     if (!name)                                                          \
1029       name = gnupg_build_directory                                      \
1030         ? xstrconcat (gnupg_build_directory,                            \
1031                       DIRSEP_S b DIRSEP_S c EXEEXT_S, NULL)             \
1032         : xstrconcat (gnupg_ ## a (), DIRSEP_S c EXEEXT_S, NULL);       \
1033     return name;                                                        \
1034   } while (0)
1035
1036   switch (which)
1037     {
1038     case GNUPG_MODULE_NAME_AGENT:
1039 #ifdef GNUPG_DEFAULT_AGENT
1040       return GNUPG_DEFAULT_AGENT;
1041 #else
1042       X(bindir, "agent", "gpg-agent");
1043 #endif
1044
1045     case GNUPG_MODULE_NAME_PINENTRY:
1046 #ifdef GNUPG_DEFAULT_PINENTRY
1047       return GNUPG_DEFAULT_PINENTRY;  /* (Set by a configure option) */
1048 #else
1049       return get_default_pinentry_name (0);
1050 #endif
1051
1052     case GNUPG_MODULE_NAME_SCDAEMON:
1053 #ifdef GNUPG_DEFAULT_SCDAEMON
1054       return GNUPG_DEFAULT_SCDAEMON;
1055 #else
1056       X(libexecdir, "scd", "scdaemon");
1057 #endif
1058
1059     case GNUPG_MODULE_NAME_DIRMNGR:
1060 #ifdef GNUPG_DEFAULT_DIRMNGR
1061       return GNUPG_DEFAULT_DIRMNGR;
1062 #else
1063       X(bindir, "dirmngr", DIRMNGR_NAME);
1064 #endif
1065
1066     case GNUPG_MODULE_NAME_PROTECT_TOOL:
1067 #ifdef GNUPG_DEFAULT_PROTECT_TOOL
1068       return GNUPG_DEFAULT_PROTECT_TOOL;
1069 #else
1070       X(libexecdir, "agent", "gpg-protect-tool");
1071 #endif
1072
1073     case GNUPG_MODULE_NAME_DIRMNGR_LDAP:
1074 #ifdef GNUPG_DEFAULT_DIRMNGR_LDAP
1075       return GNUPG_DEFAULT_DIRMNGR_LDAP;
1076 #else
1077       X(libexecdir, "dirmngr", "dirmngr_ldap");
1078 #endif
1079
1080     case GNUPG_MODULE_NAME_CHECK_PATTERN:
1081       X(libexecdir, "tools", "gpg-check-pattern");
1082
1083     case GNUPG_MODULE_NAME_GPGSM:
1084       X(bindir, "sm", "gpgsm");
1085
1086     case GNUPG_MODULE_NAME_GPG:
1087 #if USE_GPG2_HACK
1088       if (! gnupg_build_directory)
1089         X(bindir, "g10", GPG_NAME "2");
1090       else
1091 #endif
1092         X(bindir, "g10", GPG_NAME);
1093
1094     case GNUPG_MODULE_NAME_GPGV:
1095 #if USE_GPG2_HACK
1096       if (! gnupg_build_directory)
1097         X(bindir, "g10", GPG_NAME "v2");
1098       else
1099 #endif
1100         X(bindir, "g10", GPG_NAME "v");
1101
1102     case GNUPG_MODULE_NAME_CONNECT_AGENT:
1103       X(bindir, "tools", "gpg-connect-agent");
1104
1105     case GNUPG_MODULE_NAME_GPGCONF:
1106       X(bindir, "tools", "gpgconf");
1107
1108     default:
1109       BUG ();
1110     }
1111 #undef X
1112 }
1113
1114
1115 /* Flush some of the cached module names.  This is for example used by
1116    gpg-agent to allow configuring a different pinentry.  */
1117 void
1118 gnupg_module_name_flush_some (void)
1119 {
1120   (void)get_default_pinentry_name (1);
1121 }