~ubuntu-branches/ubuntu/jaunty/gnupg2/jaunty-updates

« back to all changes in this revision

Viewing changes to scd/scdaemon.c

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Urlichs
  • Date: 2005-12-08 22:13:21 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20051208221321-4rvs2vu835iam5wv
Tags: 1.9.19-2
* Convert debian/changelog to UTF-8.
* Put gnupg-agent and gpgsm lintian overrides in the respectively
  right package.  Closes: #335066
* Added debhelper tokens to maintainer scripts.
* xsession fixes:
  o Added host name to gpg-agent PID file name.  Closes: #312717
  o Fixed xsession script to be able to run under zsh.  Closes: #308516
  o Don't run gpg-agent if one is already running.  Closes: #336480
* debian/control:
  o Fixed package description of gpgsm package.  Closes: #299842
  o Added mention of gpg-agent to description of gnupg-agent package.
    Closes: #304355
* Thanks to Peter Eisentraut <petere@debian.org> for all of the above.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* scdaemon.c  -  The GnuPG Smartcard Daemon
2
 
 *      Copyright (C) 2001, 2002, 2004 Free Software Foundation, Inc.
 
2
 *      Copyright (C) 2001, 2002, 2004, 2005 Free Software Foundation, Inc.
3
3
 *
4
4
 * This file is part of GnuPG.
5
5
 *
35
35
#endif /*HAVE_W32_SYSTEM*/
36
36
#include <unistd.h>
37
37
#include <signal.h>
38
 
#ifdef USE_GNU_PTH
39
 
# include <pth.h>
40
 
#endif
 
38
#include <pth.h>
41
39
 
42
40
#define JNLIB_NEED_LOG_LOGV
43
41
#include "scdaemon.h"
52
50
#ifdef HAVE_W32_SYSTEM
53
51
#include "../jnlib/w32-afunix.h"
54
52
#endif
55
 
 
 
53
#include "ccid-driver.h"
 
54
#include "mkdtemp.h"
56
55
 
57
56
enum cmd_and_opt_values 
58
57
{ aNull = 0,
68
67
  oDebugAll,
69
68
  oDebugLevel,
70
69
  oDebugWait,
71
 
  oDebugSC,
 
70
  oDebugAllowCoreDump,
 
71
  oDebugCCIDDriver,
72
72
  oNoGreeting,
73
73
  oNoOptions,
74
74
  oHomedir,
76
76
  oNoGrab,
77
77
  oLogFile,
78
78
  oServer,
 
79
  oMultiServer,
79
80
  oDaemon,
80
81
  oBatch,
81
82
  oReaderPort,
86
87
  oAllowAdmin,
87
88
  oDenyAdmin,
88
89
  oDisableApplication,
89
 
 
90
 
aTest };
 
90
  oDebugDisableTicker
 
91
};
91
92
 
92
93
 
93
94
 
98
99
  { 301, NULL, 0, N_("@Options:\n ") },
99
100
 
100
101
  { oServer,   "server",     0, N_("run in server mode (foreground)") },
 
102
  { oMultiServer, "multi-server", 0,
 
103
                                N_("run in multi server mode (foreground)") },
101
104
  { oDaemon,   "daemon",     0, N_("run in daemon mode (background)") },
102
105
  { oVerbose, "verbose",   0, N_("verbose") },
103
106
  { oQuiet,     "quiet",     0, N_("be somewhat more quiet") },
108
111
  { oDebugAll, "debug-all"     ,0, "@"},
109
112
  { oDebugLevel, "debug-level" ,2, "@"},
110
113
  { oDebugWait,"debug-wait",1, "@"},
111
 
  { oDebugSC,  "debug-sc",  1, N_("|N|set OpenSC debug level to N")},
 
114
  { oDebugAllowCoreDump, "debug-allow-core-dump", 0, "@" },
 
115
  { oDebugCCIDDriver, "debug-ccid-driver", 0, "@"},
 
116
  { oDebugDisableTicker, "debug-disable-ticker", 0, "@"},
112
117
  { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
113
118
  { oLogFile,  "log-file"   ,2, N_("use a log file for the server")},
114
119
  { oReaderPort, "reader-port", 2, N_("|N|connect to reader at port N")},
121
126
                                    "@"
122
127
#endif
123
128
                                         /* end --disable-ccid */},
