2002-04-24 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / scdaemon.c
bloba6f18cc36df34ce77b38df6cb8a03db3fe51da1d
1 /* scdaemon.c - The GnuPG Smartcard Daemon
2 * Copyright (C) 2001, 2002 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
21 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stddef.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <time.h>
31 #include <fcntl.h>
32 #include <sys/socket.h>
33 #include <sys/un.h>
34 #include <unistd.h>
35 #include <signal.h>
37 #include <ksba.h>
38 #include <gcrypt.h>
40 #define JNLIB_NEED_LOG_LOGV
41 #include "scdaemon.h"
42 #include "../assuan/assuan.h" /* malloc hooks */
44 #include "sysutils.h"
47 #define N_(a) a
48 #define _(a) a
51 enum cmd_and_opt_values
52 { aNull = 0,
53 oCsh = 'c',
54 oQuiet = 'q',
55 oSh = 's',
56 oVerbose = 'v',
58 oNoVerbose = 500,
59 oOptions,
60 oDebug,
61 oDebugAll,
62 oDebugWait,
63 oDebugSC,
64 oNoGreeting,
65 oNoOptions,
66 oHomedir,
67 oNoDetach,
68 oNoGrab,
69 oLogFile,
70 oServer,
71 oBatch,
73 aTest };
77 static ARGPARSE_OPTS opts[] = {
79 { 301, NULL, 0, N_("@Options:\n ") },
81 { oServer, "server", 0, N_("run in server mode") },
82 { oVerbose, "verbose", 0, N_("verbose") },
83 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
84 { oSh, "sh", 0, N_("sh-style command output") },
85 { oCsh, "csh", 0, N_("csh-style command output") },
86 { oOptions, "options" , 2, N_("read options from file")},
87 { oDebug, "debug" ,4|16, N_("set debugging flags")},
88 { oDebugAll, "debug-all" ,0, N_("enable full debugging")},
89 { oDebugWait,"debug-wait",1, "@"},
90 { oDebugSC, "debug-sc", 1, N_("N|set OpenSC debug level to N")},
91 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
92 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
95 {0}
99 static volatile int caught_fatal_sig = 0;
101 /* It is possible that we are currently running under setuid permissions */
102 static int maybe_setuid = 1;
104 /* Name of the communication socket */
105 static char socket_name[128];
107 static const char *
108 my_strusage (int level)
110 const char *p;
111 switch (level)
113 case 11: p = "scdaemon (GnuPG)";
114 break;
115 case 13: p = VERSION; break;
116 case 17: p = PRINTABLE_OS_NAME; break;
117 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
118 break;
119 case 1:
120 case 40: p = _("Usage: scdaemon [options] (-h for help)");
121 break;
122 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
123 "Smartcard daemon for GnuPG\n");
124 break;
126 default: p = NULL;
128 return p;
133 static void
134 i18n_init (void)
136 #ifdef USE_SIMPLE_GETTEXT
137 set_gettext_file( PACKAGE );
138 #else
139 #ifdef ENABLE_NLS
140 /* gtk_set_locale (); HMMM: We have not yet called gtk_init */
141 bindtextdomain( PACKAGE, GNUPG_LOCALEDIR );
142 textdomain( PACKAGE );
143 #endif
144 #endif
149 /* Used by gcry for logging */
150 static void
151 my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr)
153 /* translate the log levels */
154 switch (level)
156 case GCRY_LOG_CONT: level = JNLIB_LOG_CONT; break;
157 case GCRY_LOG_INFO: level = JNLIB_LOG_INFO; break;
158 case GCRY_LOG_WARN: level = JNLIB_LOG_WARN; break;
159 case GCRY_LOG_ERROR:level = JNLIB_LOG_ERROR; break;
160 case GCRY_LOG_FATAL:level = JNLIB_LOG_FATAL; break;
161 case GCRY_LOG_BUG: level = JNLIB_LOG_BUG; break;
162 case GCRY_LOG_DEBUG:level = JNLIB_LOG_DEBUG; break;
163 default: level = JNLIB_LOG_ERROR; break;
165 log_logv (level, fmt, arg_ptr);
169 static void
170 cleanup (void)
172 if (*socket_name)
174 char *p;
176 remove (socket_name);
177 p = strrchr (socket_name, '/');
178 if (p)
180 *p = 0;
181 rmdir (socket_name);
182 *p = '/';
184 *socket_name = 0;
189 static RETSIGTYPE
190 cleanup_sh (int sig)
192 if (caught_fatal_sig)
193 raise (sig);
194 caught_fatal_sig = 1;
196 /* gcry_control( GCRYCTL_TERM_SECMEM );*/
197 cleanup ();
199 #ifndef HAVE_DOSISH_SYSTEM
200 { /* reset action to default action and raise signal again */
201 struct sigaction nact;
202 nact.sa_handler = SIG_DFL;
203 sigemptyset( &nact.sa_mask );
204 nact.sa_flags = 0;
205 sigaction( sig, &nact, NULL);
207 #endif
208 raise( sig );
212 main (int argc, char **argv )
214 ARGPARSE_ARGS pargs;
215 int orig_argc;
216 int may_coredump;
217 char **orig_argv;
218 FILE *configfp = NULL;
219 char *configname = NULL;
220 const char *shell;
221 unsigned configlineno;
222 int parse_debug = 0;
223 int default_config =1;
224 int greeting = 0;
225 int nogreeting = 0;
226 int pipe_server = 0;
227 int nodetach = 0;
228 int csh_style = 0;
229 char *logfile = NULL;
230 int debug_wait = 0;
232 set_strusage (my_strusage);
233 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
234 /* Please note that we may running SUID(ROOT), so be very CAREFUL
235 when adding any stuff between here and the call to INIT_SECMEM()
236 somewhere after the option parsing */
237 log_set_prefix ("scdaemon", 1|4);
238 i18n_init ();
240 /* check that the libraries are suitable. Do it here because
241 the option parsing may need services of the library */
242 if (!gcry_check_version ( "1.1.5" ) )
244 log_fatal( _("libgcrypt is too old (need %s, have %s)\n"),
245 "1.1.5", gcry_check_version (NULL) );
248 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
249 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
250 gcry_set_log_handler (my_gcry_logger, NULL);
251 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
253 may_coredump = disable_core_dumps ();
255 shell = getenv ("SHELL");
256 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
257 csh_style = 1;
259 /* FIXME: Using this homedir option does only make sense when not
260 running as a system service. We might want to check for this by
261 looking at the uid or ebtter use an explict option for this */
262 opt.homedir = getenv("GNUPGHOME");
263 if (!opt.homedir || !*opt.homedir)
265 #ifdef HAVE_DRIVE_LETTERS
266 opt.homedir = "c:/gnupg-test";
267 #else
268 opt.homedir = "~/.gnupg-test";
269 #endif
272 /* check whether we have a config file on the commandline */
273 orig_argc = argc;
274 orig_argv = argv;
275 pargs.argc = &argc;
276 pargs.argv = &argv;
277 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
278 while (arg_parse( &pargs, opts))
280 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
281 parse_debug++;
282 else if (pargs.r_opt == oOptions)
283 { /* yes there is one, so we do not try the default one, but
284 read the option file when it is encountered at the
285 commandline */
286 default_config = 0;
288 else if (pargs.r_opt == oNoOptions)
289 default_config = 0; /* --no-options */
290 else if (pargs.r_opt == oHomedir)
291 opt.homedir = pargs.r.ret_str;
294 /* initialize the secure memory. */
295 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
296 maybe_setuid = 0;
299 Now we are working under our real uid
303 if (default_config)
304 configname = make_filename (opt.homedir, "scdaemon.conf", NULL );
306 argc = orig_argc;
307 argv = orig_argv;
308 pargs.argc = &argc;
309 pargs.argv = &argv;
310 pargs.flags= 1; /* do not remove the args */
311 next_pass:
312 if (configname)
314 configlineno = 0;
315 configfp = fopen (configname, "r");
316 if (!configfp)
318 if (default_config)
320 if( parse_debug )
321 log_info (_("NOTE: no default option file `%s'\n"),
322 configname );
324 else
326 log_error (_("option file `%s': %s\n"),
327 configname, strerror(errno) );
328 exit(2);
330 xfree (configname);
331 configname = NULL;
333 if (parse_debug && configname )
334 log_info (_("reading options from `%s'\n"), configname );
335 default_config = 0;
338 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
340 switch (pargs.r_opt)
342 case oQuiet: opt.quiet = 1; break;
343 case oVerbose: opt.verbose++; break;
344 case oBatch: opt.batch=1; break;
346 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
347 case oDebugAll: opt.debug = ~0; break;
348 case oDebugWait: debug_wait = pargs.r.ret_int; break;
349 case oDebugSC: opt.debug_sc = pargs.r.ret_int; break;
351 case oOptions:
352 /* config files may not be nested (silently ignore them) */
353 if (!configfp)
355 xfree(configname);
356 configname = xstrdup(pargs.r.ret_str);
357 goto next_pass;
359 break;
360 case oNoGreeting: nogreeting = 1; break;
361 case oNoVerbose: opt.verbose = 0; break;
362 case oNoOptions: break; /* no-options */
363 case oHomedir: opt.homedir = pargs.r.ret_str; break;
364 case oNoDetach: nodetach = 1; break;
365 case oLogFile: logfile = pargs.r.ret_str; break;
366 case oCsh: csh_style = 1; break;
367 case oSh: csh_style = 0; break;
368 case oServer: pipe_server = 1; break;
370 default : pargs.err = configfp? 1:2; break;
373 if (configfp)
375 fclose( configfp );
376 configfp = NULL;
377 xfree(configname);
378 configname = NULL;
379 goto next_pass;
381 xfree (configname);
382 configname = NULL;
383 if (log_get_errorcount(0))
384 exit(2);
385 if (nogreeting )
386 greeting = 0;
388 if (greeting)
390 fprintf (stderr, "%s %s; %s\n",
391 strusage(11), strusage(13), strusage(14) );
392 fprintf (stderr, "%s\n", strusage(15) );
394 #ifdef IS_DEVELOPMENT_VERSION
395 log_info ("NOTE: this is a development version!\n");
396 #endif
399 if (atexit (cleanup))
401 log_error ("atexit failed\n");
402 cleanup ();
403 exit (1);
406 if (debug_wait && pipe_server)
408 log_debug ("waiting for debugger - my pid is %u .....\n",
409 (unsigned int)getpid());
410 sleep (debug_wait);
411 log_debug ("... okay\n");
414 /* now start with logging to a file if this is desired */
415 if (logfile)
417 log_set_file (logfile);
418 log_set_prefix (NULL, 1|2|4);
422 if (pipe_server)
423 { /* this is the simple pipe based server */
424 scd_command_handler (-1);
426 else
427 { /* regular server mode */
428 int fd;
429 pid_t pid;
430 int i;
431 int len;
432 struct sockaddr_un serv_addr;
433 char *p;
435 /* fixme: if there is already a running gpg-agent we should
436 sahre the same directory - and vice versa */
437 *socket_name = 0;
438 snprintf (socket_name, DIM(socket_name)-1,
439 "/tmp/gpg-XXXXXX/S.scdaemon");
440 socket_name[DIM(socket_name)-1] = 0;
441 p = strrchr (socket_name, '/');
442 if (!p)
443 BUG ();
444 *p = 0;;
445 if (!mkdtemp(socket_name))
447 log_error ("can't create directory `%s': %s\n",
448 socket_name, strerror(errno) );
449 exit (1);
451 *p = '/';
453 if (strchr (socket_name, ':') )
455 log_error ("colons are not allowed in the socket name\n");
456 exit (1);
458 if (strlen (socket_name)+1 >= sizeof serv_addr.sun_path )
460 log_error ("name of socket to long\n");
461 exit (1);
465 fd = socket (AF_UNIX, SOCK_STREAM, 0);
466 if (fd == -1)
468 log_error ("can't create socket: %s\n", strerror(errno) );
469 exit (1);
472 memset (&serv_addr, 0, sizeof serv_addr);
473 serv_addr.sun_family = AF_UNIX;
474 strcpy (serv_addr.sun_path, socket_name);
475 len = (offsetof (struct sockaddr_un, sun_path)
476 + strlen(serv_addr.sun_path) + 1);
478 if (bind (fd, (struct sockaddr*)&serv_addr, len) == -1)
480 log_error ("error binding socket to `%s': %s\n",
481 serv_addr.sun_path, strerror (errno) );
482 close (fd);
483 exit (1);
486 if (listen (fd, 5 ) == -1)
488 log_error ("listen() failed: %s\n", strerror (errno));
489 close (fd);
490 exit (1);
493 if (opt.verbose)
494 log_info ("listening on socket `%s'\n", socket_name );
497 fflush (NULL);
498 pid = fork ();
499 if (pid == (pid_t)-1)
501 log_fatal ("fork failed: %s\n", strerror (errno) );
502 exit (1);
504 else if (pid)
505 { /* we are the parent */
506 char *infostr;
508 close (fd);
510 /* create the info string: <name>:<pid>:<protocol_version> */
511 if (asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
512 socket_name, (ulong)pid ) < 0)
514 log_error ("out of core\n");
515 kill (pid, SIGTERM);
516 exit (1);
518 *socket_name = 0; /* don't let cleanup() remove the socket -
519 the child should do this from now on */
520 if (argc)
521 { /* run the program given on the commandline */
522 if (putenv (infostr))
524 log_error ("failed to set environment: %s\n",
525 strerror (errno) );
526 kill (pid, SIGTERM );
527 exit (1);
529 execvp (argv[0], argv);
530 log_error ("failed to run the command: %s\n", strerror (errno));
531 kill (pid, SIGTERM);
532 exit (1);
534 else
536 /* print the environment string, so that the caller can use
537 shell's eval to set it */
538 if (csh_style)
540 *strchr (infostr, '=') = ' ';
541 printf ( "setenv %s\n", infostr);
543 else
545 printf ( "%s; export SCDAEMON_INFO;\n", infostr);
547 free (infostr);
548 exit (0);
550 /* NOTREACHED */
551 } /* end parent */
553 /* this is the child */
555 /* detach from tty and put process into a new session */
556 if (!nodetach )
557 { /* close stdin, stdout and stderr unless it is the log stream */
558 for (i=0; i <= 2; i++)
560 if ( log_get_fd () != i)
561 close (i);
563 if (setsid() == -1)
565 log_error ("setsid() failed: %s\n", strerror(errno) );
566 cleanup ();
567 exit (1);
571 /* setup signals */
573 struct sigaction oact, nact;
575 nact.sa_handler = cleanup_sh;
576 sigemptyset (&nact.sa_mask);
577 nact.sa_flags = 0;
579 sigaction (SIGHUP, NULL, &oact);
580 if (oact.sa_handler != SIG_IGN)
581 sigaction (SIGHUP, &nact, NULL);
582 sigaction( SIGTERM, NULL, &oact );
583 if (oact.sa_handler != SIG_IGN)
584 sigaction (SIGTERM, &nact, NULL);
585 nact.sa_handler = SIG_IGN;
586 sigaction (SIGPIPE, &nact, NULL);
587 sigaction (SIGINT, &nact, NULL);
590 if (chdir("/"))
592 log_error ("chdir to / failed: %s\n", strerror (errno));
593 exit (1);
596 scd_command_handler (fd);
598 close (fd);
601 return 0;
604 void
605 scd_exit (int rc)
607 #if 0
608 #warning no update_random_seed_file
609 update_random_seed_file();
610 #endif
611 #if 0
612 /* at this time a bit annoying */
613 if (opt.debug & DBG_MEMSTAT_VALUE)
615 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
616 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
618 if (opt.debug)
619 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
620 #endif
621 gcry_control (GCRYCTL_TERM_SECMEM );
622 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
623 exit (rc);
627 void
628 scd_init_default_ctrl (CTRL ctrl)