7b6b4aea0bde4ab0294ec98688f80197c01149d0
[platform/upstream/gpg2.git] / common / init.c
1 /* init.c - Various initializations
2  *      Copyright (C) 2007 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * This file is free software; you can redistribute it and/or modify
7  * it under the terms of either
8  *
9  *   - the GNU Lesser General Public License as published by the Free
10  *     Software Foundation; either version 3 of the License, or (at
11  *     your option) any later version.
12  *
13  * or
14  *
15  *   - the GNU General Public License as published by the Free
16  *     Software Foundation; either version 2 of the License, or (at
17  *     your option) any later version.
18  *
19  * or both in parallel, as here.
20  *
21  * This file is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program; if not, see <https://www.gnu.org/licenses/>.
28  */
29
30 #include <config.h>
31
32 #ifdef HAVE_W32_SYSTEM
33 # ifdef HAVE_WINSOCK2_H
34 #  include <winsock2.h>
35 # endif
36 # include <windows.h>
37 #endif
38 #ifdef HAVE_W32CE_SYSTEM
39 # include <assuan.h> /* For _assuan_w32ce_finish_pipe. */
40 #endif
41
42 #include <gcrypt.h>
43 #include "util.h"
44 #include "i18n.h"
45 #include "w32help.h"
46
47 /* This object is used to register memory cleanup functions.
48    Technically they are not needed but they can avoid frequent
49    questions about un-released memory.  Note that we use the system
50    malloc and not any wrappers.  */
51 struct mem_cleanup_item_s;
52 typedef struct mem_cleanup_item_s *mem_cleanup_item_t;
53
54 struct mem_cleanup_item_s
55 {
56   mem_cleanup_item_t next;
57   void (*func) (void);
58 };
59
60 static mem_cleanup_item_t mem_cleanup_list;
61
62
63 /* The default error source of the application.  This is different
64    from GPG_ERR_SOURCE_DEFAULT in that it does not depend on the
65    source file and thus is usable in code shared by applications.
66    Note that we need to initialize it because otherwise some linkers
67    (OS X at least) won't find the symbol when linking the t-*.c
68    files.  */
69 gpg_err_source_t default_errsource = 0;
70
71
72 #ifdef HAVE_W32CE_SYSTEM
73 static void parse_std_file_handles (int *argcp, char ***argvp);
74 static void
75 sleep_on_exit (void)
76 {
77   /* The sshd on CE swallows some of the command output.  Sleeping a
78      while usually helps.  */
79   Sleep (400);
80 }
81 #endif /*HAVE_W32CE_SYSTEM*/
82
83 #if HAVE_W32_SYSTEM
84 static void prepare_w32_commandline (int *argcp, char ***argvp);
85 #endif /*HAVE_W32_SYSTEM*/
86
87
88
89 static void
90 run_mem_cleanup (void)
91 {
92   mem_cleanup_item_t next;
93
94   while (mem_cleanup_list)
95     {
96       next = mem_cleanup_list->next;
97       mem_cleanup_list->func ();
98       free (mem_cleanup_list);
99       mem_cleanup_list = next;
100     }
101 }
102
103
104 void
105 register_mem_cleanup_func (void (*func)(void))
106 {
107   mem_cleanup_item_t item;
108
109   for (item = mem_cleanup_list; item; item = item->next)
110     if (item->func == func)
111       return; /* Function has already been registered.  */
112
113   item = malloc (sizeof *item);
114   if (item)
115     {
116       item->func = func;
117       item->next = mem_cleanup_list;
118       mem_cleanup_list = item;
119     }
120 }
121
122
123 /* If STRING is not NULL write string to es_stdout or es_stderr.  MODE
124    must be 1 or 2.  If STRING is NULL flush the respective stream.  */
125 static int
126 writestring_via_estream (int mode, const char *string)
127 {
128   if (mode == 1 || mode == 2)
129     {
130       if (string)
131         return es_fputs (string, mode == 1? es_stdout : es_stderr);
132       else
133         return es_fflush (mode == 1? es_stdout : es_stderr);
134     }
135   else
136     return -1;
137 }
138
139
140 /* This function should be the first called after main.  */
141 void
142 early_system_init (void)
143 {
144 }
145
146
147 /* This function is to be used early at program startup to make sure
148    that some subsystems are initialized.  This is in particular
149    important for W32 to initialize the sockets so that our socket
150    emulation code used directly as well as in libassuan may be used.
151    It should best be called before any I/O is done so that setup
152    required for logging is ready.  ARGCP and ARGVP are the addresses
153    of the parameters given to main.  This function may modify them.
154
155    This function should be called only via the macro
156    init_common_subsystems.
157
158    CAUTION: This might be called while running suid(root).  */
159 void
160 _init_common_subsystems (gpg_err_source_t errsource, int *argcp, char ***argvp)
161 {
162   /* Store the error source in a global variable. */
163   default_errsource = errsource;
164
165   atexit (run_mem_cleanup);
166
167   /* Try to auto set the character set.  */
168   set_native_charset (NULL);
169
170 #ifdef HAVE_W32_SYSTEM
171   /* For W32 we need to initialize the socket layer.  This is because
172      we use recv and send in libassuan as well as at some other
173      places.  */
174   {
175     WSADATA wsadat;
176
177     WSAStartup (0x202, &wsadat);
178   }
179 #endif
180
181 #ifdef HAVE_W32CE_SYSTEM
182   /* Register the sleep exit function before the estream init so that
183      the sleep will be called after the estream registered atexit
184      function which flushes the left open estream streams and in
185      particular es_stdout.  */
186   atexit (sleep_on_exit);
187 #endif
188
189   if (!gcry_check_version (NEED_LIBGCRYPT_VERSION))
190     {
191       log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
192                  NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL));
193     }
194
195   /* Initialize the Estream library. */
196   gpgrt_init ();
197   gpgrt_set_alloc_func (gcry_realloc);
198
199 #ifdef HAVE_W32CE_SYSTEM
200   /* Special hack for Windows CE: We extract some options from arg
201      to setup the standard handles.  */
202   parse_std_file_handles (argcp, argvp);
203 #endif
204
205 #ifdef HAVE_W32_SYSTEM
206   /* We want gettext to always output UTF-8 and we put the console in
207    * utf-8 mode.  */
208   gettext_use_utf8 (1);
209   if (!SetConsoleCP (CP_UTF8) || !SetConsoleOutputCP (CP_UTF8))
210     {
211       log_info ("SetConsoleCP failed: %s\n", w32_strerror (-1));
212       log_info ("Warning: Garbled console data possible\n");
213     }
214 #endif
215
216   /* Access the standard estreams as early as possible.  If we don't
217      do this the original stdio streams may have been closed when
218      _es_get_std_stream is first use and in turn it would connect to
219      the bit bucket.  */
220   {
221     int i;
222     for (i=0; i < 3; i++)
223       (void)_gpgrt_get_std_stream (i);
224   }
225
226   /* --version et al shall use estream as well.  */
227   gpgrt_set_usage_outfnc (writestring_via_estream);
228
229   /* Register our string mapper with gpgrt.  */
230   gpgrt_set_fixed_string_mapper (map_static_macro_string);
231
232   /* Logging shall use the standard socket directory as fallback.  */
233   log_set_socket_dir_cb (gnupg_socketdir);
234
235 #if HAVE_W32_SYSTEM
236   /* For Standard Windows we use our own parser for the command line
237    * so that we can return an array of utf-8 encoded strings.  */
238   prepare_w32_commandline (argcp, argvp);
239 #else
240   (void)argcp;
241   (void)argvp;
242 #endif
243
244 }
245
246
247
248 /* WindowsCE uses a very strange way of handling the standard streams.
249    There is a function SetStdioPath to associate a standard stream
250    with a file or a device but what we really want is to use pipes as
251    standard streams.  Despite that we implement pipes using a device,
252    we would have some limitations on the number of open pipes due to
253    the 3 character limit of device file name.  Thus we don't take this
254    path.  Another option would be to install a file system driver with
255    support for pipes; this would allow us to get rid of the device
256    name length limitation.  However, with GnuPG we can get away be
257    redefining the standard streams and passing the handles to be used
258    on the command line.  This has also the advantage that it makes
259    creating a process much easier and does not require the
260    SetStdioPath set and restore game.  The caller needs to pass the
261    rendezvous ids using up to three options:
262
263      -&S0=<rvid> -&S1=<rvid> -&S2=<rvid>
264
265    They are all optional but they must be the first arguments on the
266    command line.  Parsing stops as soon as an invalid option is found.
267    These rendezvous ids are then used to finish the pipe creation.*/
268 #ifdef HAVE_W32CE_SYSTEM
269 static void
270 parse_std_file_handles (int *argcp, char ***argvp)
271 {
272   int argc = *argcp;
273   char **argv = *argvp;
274   const char *s;
275   assuan_fd_t fd;
276   int i;
277   int fixup = 0;
278
279   if (!argc)
280     return;
281
282   for (argc--, argv++; argc; argc--, argv++)
283     {
284       s = *argv;
285       if (*s == '-' && s[1] == '&' && s[2] == 'S'
286           && (s[3] == '0' || s[3] == '1' || s[3] == '2')
287           && s[4] == '='
288           && (strchr ("-01234567890", s[5]) || !strcmp (s+5, "null")))
289         {
290           if (s[5] == 'n')
291             fd = ASSUAN_INVALID_FD;
292           else
293             fd = _assuan_w32ce_finish_pipe (atoi (s+5), s[3] != '0');
294           _es_set_std_fd (s[3] - '0', (int)fd);
295           fixup++;
296         }
297       else
298         break;
299     }
300
301   if (fixup)
302     {
303       argc = *argcp;
304       argc -= fixup;
305       *argcp = argc;
306
307       argv = *argvp;
308       for (i=1; i < argc; i++)
309         argv[i] = argv[i + fixup];
310       for (; i < argc + fixup; i++)
311         argv[i] = NULL;
312     }
313
314
315 }
316 #endif /*HAVE_W32CE_SYSTEM*/
317
318
319 /* For Windows we need to parse the command line so that we can
320  * provide an UTF-8 encoded argv.  If there is any Unicode character
321  * we return a new array but if there is no Unicode character we do
322  * nothing.  */
323 #ifdef HAVE_W32_SYSTEM
324 static void
325 prepare_w32_commandline (int *r_argc, char ***r_argv)
326 {
327   const wchar_t *wcmdline, *ws;
328   char *cmdline;
329   int argc;
330   char **argv;
331   const char *s;
332   int i, globing, itemsalloced;
333
334   s = gpgrt_strusage (95);
335   globing = (s && *s == '1');
336
337   wcmdline = GetCommandLineW ();
338   if (!wcmdline)
339     {
340       log_error ("GetCommandLineW failed\n");
341       return;  /* Ooops.  */
342     }
343
344   if (!globing)
345     {
346       /* If globbing is not enabled we use our own parser only if
347        * there are any non-ASCII characters.  */
348       for (ws=wcmdline; *ws; ws++)
349         if (!iswascii (*ws))
350           break;
351       if (!*ws)
352         return;  /* No Unicode - return directly.  */
353     }
354
355   cmdline = wchar_to_utf8 (wcmdline);
356   if (!cmdline)
357     {
358       log_error ("parsing command line failed: %s\n", strerror (errno));
359       return;  /* Ooops.  */
360     }
361   gpgrt_annotate_leaked_object (cmdline);
362
363   argv = w32_parse_commandline (cmdline, globing, &argc, &itemsalloced);
364   if (!argv)
365     {
366       log_error ("parsing command line failed: %s\n", "internal error");
367       return;  /* Ooops.  */
368     }
369   gpgrt_annotate_leaked_object (argv);
370   if (itemsalloced)
371     {
372       for (i=0; i < argc; i++)
373         gpgrt_annotate_leaked_object (argv[i]);
374     }
375   *r_argv = argv;
376   *r_argc = argc;
377 }
378 #endif /*HAVE_W32_SYSTEM*/