124
 
  { oDisableOpenSC, "disable-opensc", 0,
125
 
#ifdef HAVE_OPENSC
126
 
                                    N_("do not use the OpenSC layer")
127
 
#else
128
 
                                    "@"
129
 
#endif
130
 
                                         /* end --disable-opensc */},
131
129
  { oAllowAdmin, "allow-admin", 0, N_("allow the use of admin card commands")},
132
130
  { oDenyAdmin,  "deny-admin",  0, "@" },  
133
131
  { oDisableApplication, "disable-application", 2, "@"},
144
142
#endif
145
143
 
146
144
 
147
 
static volatile int caught_fatal_sig = 0;
148
 
 
149
145
/* Flag to indicate that a shutdown was requested. */
150
146
static int shutdown_pending;
151
147
 
153
149
static int maybe_setuid = 1;
154
150
 
155
151
/* Name of the communication socket */
156
 
static char socket_name[128];
157
 
 
158
 
 
159
 
#ifndef HAVE_OPENSC
160
 
#ifdef USE_GNU_PTH
 
152
static char *socket_name;
 
153
 
 
154
 
 
155
/* Debug flag to disable the ticker.  The ticker is in fact not
 
156
   disabled but it won't perform any ticker specific actions. */
 
157
static int ticker_disabled;
 
158
 
 
159
 
 
160
 
 
161
static char *create_socket_name (int use_standard_socket,
 
162
                                 char *standard_name, char *template);
 
163
static int create_server_socket (int is_standard_name, const char *name);
 
164
 
 
165
static void *start_connection_thread (void *arg);
 
166
static void handle_connections (int listen_fd);
 
167
 
161
168
/* Pth wrapper function definitions. */
162
169
GCRY_THREAD_OPTION_PTH_IMPL;
163
170
 
164
 
static void *ticker_thread (void *arg);
165
 
#endif /*USE_GNU_PTH*/
166
 
#endif /*!HAVE_OPENSC*/
167
171
 
 
172
 
