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
32 #include <sys/socket.h>
40 #define JNLIB_NEED_LOG_LOGV
42 #include "../assuan/assuan.h" /* malloc hooks */
51 enum cmd_and_opt_values
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")},
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];
108 my_strusage (int level
)
113 case 11: p
= "scdaemon (GnuPG)";
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");
120 case 40: p
= _("Usage: scdaemon [options] (-h for help)");
122 case 41: p
= _("Syntax: scdaemon [options] [command [args]]\n"
123 "Smartcard daemon for GnuPG\n");
136 #ifdef USE_SIMPLE_GETTEXT
137 set_gettext_file( PACKAGE
);
140 /* gtk_set_locale (); HMMM: We have not yet called gtk_init */
141 bindtextdomain( PACKAGE
, GNUPG_LOCALEDIR
);
142 textdomain( PACKAGE
);
149 /* Used by gcry for logging */
151 my_gcry_logger (void *dummy
, int level
, const char *fmt
, va_list arg_ptr
)
153 /* translate the log levels */
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
);
176 remove (socket_name
);
177 p
= strrchr (socket_name
, '/');
192 if (caught_fatal_sig
)
194 caught_fatal_sig
= 1;
196 /* gcry_control( GCRYCTL_TERM_SECMEM );*/
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
);
205 sigaction( sig
, &nact
, NULL
);
212 main (int argc
, char **argv
)
218 FILE *configfp
= NULL
;
219 char *configname
= NULL
;
221 unsigned configlineno
;
223 int default_config
=1;
229 char *logfile
= NULL
;
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);
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") )
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";
268 opt
.homedir
= "~/.gnupg-test";
272 /* check whether we have a config file on the commandline */
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
)
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
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);
299 Now we are working under our real uid
304 configname
= make_filename (opt
.homedir
, "scdaemon.conf", NULL
);
310 pargs
.flags
= 1; /* do not remove the args */
315 configfp
= fopen (configname
, "r");
321 log_info (_("NOTE: no default option file `%s'\n"),
326 log_error (_("option file `%s': %s\n"),
327 configname
, strerror(errno
) );
333 if (parse_debug
&& configname
)
334 log_info (_("reading options from `%s'\n"), configname
);
338 while (optfile_parse( configfp
, configname
, &configlineno
, &pargs
, opts
) )
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;
352 /* config files may not be nested (silently ignore them) */
356 configname
= xstrdup(pargs
.r
.ret_str
);
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;
383 if (log_get_errorcount(0))
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");
399 if (atexit (cleanup
))
401 log_error ("atexit failed\n");
406 if (debug_wait
&& pipe_server
)
408 log_debug ("waiting for debugger - my pid is %u .....\n",
409 (unsigned int)getpid());
411 log_debug ("... okay\n");
414 /* now start with logging to a file if this is desired */
417 log_set_file (logfile
);
418 log_set_prefix (NULL
, 1|2|4);
423 { /* this is the simple pipe based server */
424 scd_command_handler (-1);
427 { /* regular server mode */
432 struct sockaddr_un serv_addr
;
435 /* fixme: if there is already a running gpg-agent we should
436 sahre the same directory - and vice versa */
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
, '/');
445 if (!mkdtemp(socket_name
))
447 log_error ("can't create directory `%s': %s\n",
448 socket_name
, strerror(errno
) );
453 if (strchr (socket_name
, ':') )
455 log_error ("colons are not allowed in the socket name\n");
458 if (strlen (socket_name
)+1 >= sizeof serv_addr
.sun_path
)
460 log_error ("name of socket to long\n");
465 fd
= socket (AF_UNIX
, SOCK_STREAM
, 0);
468 log_error ("can't create socket: %s\n", strerror(errno
) );
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
) );
486 if (listen (fd
, 5 ) == -1)
488 log_error ("listen() failed: %s\n", strerror (errno
));
494 log_info ("listening on socket `%s'\n", socket_name
);
499 if (pid
== (pid_t
)-1)
501 log_fatal ("fork failed: %s\n", strerror (errno
) );
505 { /* we are the parent */
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");
518 *socket_name
= 0; /* don't let cleanup() remove the socket -
519 the child should do this from now on */
521 { /* run the program given on the commandline */
522 if (putenv (infostr
))
524 log_error ("failed to set environment: %s\n",
526 kill (pid
, SIGTERM
);
529 execvp (argv
[0], argv
);
530 log_error ("failed to run the command: %s\n", strerror (errno
));
536 /* print the environment string, so that the caller can use
537 shell's eval to set it */
540 *strchr (infostr
, '=') = ' ';
541 printf ( "setenv %s\n", infostr
);
545 printf ( "%s; export SCDAEMON_INFO;\n", infostr
);
553 /* this is the child */
555 /* detach from tty and put process into a new session */
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
)
565 log_error ("setsid() failed: %s\n", strerror(errno
) );
573 struct sigaction oact
, nact
;
575 nact
.sa_handler
= cleanup_sh
;
576 sigemptyset (&nact
.sa_mask
);
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
);
592 log_error ("chdir to / failed: %s\n", strerror (errno
));
596 scd_command_handler (fd
);
608 #warning no update_random_seed_file
609 update_random_seed_file();
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
);
619 gcry_control (GCRYCTL_DUMP_SECMEM_STATS
);
621 gcry_control (GCRYCTL_TERM_SECMEM
);
622 rc
= rc
? rc
: log_get_errorcount(0)? 2 : 0;
628 scd_init_default_ctrl (CTRL ctrl
)