168
173
static const char *
169
174
my_strusage (int level)
170
175
{
271
276
static void
272
277
cleanup (void)
273
278
{
274
 
  if (*socket_name)
 
279
  if (socket_name && *socket_name)
275
280
    {
276
281
      char *p;
277
282
 
288
293
}
289
294
 
290
295
 
291
 
static RETSIGTYPE
292
 
cleanup_sh (int sig)
293
 
{
294
 
  if (caught_fatal_sig)
295
 
    raise (sig);
296
 
  caught_fatal_sig = 1;
297
 
 
298
 
  /* gcry_control( GCRYCTL_TERM_SECMEM );*/
299
 
  cleanup ();
300
 
 
301
 
#ifndef HAVE_DOSISH_SYSTEM
302
 
  {     /* reset action to default action and raise signal again */
303
 
    struct sigaction nact;
304
 
    nact.sa_handler = SIG_DFL;
305
 
    sigemptyset( &nact.sa_mask );
306
 
    nact.sa_flags = 0;
307
 
    sigaction( sig, &nact, NULL);
308
 
  }
309
 
#endif
310
 
  raise( sig );
311
 
}
312
296
 
313
297
int
314
298
main (int argc, char **argv )
328
312
  int greeting = 0;
329
313
  int nogreeting = 0;
330
314
  int pipe_server = 0;
 
315
  int multi_server = 0;
331
316
  int is_daemon = 0;
332
317
  int nodetach = 0;
333
318
  int csh_style = 0;
335
320
  int debug_wait = 0;
336
321
  int gpgconf_list = 0;
337
322
  const char *config_filename = NULL;
 
323
  int allow_coredump = 0;
338
324
 
339
325
  set_strusage (my_strusage);
340
326
  gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
349
335
 
350
336
  /* Libgcrypt requires us to register the threading model first.
351
337
     Note that this will also do the pth_init. */
352
 
#ifndef HAVE_OPENSC
353
 
#ifdef USE_GNU_PTH
354
338
  err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
355
339
  if (err)
356
340
    {
357
341
      log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
358
342
                 gpg_strerror (err));
359
343
    }
360
 
#endif /*USE_GNU_PTH*/
361
 
#endif /*!HAVE_OPENSC*/
362
344
 
363
345
  /* Check that the libraries are suitable.  Do it here because
364
346
     the option parsing may need services of the library */
469
451
        case oDebugAll: opt.debug = ~0; break;
470
452
        case oDebugLevel: debug_level = pargs.r.ret_str; break;
471
453
        case oDebugWait: debug_wait = pargs.r.ret_int; break;
472
 
        case oDebugSC: opt.debug_sc = pargs.r.ret_int; break;
 
454
        case oDebugAllowCoreDump:
 
455
          enable_core_dumps ();
 
456
          allow_coredump = 1;
 
457
          break;
 
458
        case oDebugCCIDDriver: 
 
459
#ifdef HAVE_LIBUSB
 
460
          ccid_set_debug_level (ccid_set_debug_level (-1)+1);
 
461
#endif /*HAVE_LIBUSB*/
 
462
          break;
 
463
        case oDebugDisableTicker: ticker_disabled = 1; break;
473
464
 
474
465
        case oOptions:
475
466
          /* config files may not be nested (silently ignore them) */
489
480
        case oCsh: csh_style = 1; break;
490
481
        case oSh: csh_style = 0; break;
491
482
        case oServer: pipe_server = 1; break;
 
483
        case oMultiServer: pipe_server = 1; multi_server = 1; break;
492
484
        case oDaemon: is_daemon = 1; break;
493
485
 
494
486
        case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
495
487
        case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
496
488
        case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
497
489
        case oDisableCCID: opt.disable_ccid = 1; break;
498
 
        case oDisableOpenSC: opt.disable_opensc = 1; break;
 
490
        case oDisableOpenSC: break;
499
491
 
500
492
        case oAllowAdmin: opt.allow_admin = 1; break;
501
493
        case oDenyAdmin: opt.allow_admin = 0; break;
593
585
#ifdef HAVE_LIBUSB
594
586
      printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
595
587
#endif
596
 
#ifdef HAVE_LIBUSB
597
 
      printf ("disable-opensc:%lu:\n", GC_OPT_FLAG_NONE );
598
 
#endif
599
588
      printf ("allow-admin:%lu:\n", GC_OPT_FLAG_NONE );
600
589
 
601
590
 
609
598
      log_set_prefix (NULL, 1|2|4);
610
599
    }
611
600
 
612
 
 
613
601
  if (pipe_server)
614
 
    { /* This is the simple pipe based server */
615
 
#ifndef HAVE_OPENSC
616
 
#ifdef USE_GNU_PTH
 
602
    { 
 
603
      /* This is the simple pipe based server */
617
604
      pth_attr_t tattr;
618
 
 
 
605
      int fd = -1;
 
606
 
 
607
      {
 
608
        struct sigaction sa;
 
609
        
 
610
        sa.sa_handler = SIG_IGN;
 
611
        sigemptyset (&sa.sa_mask);
 
612
        sa.sa_flags = 0;
 
613
        sigaction (SIGPIPE, &sa, NULL);
 
614
      }
 
615
 
 
616
      /* If --debug-allow-core-dump has been given we also need to
 
617
         switch the working directory to a place where we can actually
 
618
         write. */
 
619
      if (allow_coredump)
 
620
        {
 
621
          if (chdir("/tmp"))
 
622
            log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno));
 
623
          else
 
624
            log_debug ("changed working directory to `/tmp'\n");
 
625
        }
 
626
 
 
627
      /* In multi server mode we need to listen on an additional
 
628
         socket.  Create that socket now before starting the handler
 
629
         for the pipe connection.  This allows that handler to send
 
630
         back the name of that socket. */
 
631
      if (multi_server)
 
632
        {
 
633
          socket_name = create_socket_name (0,
 
634
                                            "S.scdaemon",
 
635
                                            "/tmp/gpg-XXXXXX/S.scdaemon");
 
636
          
 
637
          fd = create_server_socket (0, socket_name);
 
638
        }
 
639
 
619
640
      tattr = pth_attr_new();
620
641
      pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
621
642
      pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
622
 
      pth_attr_set (tattr, PTH_ATTR_NAME, "ticker");
 
643
      pth_attr_set (tattr, PTH_ATTR_NAME, "pipe-connection");
623
644
 
624
 
      if (!pth_spawn (tattr, ticker_thread, NULL))
 
645
      if (!pth_spawn (tattr, start_connection_thread, (void*)(-1)))
625
646
        {
626
 
          log_error ("error spawning ticker thread: %s\n", strerror (errno));
 
647
          log_error ("error spawning pipe connection handler: %s\n",
 
648
                     strerror (errno) );
627
649
          scd_exit (2);
628
650
        }
629
 
#endif /*USE_GNU_PTH*/
630
 
#endif /*!HAVE_OPENSC*/
631
 
      scd_command_handler (-1);
 
651
 
 
652
      handle_connections (fd);
 
653
      if (fd != -1)
 
654
        close (fd);
632
655
    }
633
656
  else if (!is_daemon)
634
657
    {
636
659
                  " to run the program in the background\n"));
637
660
    }
638
661
  else
639
 
    { /* regular server mode */
 
662
    { /* Regular server mode */
640
663
      int fd;
641
664
      pid_t pid;
642
665
      int i;
643
 
      int len;
644
 
      struct sockaddr_un serv_addr;
645
 
      char *p;
646
 
 
647
 
      /* fixme: if there is already a running gpg-agent we should
648
 
         share the same directory - and vice versa */
649
 
      *socket_name = 0;
650
 
      snprintf (socket_name, DIM(socket_name)-1,
651
 
                "/tmp/gpg-XXXXXX/S.scdaemon");
652
 
      socket_name[DIM(socket_name)-1] = 0;
653
 
      p = strrchr (socket_name, '/');
654
 
      if (!p)
655
 
        BUG ();
656
 
      *p = 0;;
657
 
 
658
 
#ifndef HAVE_W32_SYSTEM
659
 
      if (!mkdtemp(socket_name))
660
 
        {
661
 
          log_error ("can't create directory `%s': %s\n",
662
 
                     socket_name, strerror(errno) );
663
 
          exit (1);
664
 
        }
665
 
#endif
666
 
      *p = '/';
667
 
 
668
 
      if (strchr (socket_name, ':') )
669
 
        {
670
 
          log_error ("colons are not allowed in the socket name\n");
671
 
          exit (1);
672
 
        }
673
 
      if (strlen (socket_name)+1 >= sizeof serv_addr.sun_path ) 
674
 
        {
675
 
          log_error ("name of socket to long\n");
676
 
          exit (1);
677
 
        }
678
 
   
679
 
 
680
 
#ifdef HAVE_W32_SYSTEM
681
 
      fd = _w32_sock_new (AF_UNIX, SOCK_STREAM, 0);
682
 
#else
683
 
      fd = socket (AF_UNIX, SOCK_STREAM, 0);
684
 
#endif
685
 
      if (fd == -1)
686
 
        {
687
 
          log_error ("can't create socket: %s\n", strerror(errno) );
688
 
          exit (1);
689
 
        }
690
 
 
691
 
      memset (&serv_addr, 0, sizeof serv_addr);
692
 
      serv_addr.sun_family = AF_UNIX;
693
 
      strcpy (serv_addr.sun_path, socket_name);
694
 
      len = (offsetof (struct sockaddr_un, sun_path)
695
 
             + strlen(serv_addr.sun_path) + 1);
696
 
 
697
 
      if (
698
 
#ifdef HAVE_W32_SYSTEM
699
 
          _w32_sock_bind
700
 
#else
701
 
          bind 
702
 
#endif
703
 
          (fd, (struct sockaddr*)&serv_addr, len) == -1)
704
 
        {
705
 
          log_error ("error binding socket to `%s': %s\n",
706
 
                     serv_addr.sun_path, strerror (errno) );
707
 
          close (fd);
708
 
          exit (1);
709
 
        }
710
 
  
711
 
      if (listen (fd, 5 ) == -1)
712
 
        {
713
 
          log_error ("listen() failed: %s\n", strerror (errno));
714
 
          close (fd);
715
 
          exit (1);
716
 
        }
717
 
 
718
 
      if (opt.verbose)
719
 
        log_info ("listening on socket `%s'\n", socket_name );
 
666
 
 
667
      /* Create the socket.  */
 
668
      socket_name = create_socket_name (0,
 
669
                                        "S.scdaemon",
 
670
                                        "/tmp/gpg-XXXXXX/S.scdaemon");
 
671
 
 
672
      fd = create_server_socket (0, socket_name);
720
673
 
721
674
 
722
675
      fflush (NULL);
759
712
            }
760
713
          else
761
714
            {
762
 
              /* print the environment string, so that the caller can use
 
715
              /* Print the environment string, so that the caller can use
763
716
                 shell's eval to set it */
764
717
              if (csh_style)
765
718
                {
776
729
          /* NOTREACHED */
777
730
        } /* end parent */
778
731
      
779
 
      /* this is the child */
 
732
      /* This is the child. */
780
733
 
781
 
      /* detach from tty and put process into a new session */
 
734
      /* Detach from tty and put process into a new session. */
782
735
      if (!nodetach )
783
 
        {  /* close stdin, stdout and stderr unless it is the log stream */
 
736
        {  
 
737
          /* Close stdin, stdout and stderr unless it is the log stream. */
784
738
          for (i=0; i <= 2; i++) 
785
739
            {
786
 
              if ( log_get_fd () != i)
 
740
              if ( log_test_fd (i) && i != fd)
787
741
                close (i);
788
742
            }
789
743
          if (setsid() == -1)
794
748
            }
795
749
        }
796
750
 
797
 
      /* setup signals */
798
751
      {
799
 
        struct sigaction oact, nact;
800
 
        
801
 
        nact.sa_handler = cleanup_sh;
802
 
        sigemptyset (&nact.sa_mask);
803
 
        nact.sa_flags = 0;
804
 
        
805
 
        sigaction (SIGHUP, NULL, &oact);
806
 
        if (oact.sa_handler != SIG_IGN)
807
 
          sigaction (SIGHUP, &nact, NULL);
808
 
        sigaction( SIGTERM, NULL, &oact );
809
 
        if (oact.sa_handler != SIG_IGN)
810
 
          sigaction (SIGTERM, &nact, NULL);
811
 
        nact.sa_handler = SIG_IGN;
812
 
        sigaction (SIGPIPE, &nact, NULL);
813
 
        sigaction (SIGINT, &nact, NULL);
 
752
        struct sigaction sa;
 
753
        
 
754
        sa.sa_handler = SIG_IGN;
 
755
        sigemptyset (&sa.sa_mask);
 
756
        sa.sa_flags = 0;
 
757
        sigaction (SIGPIPE, &sa, NULL);
814
758
      }
815
759
 
816
760
      if (chdir("/"))
821
765
 
822
766
#endif /*!HAVE_W32_SYSTEM*/
823
767
 
824
 
      scd_command_handler (fd);
 
768
      handle_connections (fd);
825
769
 
826
770
      close (fd);
827
771
    }
853
797
 
854
798
 
855
799
void
856
 
scd_init_default_ctrl (CTRL ctrl)
 
800
scd_init_default_ctrl (ctrl_t ctrl)
857
801
{
858
802
  ctrl->reader_slot = -1;
859
803
}
860
804
 
861
805
 
862
 
#ifndef HAVE_OPENSC
863
 
#ifdef USE_GNU_PTH
 
806
/* Return the name of the socket to be used to connect to this
 
807
   process.  If no socket is available, return NULL. */
 
808
const char *
 
809
scd_get_socket_name ()
 
810
{
 
811
  if (socket_name && *socket_name)
 
812
    return socket_name;
 
813
  return NULL;
 
814
}
 
815
 
864
816
 
865
817
static void
866
818
handle_signal (int signo)
875
827
      break;
876
828
      
877
829
    case SIGUSR1:
878
 
      log_info ("SIGUSR1 received - no action defined\n");
 
830
      log_info ("SIGUSR1 received - printing internal information:\n");
 
831
      pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
 
832
      app_dump_state ();
879
833
      break;
880
834
 
881
835
    case SIGUSR2:
911
865
    }
912
866
}
913
867
 
 
868
 
914
869
static void
915
870
handle_tick (void)
916
871
{
917
 
  scd_update_reader_status_file ();
918
 
}
919
 
 
 
872
  if (!ticker_disabled)
 
873
    scd_update_reader_status_file ();
 
874
}
 
875
 
 
876
 
 
877
/* Create a name for the socket.  With USE_STANDARD_SOCKET given as
 
878
   true using STANDARD_NAME in the home directory or if given has
 
879
   false from the mkdir type name TEMPLATE.  In the latter case a
 
880
   unique name in a unique new directory will be created.  In both
 
881
   cases check for valid characters as well as against a maximum
 
882
   allowed length for a unix domain socket is done.  The function
 
883
   terminates the process in case of an error.  Retunrs: Pointer to an
 
884
   allcoated string with the absolute name of the socket used.  */
 
885
static char *
 
886
create_socket_name (int use_standard_socket,
 
887
                    char *standard_name, char *template)
 
888
{
 
889
  char *name, *p;
 
890
 
 
891
  if (use_standard_socket)
 
892
    name = make_filename (opt.homedir, standard_name, NULL);
 
893
  else
 
894
    {
 
895
      name = xstrdup (template);
 
896
      p = strrchr (name, '/');
 
897
      if (!p)
 
898
        BUG ();
 
899
      *p = 0;
 
900
      if (!mkdtemp (name))
 
901
        {
 
902
          log_error (_("can't create directory `%s': %s\n"),
 
903
                     name, strerror (errno));
 
904
          scd_exit (2);
 
905
        }
 
906
      *p = '/';
 
907
    }
 
908
 
 
909
  if (strchr (name, PATHSEP_C))
 
910
    {
 
911
      log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
 
912
      scd_exit (2);
 
913
    }
 
914
  if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
 
915
    {
 
916
      log_error (_("name of socket too long\n"));
 
917
      scd_exit (2);
 
918
    }
 
919
  return name;
 
920
}
 
921
 
 
922
 
 
923
 
 
924
/* Create a Unix domain socket with NAME.  IS_STANDARD_NAME indicates
 
925
   whether a non-random socket is used.  Returns the file descriptor
 
926
   or terminates the process in case of an error. */
 
927
static int
 
928
create_server_socket (int is_standard_name, const char *name)
 
929
{
 
930
  struct sockaddr_un *serv_addr;
 
931
  socklen_t len;
 
932
  int fd;
 
933
  int rc;
 
934
 
 
935
#ifdef HAVE_W32_SYSTEM
 
936
  fd = _w32_sock_new (AF_UNIX, SOCK_STREAM, 0);
 
937
#else
 
938
  fd = socket (AF_UNIX, SOCK_STREAM, 0);
 
939
#endif
 
940
  if (fd == -1)
 
941
    {
 
942
      log_error (_("can't create socket: %s\n"), strerror (errno));
 
943
      scd_exit (2);
 
944
    }
 
945
 
 
946
  serv_addr = xmalloc (sizeof (*serv_addr)); 
 
947
  memset (serv_addr, 0, sizeof *serv_addr);
 
948
  serv_addr->sun_family = AF_UNIX;
 
949
  assert (strlen (name) + 1 < sizeof (serv_addr->sun_path));
 
950
  strcpy (serv_addr->sun_path, name);
 
951
  len = (offsetof (struct sockaddr_un, sun_path)
 
952
         + strlen (serv_addr->sun_path) + 1);
 
953
 
 
954
#ifdef HAVE_W32_SYSTEM
 
955
  rc = _w32_sock_bind (fd, (struct sockaddr*) serv_addr, len);
 
956
  if (is_standard_name && rc == -1 )
 
957
    {
 
958
      remove (name);
 
959
      rc = bind (fd, (struct sockaddr*) serv_addr, len);
 
960
    }
 
961
#else
 
962
  rc = bind (fd, (struct sockaddr*) serv_addr, len);
 
963
  if (is_standard_name && rc == -1 && errno == EADDRINUSE)
 
964
    {
 
965
      remove (name);
 
966
      rc = bind (fd, (struct sockaddr*) serv_addr, len);
 
967
    }
 
968
#endif
 
969
  if (rc == -1)
 
970
    {
 
971
      log_error (_("error binding socket to `%s': %s\n"),
 
972
                 serv_addr->sun_path, strerror (errno));
 
973
      close (fd);
 
974
      scd_exit (2);
 
975
    }
 
976
 
 
977
  if (listen (fd, 5 ) == -1)
 
978
    {
 
979
      log_error (_("listen() failed: %s\n"), strerror (errno));
 
980
      close (fd);
 
981
      scd_exit (2);
 
982
    }
 
983
          
 
984
  if (opt.verbose)
 
985
    log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
 
986
 
 
987
  return fd;
 
988
}
 
989
 
 
990
 
 
991
 
 
992
/* This is the standard connection thread's main function.  */
920
993
static void *
921
 
ticker_thread (void *dummy_arg)
922
 
{
923
 
  pth_event_t sigs_ev, time_ev = NULL;
 
994
start_connection_thread (void *arg)
 
995
{
 
996
  int fd = (int)arg;
 
997
 
 
998
  if (opt.verbose)
 
999
    log_info (_("handler for fd %d started\n"), fd);
 
1000
 
 
1001
  scd_command_handler (fd);
 
1002
 
 
1003
  if (opt.verbose)
 
1004
    log_info (_("handler for fd %d terminated\n"), fd);
 
1005
 
 
1006
  /* If this thread is the pipe connection thread, flag that a
 
1007
     shutdown is required.  With the next ticker event and given that
 
1008
     no other connections are running the shutdown will then
 
1009
     happen. */
 
1010
  if (fd == -1)
 
1011
    shutdown_pending = 1;
 
1012
  
 
1013
  return NULL;
 
1014
}
 
1015
 
 
1016
 
 
1017
/* Connection handler loop.  Wait for connection requests and spawn a
 
1018
   thread after accepting a connection.  LISTEN_FD is allowed to be -1
 
1019
   in which case this code will only do regular timeouts and handle
 
1020
   signals. */
 
1021
static void
 
1022
handle_connections (int listen_fd)
 
1023
{
 
1024
  pth_attr_t tattr;
 
1025
  pth_event_t ev, time_ev;
924
1026
  sigset_t sigs;
925
1027
  int signo;
 
1028
  struct sockaddr_un paddr;
 
1029
  socklen_t plen;
 
1030
  fd_set fdset, read_fdset;
 
1031
  int ret;
 
1032
  int fd;
 
1033
 
 
1034
  tattr = pth_attr_new();
 
1035
  pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
 
1036
  pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
926
1037
 
927
1038
#ifndef HAVE_W32_SYSTEM /* fixme */
928
1039
  sigemptyset (&sigs );
931
1042
  sigaddset (&sigs, SIGUSR2);
932
1043
  sigaddset (&sigs, SIGINT);
933
1044
  sigaddset (&sigs, SIGTERM);
934
 
  sigs_ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
 
1045
  pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
 
1046
  ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
935
1047
#else
936
 
  sigs_ev = NULL;
 
1048
  ev = NULL;
937
1049
#endif
938
 
  
 
1050
  time_ev = NULL;
 
1051
 
 
1052
  FD_ZERO (&fdset);
 
1053
  if (listen_fd != -1)
 
1054
    FD_SET (listen_fd, &fdset);
 
1055
 
939
1056
  for (;;)
940
1057
    {
 
1058
      sigset_t oldsigs;
 
1059
      
 
1060
      if (shutdown_pending)
 
1061
        {
 
1062
          if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
 
1063
            break; /* ready */
 
1064
 
 
1065
          /* Do not accept anymore connections but wait for existing
 
1066
             connections to terminate. We do this by clearing out all
 
1067
             file descriptors to wait for, so that the select will be
 
1068
             used to just wait on a signal or timeout event. */
 
1069
          FD_ZERO (&fdset);
 
1070
        }
 
1071
 
 
1072
      /* Create a timeout event if needed. */
941
1073
      if (!time_ev)
 
1074
        time_ev = pth_event (PTH_EVENT_TIME, pth_timeout (2, 0));
 
1075
 
 
1076
      /* POSIX says that fd_set should be implemented as a structure,
 
1077
         thus a simple assignment is fine to copy the entire set.  */
 
1078
      read_fdset = fdset;
 
1079
 
 
1080
      if (time_ev)
 
1081
        pth_event_concat (ev, time_ev, NULL);
 
1082
      ret = pth_select_ev (FD_SETSIZE, &read_fdset, NULL, NULL, NULL, ev);
 
1083
      if (time_ev)
 
1084
        pth_event_isolate (time_ev);
 
1085
 
 
1086
      if (ret == -1)
 
1087
        {
 
1088
          if (pth_event_occurred (ev)
 
1089
              || (time_ev && pth_event_occurred (time_ev)))
 
1090
            {
 
1091
              if (pth_event_occurred (ev))
 
1092
                handle_signal (signo);
 
1093
              if (time_ev && pth_event_occurred (time_ev))
 
1094
                {
 
1095
                  pth_event_free (time_ev, PTH_FREE_ALL);
 
1096
                  time_ev = NULL;
 
1097
                  handle_tick ();
 
1098
                }
 
1099
              continue;
 
1100
            }
 
1101
          log_error (_("pth_select failed: %s - waiting 1s\n"),
 
1102
                     strerror (errno));
 
1103
          pth_sleep (1);
 
1104
          continue;
 
1105
        }
 
1106
 
 
1107
      if (pth_event_occurred (ev))
942
1108
        {
943
 
          time_ev = pth_event (PTH_EVENT_TIME, pth_timeout (2, 0));
944
 
          if (time_ev)
945
 
            pth_event_concat (sigs_ev, time_ev, NULL);
 
1109
          handle_signal (signo);
946
1110
        }
947
1111
 
948
 
      if (pth_wait (sigs_ev) < 1)
949
 
        continue;
950
 
 
951
 
      if (
952
 
#ifdef PTH_STATUS_OCCURRED     /* This is Pth 2 */
953
 
          pth_event_status (sigs_ev) == PTH_STATUS_OCCURRED
954
 
#else
955
 
          pth_event_occurred (sigs_ev)
956
 
#endif
957
 
          )
958
 
        handle_signal (signo);
959
 
 
960
 
      /* Always run the ticker. */
961
 
      if (!shutdown_pending)
 
1112
      if (time_ev && pth_event_occurred (time_ev))
962
1113
        {
963
 
          pth_event_isolate (sigs_ev);
964
1114
          pth_event_free (time_ev, PTH_FREE_ALL);
965
1115
          time_ev = NULL;
966
1116
          handle_tick ();
967
1117
        }
 
1118
 
 
1119
      /* We now might create new threads and because we don't want any
 
1120
         signals - we are handling here - to be delivered to a new
 
1121
         thread. Thus we need to block those signals. */
 
1122
      pth_sigmask (SIG_BLOCK, &sigs, &oldsigs);
 
1123
 
 
1124
      if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
 
1125
        {
 
1126
          plen = sizeof paddr;
 
1127
          fd = pth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
 
1128
          if (fd == -1)
 
1129
            {
 
1130
              log_error ("accept failed: %s\n", strerror (errno));
 
1131
            }
 
1132
          else
 
1133
            {
 
1134
              char threadname[50];
 
1135
              snprintf (threadname, sizeof threadname-1, "conn fd=%d", fd);
 
1136
              threadname[sizeof threadname -1] = 0;
 
1137
              pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
 
1138
              
 
1139
              if (!pth_spawn (tattr, start_connection_thread, (void*)fd))
 
1140
                {
 
1141
                  log_error ("error spawning connection handler: %s\n",
 
1142
                             strerror (errno) );
 
1143
                  close (fd);
 
1144
                }
 
1145
            }
 
1146
          fd = -1;
 
1147
        }
 
1148
 
 
1149
      /* Restore the signal mask. */
 
1150
      pth_sigmask (SIG_SETMASK, &oldsigs, NULL);
 
1151
 
968
1152
    }
969
1153
 
970
 
  pth_event_free (sigs_ev, PTH_FREE_ALL);
 
1154
  pth_event_free (ev, PTH_FREE_ALL);
 
1155
  if (time_ev)
 
1156
    pth_event_free (time_ev, PTH_FREE_ALL);
 
1157
  cleanup ();
 
1158
  log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
971
1159
}
972
 
#endif /*USE_GNU_PTH*/
973
 
#endif /*!HAVE_OPENSC*/
 
1160
 
 
1161