2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
49 #include <sys/resource.h>
64 #ifdef HAVE_GETOPT_LONG
69 #include "getopt_long.h"
72 #ifdef HAVE_PR_SET_NAME
73 #include <sys/prctl.h>
76 #include "pwmd-error.h"
79 #include "util-misc.h"
85 #include "util-string.h"
90 /* In tenths of a second. */
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 50000
100 static pthread_cond_t quit_cond
;
101 static pthread_mutex_t quit_mutex
;
103 static unsigned assuan_level
;
105 pthread_t accept_tid
;
109 static int start_stop_tls (int term
);
112 static gpg_error_t
do_cache_push (struct crypto_s
*crypto
);
113 static int signal_loop (sigset_t sigset
);
115 #ifndef HAVE_PTHREAD_CANCEL
116 #define INIT_SIGNAL(s, cb) do { \
117 int *n = xmalloc (sizeof (int)); \
119 pthread_setspecific (signal_thread_key, n); \
120 struct sigaction act; \
122 sigemptyset (&sigset); \
123 sigaddset (&sigset, s); \
124 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
125 memset (&act, 0, sizeof(act)); \
126 act.sa_flags = SA_SIGINFO; \
127 act.sa_mask = sigset; \
128 act.sa_sigaction = cb; \
129 sigaction (s, &act, NULL); \
133 #ifndef HAVE_PTHREAD_CANCEL
135 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
137 int *n
= (int *) pthread_getspecific (signal_thread_key
);
146 int n
= config_get_boolean ("global", "enable_logging");
150 char *p
= config_get_string ("global", "log_path");
152 if (!p
|| (logfile
&& p
&& log_fd
!= -1 && strcmp(p
, logfile
)))
163 logfile
= expand_homedir (p
);
177 log_syslog
= config_get_boolean ("global", "syslog");
179 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
183 reload_rcfile_thread (void *arg
)
185 #ifndef HAVE_PTHREAD_CANCEL
186 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
189 #ifdef HAVE_PR_SET_NAME
190 prctl (PR_SET_NAME
, "reload rcfile");
192 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
193 MUTEX_LOCK (&rcfile_mutex
);
197 struct slist_s
*keep
= NULL
;
198 struct slist_s
*config
;
199 int b
= disable_list_and_dump
;
205 pthread_cleanup_push (release_mutex_cb
, &rcfile_mutex
);
206 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
208 keep
= config_keep_save ();
209 log_write (_("reloading configuration file '%s'"), rcfile
);
211 prio
= config_get_string ("global", "tls_cipher_suite");
212 config
= config_parse (rcfile
, 1);
215 config_free (global_config
);
216 global_config
= config
;
220 config_keep_restore (keep
);
221 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
224 /* Restart listening sockets since they may have changed. */
228 prio2
= config_get_string ("global", "tls_cipher_suite");
229 if ((prio2
&& (!prio
|| strcmp (prio
, prio2
))) || (prio
&& !prio2
))
235 crypto_set_keepalive ();
236 pthread_cleanup_pop (0);
239 MUTEX_UNLOCK (&rcfile_mutex
);
244 send_error (assuan_context_t ctx
, gpg_error_t e
)
246 struct client_s
*client
= assuan_get_pointer (ctx
);
248 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
255 return assuan_process_done (ctx
, 0);
259 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
263 if (client
&& client
->xml_error
)
265 log_write ("%s", client
->xml_error
->message
);
266 xfree (client
->last_error
);
267 client
->last_error
= NULL
;
268 if (client
->xml_error
->message
)
269 client
->last_error
= str_dup (client
->xml_error
->message
);
271 e
= assuan_process_done (ctx
,
272 assuan_set_error (ctx
, e
,
273 client
->xml_error
->message
? client
->xml_error
->message
: NULL
));
274 xmlResetLastError ();
275 xmlResetError (client
->xml_error
);
276 xfree (client
->xml_error
);
277 client
->xml_error
= NULL
;
281 return assuan_process_done (ctx
,
282 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
286 log_write (const char *fmt
, ...)
292 pthread_t tid
= pthread_self ();
293 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
295 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
298 pthread_mutex_lock (&m
);
299 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
301 if (!cmdline
&& logfile
&& log_fd
== -1)
303 log_fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600);
305 warn ("%s", logfile
);
310 if (str_vasprintf (&args
, fmt
, ap
) != -1)
314 pthread_cleanup_push (xfree
, args
);
315 fprintf (stderr
, "pwmd: %s\n", args
);
317 pthread_cleanup_pop (1);
321 char *name
= pthread_getspecific (thread_name_key
);
324 pthread_cleanup_push (xfree
, args
);
325 snprintf (buf
, sizeof (buf
),
326 name
&& *name
== '!' ? "%s: " : name
? "%s(%p): " : "%s",
327 name
? *name
== '!' ? name
+1 : name
: "",
328 name
&& *name
== '!' ? 0 : name
? (pthread_t
*) tid
: 0);
331 if (!cmdline
&& log_syslog
&& !nofork
)
332 syslog (LOG_INFO
, "%s%s", name
, args
);
335 struct tm
*tm
= localtime (&now
);
337 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
338 tbuf
[sizeof (tbuf
) - 1] = 0;
340 if (args
[strlen (args
) - 1] == '\n')
341 args
[strlen (args
) - 1] = 0;
343 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
,
345 pthread_cleanup_pop (1);
348 pthread_cleanup_push (xfree
, line
);
349 if (logfile
&& log_fd
!= -1)
351 ssize_t ret
= write (log_fd
, line
, strlen (line
));
358 fprintf (stdout
, "%s", line
);
362 pthread_cleanup_pop (1);
368 pthread_cleanup_pop (0);
370 if (log_fd
!= -1 && log_keepopen
<= 0)
376 pthread_mutex_unlock (&m
);
384 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION
))
386 fprintf (stderr
, _("gpgrt_check_version(): Incompatible libgpg-error. "
387 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION
,
388 gpgrt_check_version (NULL
));
389 return GPG_ERR_UNKNOWN_VERSION
;
393 //gpgrt_set_alloc_func (xrealloc_gpgrt);
395 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION
))
397 fprintf (stderr
, _("assuan_check_version(): Incompatible libassuan. "
398 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION
,
399 assuan_check_version (NULL
));
400 return GPG_ERR_UNKNOWN_VERSION
;
403 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION
))
405 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
406 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION
,
407 gcry_check_version (NULL
));
408 return GPG_ERR_UNKNOWN_VERSION
;
411 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
413 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION
))
415 fprintf (stderr
, _("gpgme_check_version(): Incompatible libgpgme. "
416 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION
,
417 gpgme_check_version (NULL
));
418 return GPG_ERR_UNKNOWN_VERSION
;
421 rc
= gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP
);
424 fprintf (stderr
, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc
));
425 return GPG_ERR_UNKNOWN_VERSION
;
428 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
430 gpgme_set_locale (NULL
, LC_CTYPE
, setlocale (LC_CTYPE
, NULL
));
431 gpgme_set_locale (NULL
, LC_MESSAGES
, setlocale (LC_MESSAGES
, NULL
));
435 if (gnutls_global_init ())
437 fprintf(stderr
, _("gnutls_global_init() failed.\n"));
438 return GPG_ERR_UNKNOWN_VERSION
;
441 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION
))
443 fprintf (stderr
, _("gnutls_check_version(): Incompatible libgnutls. "
444 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION
,
445 gnutls_check_version (NULL
));
446 return GPG_ERR_UNKNOWN_VERSION
;
449 gnutls_global_set_log_function (tls_log
);
450 gnutls_global_set_audit_log_function (tls_audit_log
);
456 do_validate_peer (assuan_context_t ctx
, const char *section
,
457 assuan_peercred_t
* peer
)
462 struct client_s
*client
= assuan_get_pointer (ctx
);
465 return GPG_ERR_FORBIDDEN
;
468 if (client
->thd
->remote
)
469 return tls_validate_access (client
, section
);
472 rc
= assuan_get_peercred (ctx
, peer
);
476 users
= config_get_list (section
, "allowed");
479 for (char **p
= users
; !rc
&& *p
; p
++)
481 rc
= acl_check_common(client
, *p
, (*peer
)->uid
, (*peer
)->gid
,
487 else if (client
->no_access_param
)
490 return allowed
&& !rc
? 0 : rc
? rc
: GPG_ERR_FORBIDDEN
;
493 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
494 #ifdef HAVE_GETGRNAM_R
496 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
499 struct group gr
, *gresult
;
500 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
509 return GPG_ERR_ENOMEM
;
511 err
= getgrnam_r (name
, &gr
, buf
, len
, &gresult
);
514 if (gresult
->gr_gid
== gid
)
521 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
525 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &tbuf
, &rc
);
527 if (!rc
&& result
&& result
->pw_uid
== uid
)
541 rc
= gpg_error_from_errno (err
);
544 return rc
? rc
: !gresult
? 0 : GPG_ERR_EACCES
;
548 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
550 struct group
*gresult
;
554 gresult
= getgrnam (name
);
555 if (!errno
&& gresult
&& gresult
->gr_gid
== gid
)
561 rc
= gpg_error_from_syserror ();
565 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
569 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &buf
, &rc
);
571 if (!rc
&& result
&& result
->pw_uid
== uid
)
586 peer_is_invoker(struct client_s
*client
)
588 struct invoking_user_s
*user
;
591 if (client
->thd
->state
== CLIENT_STATE_UNKNOWN
)
592 return GPG_ERR_EACCES
;
594 for (user
= invoking_users
; user
; user
= user
->next
)
597 if (client
->thd
->remote
)
599 if (user
->type
== INVOKING_TLS
600 && !strcmp(client
->thd
->tls
->fp
, user
->id
))
601 allowed
= user
->not ? 0 : 1;
607 if (user
->type
== INVOKING_GID
)
609 gpg_error_t rc
= acl_check_group (user
->id
,
610 client
->thd
->peer
->uid
,
611 client
->thd
->peer
->gid
,
612 user
->not, &allowed
);
616 else if (user
->type
== INVOKING_UID
&& client
->thd
->peer
->uid
== user
->uid
)
617 allowed
= user
->not ? 0 : 1;
620 return allowed
? 0 : GPG_ERR_EACCES
;
623 #ifdef HAVE_GETGRNAM_R
625 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
626 gid_t gid
, int *allowed
)
636 if (*user
== '-' || *user
== '!')
639 if (*user
== '+') // not implemented yet
642 if (*user
== '#') // TLS fingerprint hash
645 if (not || rw
|| tls
)
651 if (client
->thd
->remote
)
653 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
663 else if (client
->thd
->remote
) // Remote client with no FP in the ACL
667 if (*user
== '@') // all users in group
668 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
673 struct passwd
*pwd
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
675 if (!rc
&& pwd
&& pwd
->pw_uid
== uid
)
685 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
686 gid_t gid
, int *allowed
)
696 if (*user
== '-' || *user
== '!')
699 if (*user
== '+') // not implemented yet
702 if (*user
== '#') // TLS fingerprint hash
705 if (not || rw
|| tls
)
711 if (client
->thd
->remote
)
713 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
723 if (*user
== '@') // all users in group
724 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
729 struct passwd
*result
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
731 if (!rc
&& result
&& result
->pw_uid
== uid
)
742 validate_peer (struct client_s
*cl
)
748 return tls_validate_access (cl
, NULL
);
751 MUTEX_LOCK (&cn_mutex
);
752 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
753 rc
= do_validate_peer (cl
->ctx
, "global", &cl
->thd
->peer
);
754 pthread_cleanup_pop (1);
755 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
756 !rc
? _("accepted") : _("rejected"), cl
->thd
->peer
->uid
,
757 cl
->thd
->peer
->gid
, cl
->thd
->peer
->pid
, rc
);
762 xml_error_cb (void *data
, xmlErrorPtr e
)
764 struct client_s
*client
= data
;
767 * Keep the first reported error as the one to show in the error
768 * description. Reset in send_error().
770 if (client
->xml_error
)
773 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
774 xmlCopyError (e
, client
->xml_error
);
778 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
779 int *status
, int options
)
781 return waitpid (pid
, status
, options
);
785 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
788 struct client_s
*client
= assuan_get_pointer (ctx
);
790 if (client
->thd
->remote
)
791 return tls_read_hook (ctx
, (int) fd
, data
, len
);
794 return read ((int) fd
, data
, len
);
798 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
799 const void *data
, size_t len
)
802 struct client_s
*client
= assuan_get_pointer (ctx
);
804 if (client
->thd
->remote
)
805 return tls_write_hook (ctx
, (int) fd
, data
, len
);
808 return write ((int) fd
, data
, len
);
812 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
815 struct client_s
*client
= data
;
820 if (!(assuan_level
& cat
))
828 case ASSUAN_LOG_INIT
:
829 str
= "ASSUAN[INIT]";
834 case ASSUAN_LOG_ENGINE
:
835 str
= "ASSUAN[ENGINE]";
837 case ASSUAN_LOG_DATA
:
838 str
= "ASSUAN[DATA]";
840 case ASSUAN_LOG_SYSIO
:
841 str
= "ASSUAN[SYSIO]";
843 case ASSUAN_LOG_CONTROL
:
844 str
= "ASSUAN[CONTROL]";
847 str
= "ASSUAN[UNKNOWN]";
851 log_write ("%s: %s", str
, msg
);
856 new_connection (struct client_s
*cl
)
859 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
860 static struct assuan_system_hooks shooks
= {
861 ASSUAN_SYSTEM_HOOKS_VERSION
,
869 NULL
, //sendmsg both are used for FD passing
880 char *prio
= config_get_string ("global", "tls_cipher_suite");
882 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
883 if (fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
) == -1)
886 cl
->thd
->tls
= tls_init_client (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
893 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
898 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
899 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
903 assuan_set_pointer (cl
->ctx
, cl
);
904 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
905 rc
= register_commands (cl
->ctx
);
909 rc
= assuan_accept (cl
->ctx
);
913 rc
= validate_peer (cl
);
914 /* May not be implemented on all platforms. */
915 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
918 MUTEX_LOCK (&cn_mutex
);
919 cl
->thd
->state
= CLIENT_STATE_INIT
;
920 MUTEX_UNLOCK (&cn_mutex
);
921 cl
->lock_timeout
= config_get_integer ("global", "lock_timeout");
922 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
926 log_write ("%s", pwmd_strerror (rc
));
931 * This is called after a client_thread() terminates. Set with
932 * pthread_cleanup_push().
935 free_client_cb (void *arg
)
937 struct client_thread_s
*cn
= arg
;
938 struct client_s
*cl
= cn
->cl
;
940 MUTEX_LOCK (&cn_mutex
);
941 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
942 MUTEX_UNLOCK (&cn_mutex
);
946 unlock_flock (&cl
->flock_fd
);
949 xmlResetError (cl
->xml_error
);
951 xfree (cl
->xml_error
);
956 gnutls_deinit (cn
->tls
->ses
);
963 assuan_release (cl
->ctx
);
964 else if (cl
->thd
&& cl
->thd
->fd
!= -1)
968 crypto_free (cl
->crypto
);
979 while (cn
->msg_queue
)
981 struct status_msg_s
*msg
= cn
->msg_queue
;
983 cn
->msg_queue
= msg
->next
;
988 if (cn
->status_msg_pipe
[0] != -1)
989 close (cn
->status_msg_pipe
[0]);
991 if (cn
->status_msg_pipe
[1] != -1)
992 close (cn
->status_msg_pipe
[1]);
994 pthread_mutex_destroy (&cn
->status_mutex
);
995 log_write (_("exiting, fd=%i"), cn
->fd
);
996 send_status_all (STATUS_CLIENTS
, NULL
);
1000 xfree (cn
->peeraddr
);
1003 pthread_cond_signal (&quit_cond
);
1009 MUTEX_LOCK (&cn_mutex
);
1010 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
1012 while (slist_length (cn_thread_list
))
1014 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
1016 free_client_cb (thd
);
1020 pthread_cleanup_pop (1);
1025 send_msg_queue (struct client_thread_s
*thd
)
1027 MUTEX_LOCK (&thd
->status_mutex
);
1032 ret
= read (thd
->status_msg_pipe
[0], &c
, 1);
1033 rc
= gpg_error_from_syserror ();
1034 if (ret
== -1 && gpg_err_code (rc
) != GPG_ERR_EAGAIN
)
1035 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
1039 thd
->wrote_status
= 0;
1041 while (thd
->msg_queue
)
1043 struct status_msg_s
*msg
= thd
->msg_queue
;
1045 #ifndef HAVE_PTHREAD_CANCEL
1050 thd
->msg_queue
= thd
->msg_queue
->next
;
1051 MUTEX_UNLOCK (&thd
->status_mutex
);
1052 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
1053 MUTEX_LOCK (&thd
->status_mutex
);
1061 MUTEX_UNLOCK (&thd
->status_mutex
);
1062 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1063 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
1069 client_thread (void *data
)
1071 struct client_thread_s
*thd
= data
;
1072 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1073 #ifndef HAVE_PTHREAD_CANCEL
1074 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1077 #ifdef HAVE_PR_SET_NAME
1078 prctl (PR_SET_NAME
, "client");
1080 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1084 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1085 pwmd_strerror (GPG_ERR_ENOMEM
));
1089 MUTEX_LOCK (&cn_mutex
);
1090 pthread_cleanup_push (free_client_cb
, thd
);
1094 MUTEX_UNLOCK (&cn_mutex
);
1096 if (new_connection (cl
))
1100 struct pollfd fds
[2];
1102 fds
[0].fd
= thd
->fd
;
1103 fds
[0].events
= POLLIN
;
1104 fds
[1].fd
= thd
->status_msg_pipe
[0];
1105 fds
[1].events
= POLLIN
;
1107 send_status_all (STATUS_CLIENTS
, NULL
);
1108 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1111 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1120 n
= poll (fds
, 2, 100);
1123 log_write ("%s", strerror (errno
));
1128 if (thd
->remote
&& thd
->tls
&& thd
->tls
->rehandshake
)
1134 if (thd
->tls
->rehandshake
== 1)
1136 prio
= config_get_string ("global", "tls_cipher_suite");
1139 thd
->tls
->rehandshake
= 0;
1143 ret
= gnutls_priority_set_direct (thd
->tls
->ses
, prio
, &e
);
1144 if (ret
== GNUTLS_E_SUCCESS
)
1146 rc
= send_status (cl
->ctx
, STATUS_REHANDSHAKE
, NULL
);
1149 rc
= assuan_send_data (cl
->ctx
, NULL
, 0);
1152 ret
= gnutls_rehandshake (thd
->tls
->ses
);
1155 log_write ("%s", gnutls_strerror (ret
));
1156 thd
->tls
->rehandshake
= 0;
1159 thd
->tls
->rehandshake
= 2;
1164 log_write ("%s", pwmd_strerror (rc
));
1167 log_write ("%s: %s", gnutls_strerror (ret
), e
);
1178 if (fds
[1].revents
& POLLIN
)
1181 if (!thd
->remote
|| (thd
->tls
&& !thd
->tls
->rehandshake
))
1184 rc
= send_msg_queue (thd
);
1185 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1190 #ifdef HAVE_PTHREAD_CANCEL
1191 if (!(fds
[0].revents
& POLLIN
))
1193 if (thd
->fd
!= -1 && !(fds
[0].revents
& POLLIN
))
1197 rc
= assuan_process_next (cl
->ctx
, &eof
);
1200 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1203 log_write ("assuan_process_next(): rc=%u %s", rc
,
1204 pwmd_strerror (rc
));
1205 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1208 rc
= send_error (cl
->ctx
, rc
);
1211 log_write ("assuan_process_done(): rc=%u %s", rc
,
1212 pwmd_strerror (rc
));
1217 /* Since the msg queue pipe fd's are non-blocking, check for
1218 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1219 * client has already disconnected and will be converted to
1220 * GPG_ERR_EOF during assuan_process_next().
1223 if (!thd
->remote
|| (thd
->tls
&& !thd
->tls
->rehandshake
))
1226 rc
= send_msg_queue (thd
);
1227 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1233 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1234 * functions would be called after a command failed but then the client
1235 * exited normally which may lead to a double free. */
1236 pthread_cleanup_pop (1);
1241 xml_import (const char *filename
, const char *outfile
, char **keyid
,
1242 char **sign_keyid
, char *keyfile
, const char *keyparam
,
1251 struct crypto_s
*crypto
= NULL
;
1253 if (stat (filename
, &st
) == -1)
1255 rc
= gpg_error_from_errno (errno
);
1259 fd
= open (filename
, O_RDONLY
);
1261 return gpg_error_from_errno (errno
);
1263 xmlbuf
= xmalloc (st
.st_size
+ 1);
1267 return GPG_ERR_ENOMEM
;
1270 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1272 rc
= gpg_error_from_errno (errno
);
1279 xmlbuf
[st
.st_size
] = 0;
1280 // Be sure the document validates.
1281 doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
);
1284 return GPG_ERR_BAD_DATA
;
1286 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1287 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1288 rc
= GPG_ERR_BAD_DATA
;
1292 rc
= xml_validate_import (NULL
, n
? n
->children
: n
);
1295 rc
= crypto_init (&crypto
, NULL
, filename
, keyfile
!= NULL
, keyfile
);
1300 crypto
->flags
|= CRYPTO_FLAG_KEYFILE
;
1301 crypto
->keyfile
= str_dup (keyfile
);
1304 xmlDocDumpMemory (doc
, &crypto
->plaintext
, &len
);
1306 crypto
->plaintext_size
= len
;
1308 rc
= GPG_ERR_ENOMEM
;
1315 if (!symmetric
&& (keyparam
|| !keyid
))
1321 fd
= open (keyparam
, O_RDONLY
);
1323 rc
= gpg_error_from_errno (errno
);
1327 if (stat (keyparam
, &st
) == -1)
1328 rc
= gpg_error_from_errno (errno
);
1332 buf
= xmalloc (st
.st_size
+1);
1334 rc
= GPG_ERR_ENOMEM
;
1338 len
= read (fd
, buf
, st
.st_size
);
1339 if (len
!= st
.st_size
)
1340 rc
= gpg_error_from_errno (errno
);
1353 buf
= crypto_default_key_params ();
1355 rc
= GPG_ERR_ENOMEM
;
1359 rc
= crypto_genkey (NULL
, crypto
, (unsigned char *)buf
);
1365 crypto
->save
.pubkey
= strv_dup (keyid
);
1366 crypto
->save
.sigkey
= strv_dup (sign_keyid
);
1371 crypto
->flags
|= symmetric
? CRYPTO_FLAG_SYMMETRIC
: 0;
1372 rc
= crypto_encrypt (NULL
, crypto
);
1378 if (!strcmp (outfile
, "-"))
1381 xfree (crypto
->plaintext
);
1382 crypto
->plaintext
= NULL
;
1383 xfree (crypto
->filename
);
1384 crypto
->filename
= outfile
? str_dup (outfile
) : NULL
;
1385 rc
= crypto_write_file (crypto
);
1389 crypto_free (crypto
);
1394 do_cache_push (struct crypto_s
*crypto
)
1398 struct cache_data_s
*cdata
;
1403 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1406 if (valid_filename (crypto
->filename
) == 0)
1408 log_write (_("%s: Invalid characters in filename"), crypto
->filename
);
1409 return GPG_ERR_INV_VALUE
;
1412 rc
= lock_flock (NULL
, crypto
->filename
, LOCK_SH
, &fd
);
1414 rc
= crypto_decrypt (NULL
, crypto
);
1421 rc
= xml_parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_size
, &doc
);
1425 log_write ("%s", pwmd_strerror (rc
));
1429 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1434 return GPG_ERR_ENOMEM
;
1437 rc
= get_checksum (crypto
->filename
, &crc
, &len
);
1442 cache_free_data_once (cdata
);
1447 rc
= cache_encrypt (crypto
);
1450 cdata
->doc
= crypto
->plaintext
;
1451 cdata
->size
= crypto
->plaintext_size
;
1452 crypto
->plaintext
= NULL
;
1453 cdata
->pubkey
= crypto
->pubkey
;
1454 cdata
->sigkey
= crypto
->sigkey
;
1455 crypto
->pubkey
= NULL
;
1456 crypto
->sigkey
= NULL
;
1461 cache_free_data_once (cdata
);
1465 int timeout
= config_get_integer (crypto
->filename
, "cache_timeout");
1466 rc
= cache_add_file (crypto
->filename
, cdata
, timeout
);
1471 init_client (int fd
, const char *addr
)
1474 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1479 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (ENOMEM
));
1480 return GPG_ERR_ENOMEM
;
1483 MUTEX_LOCK (&cn_mutex
);
1484 new->conntime
= time (NULL
);
1485 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
1487 if (pipe (new->status_msg_pipe
) == -1)
1488 rc
= gpg_error_from_errno (errno
);
1492 if (fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
) == -1)
1493 rc
= gpg_error_from_errno (errno
);
1496 if (fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
) == -1)
1497 rc
= gpg_error_from_errno (errno
);
1499 pthread_mutex_init (&new->status_mutex
, NULL
);
1505 new->remote
= addr
? 1 : 0;
1508 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1511 close (new->status_msg_pipe
[0]);
1512 close (new->status_msg_pipe
[1]);
1513 pthread_mutex_destroy (&new->status_mutex
);
1519 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1523 cn_thread_list
= list
;
1526 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1527 (pthread_t
*) new->tid
, fd
, addr
);
1529 new->peeraddr
= str_dup (addr
);
1533 log_write (_("new connection: tid=%p, fd=%i"),
1534 (pthread_t
*) new->tid
, fd
);
1537 rc
= GPG_ERR_ENOMEM
;
1540 pthread_cleanup_pop (1);
1546 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1547 pwmd_strerror (rc
));
1553 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1555 get_in_addr (struct sockaddr
*sa
)
1557 if (sa
->sa_family
== AF_INET
)
1558 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1560 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1564 start_stop_tls_with_protocol (int ipv6
, int term
)
1566 struct addrinfo hints
, *servinfo
, *p
;
1567 int port
= config_get_integer ("global", "tcp_port");
1570 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1572 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1576 shutdown (tls6_fd
, SHUT_RDWR
);
1583 shutdown (tls_fd
, SHUT_RDWR
);
1591 memset (&hints
, 0, sizeof (hints
));
1592 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1593 hints
.ai_socktype
= SOCK_STREAM
;
1594 hints
.ai_flags
= AI_PASSIVE
;
1595 snprintf (buf
, sizeof (buf
), "%i", port
);
1597 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1599 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1603 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1607 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1608 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1611 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1613 log_write ("socket(): %s", strerror (errno
));
1617 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1619 log_write ("setsockopt(): %s",
1620 pwmd_strerror (gpg_error_from_errno (errno
)));
1621 freeaddrinfo (servinfo
);
1625 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1628 log_write ("bind(): %s",
1629 pwmd_strerror (gpg_error_from_errno (errno
)));
1637 freeaddrinfo (servinfo
);
1642 #if HAVE_DECL_SO_BINDTODEVICE != 0
1643 char *tmp
= config_get_string ("global", "tcp_interface");
1644 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1645 strlen (tmp
)) == -1)
1647 log_write ("setsockopt(): %s",
1648 pwmd_strerror (gpg_error_from_errno (errno
)));
1656 if (listen (*fd
, 128) == -1)
1658 log_write ("listen(): %s", strerror (errno
));
1665 start_stop_tls_with_protocol (0, 1);
1678 start_stop_tls (int term
)
1680 char *s
= config_get_string ("global", "tcp_bind");
1686 if (!strcmp (s
, "any"))
1688 b
= start_stop_tls_with_protocol (0, term
);
1690 b
= start_stop_tls_with_protocol (1, term
);
1692 else if (!strcmp (s
, "ipv4"))
1693 b
= start_stop_tls_with_protocol (0, term
);
1694 else if (!strcmp (s
, "ipv6"))
1695 b
= start_stop_tls_with_protocol (1, term
);
1702 gpg_error_t rc
= tls_init_params ();
1705 start_stop_tls_with_protocol (0, 1);
1716 do_tls_accept (struct pollfd
*fds
)
1718 struct sockaddr_storage raddr
;
1719 socklen_t slen
= sizeof (raddr
);
1721 char s
[INET6_ADDRSTRLEN
];
1723 if (!(fds
->revents
& POLLIN
))
1726 fd
= accept (fds
->fd
, (struct sockaddr
*) &raddr
, &slen
);
1731 if (errno
!= EAGAIN
&& !quit
)
1732 log_write ("%s: %s", __FUNCTION__
,
1733 pwmd_strerror (gpg_error_from_syserror()));
1735 return gpg_error_from_errno (e
);
1738 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
), s
,
1740 (void) init_client (fd
, s
);
1746 accept_thread (void *arg
)
1748 int sockfd
= *(int *) arg
;
1749 #ifndef HAVE_PTHREAD_CANCEL
1750 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1751 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1754 #ifdef HAVE_PR_SET_NAME
1755 prctl (PR_SET_NAME
, "accept");
1757 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1761 socklen_t slen
= sizeof (struct sockaddr_un
);
1762 struct sockaddr_un raddr
;
1764 struct pollfd fds
[3];
1767 memset (fds
, 0, sizeof (fds
));
1769 fds
[s
++].events
= POLLIN
;
1775 fds
[s
++].events
= POLLIN
;
1782 fds
[s
].fd
= tls6_fd
;
1783 fds
[s
++].events
= POLLIN
;
1786 fds
[s
].fd
= tls6_fd
;
1789 s
= poll (fds
, s
, 500);
1793 log_write ("%s", strerror (errno
));
1799 if (fds
[0].revents
& POLLIN
)
1801 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1804 if (errno
== EMFILE
|| errno
== ENFILE
)
1805 log_write ("%s: %s", __FUNCTION__
,
1806 pwmd_strerror (gpg_error_from_errno (errno
)));
1807 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
1809 if (!quit
) // probably EBADF
1810 log_write ("%s: %s", __FUNCTION__
,
1811 pwmd_strerror (gpg_error_from_errno (errno
)));
1819 (void) init_client (fd
, NULL
);
1823 if (tls_fd
!= -1 && fds
[1].fd
== tls_fd
)
1824 (void)do_tls_accept (&fds
[1]);
1826 if (tls6_fd
!= -1 && fds
[1].fd
== tls6_fd
)
1827 (void)do_tls_accept (&fds
[1]);
1829 if (tls6_fd
!= -1 && fds
[2].fd
== tls6_fd
)
1830 (void)do_tls_accept (&fds
[2]);
1834 /* Just in case accept() failed for some reason other than EBADF */
1840 cache_timer_thread (void *arg
)
1843 #ifndef HAVE_PTHREAD_CANCEL
1844 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1847 #ifdef HAVE_PR_SET_NAME
1848 prctl (PR_SET_NAME
, "timer");
1850 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1854 struct timeval tv
= { 1, 0 };
1855 unsigned keepalive
= config_get_integer ("global", "keepalive_interval");
1858 select (0, NULL
, NULL
, NULL
, &tv
);
1859 cache_adjust_timeout ();
1861 if (++k
>= keepalive
)
1863 send_status_all (STATUS_KEEPALIVE
, NULL
);
1872 signal_loop (sigset_t sigset
)
1881 sigwait (&sigset
, &sig
);
1884 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1889 pthread_cond_signal (&rcfile_cond
);
1892 log_write (_("clearing file cache"));
1893 cache_clear (NULL
, NULL
, 1);
1894 send_status_all (STATUS_CACHE
, NULL
);
1913 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
1914 #ifdef HAVE_BACKTRACE
1915 BACKTRACE (__FUNCTION__
);
1921 waiting_for_exit (void *arg
)
1924 #ifndef HAVE_PTHREAD_CANCEL
1925 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1928 #ifdef HAVE_PR_SET_NAME
1929 prctl (PR_SET_NAME
, "exiting");
1931 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1932 log_write (_("waiting for all clients to disconnect"));
1933 MUTEX_LOCK (&quit_mutex
);
1934 pthread_cleanup_push (release_mutex_cb
, &quit_mutex
);
1941 MUTEX_LOCK (&cn_mutex
);
1942 n
= slist_length (cn_thread_list
);
1943 MUTEX_UNLOCK (&cn_mutex
);
1951 log_write (_("%i clients remain"), n
);
1955 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1956 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1959 kill (getpid (), SIGQUIT
);
1960 pthread_cleanup_pop (1);
1965 server_loop (int sockfd
, char **socketpath
)
1967 pthread_t cache_timeout_tid
;
1968 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1975 sigemptyset (&sigset
);
1978 sigaddset (&sigset
, SIGTERM
);
1979 sigaddset (&sigset
, SIGINT
);
1981 /* Clears the file cache. */
1982 sigaddset (&sigset
, SIGUSR1
);
1984 /* Configuration file reloading. */
1985 sigaddset (&sigset
, SIGHUP
);
1987 /* For exiting cleanly. */
1988 sigaddset (&sigset
, SIGQUIT
);
1990 #ifndef HAVE_PTHREAD_CANCEL
1992 The socket, cache and rcfile threads use this signal when
1993 pthread_cancel() is unavailable. Prevent the main thread from
1994 catching this signal from another process.
1996 sigaddset (&sigset
, SIGUSR2
);
1999 /* An assertion failure. */
2000 signal (SIGABRT
, catchsig
);
2001 sigaddset (&sigset
, SIGABRT
);
2002 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
2004 #ifndef HAVE_PTHREAD_CANCEL
2005 /* Remove this signal from the watched signals in signal_loop(). */
2006 sigdelset (&sigset
, SIGUSR2
);
2009 /* Can show a backtrace of the stack in the log. */
2010 signal (SIGSEGV
, catchsig
);
2012 pthread_mutex_init (&quit_mutex
, NULL
);
2013 pthread_cond_init (&quit_cond
, NULL
);
2014 char *p
= get_username (getuid());
2015 log_write (_("%s started for user %s"), PACKAGE_STRING
, p
);
2019 if (config_get_boolean ("global", "enable_tcp"))
2020 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
2021 config_get_integer ("global", "tcp_port"));
2023 log_write (_("Listening on %s"), *socketpath
);
2025 log_write (_("Listening on %s"), *socketpath
);
2028 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2031 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2032 pwmd_strerror (rc
));
2036 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2039 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2040 pwmd_strerror (rc
));
2044 cancel_timeout_thread
= 1;
2045 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2048 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2049 pwmd_strerror (rc
));
2053 cancel_accept_thread
= 1;
2055 signal_loop (sigset
);
2061 * We're out of the main server loop. This happens when a signal was sent
2062 * to terminate the daemon. We'll wait for all clients to disconnect
2063 * before exiting but exit immediately if another termination signal is
2066 if (cancel_accept_thread
)
2068 #ifdef HAVE_PTHREAD_CANCEL
2069 int n
= pthread_cancel (accept_tid
);
2071 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2074 pthread_join (accept_tid
, NULL
);
2077 if (cancel_timeout_thread
)
2079 #ifdef HAVE_PTHREAD_CANCEL
2080 n
= pthread_cancel (cache_timeout_tid
);
2082 n
= pthread_kill (cache_timeout_tid
, SIGUSR2
);
2085 pthread_join (cache_timeout_tid
, NULL
);
2091 shutdown (sockfd
, SHUT_RDWR
);
2093 unlink (*socketpath
);
2094 xfree (*socketpath
);
2096 MUTEX_LOCK (&cn_mutex
);
2097 n
= slist_length (cn_thread_list
);
2098 MUTEX_UNLOCK (&cn_mutex
);
2104 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2107 if (signal_loop (sigset
))
2109 log_write (_("Received second termination request. Exiting."));
2110 #ifdef HAVE_PTHREAD_CANCEL
2111 pthread_cancel (tid
);
2113 pthread_kill (tid
, SIGUSR2
);
2115 pthread_join (tid
, NULL
);
2119 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2120 pwmd_strerror (rc
));
2123 free_all_clients ();
2125 pthread_cond_destroy (&quit_cond
);
2126 pthread_mutex_destroy (&quit_mutex
);
2127 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2134 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2135 cache_clear (NULL
, NULL
, 1);
2139 usage (const char *pn
, int status
)
2141 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2143 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2144 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2145 " -f, --rcfile=filename load the specfied configuration file\n"
2146 " (~/.pwmd/config)\n"
2147 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2148 " --kill terminate an existing instance of pwmd\n"
2149 " -n, --no-fork run as a foreground process\n"
2150 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2151 " --ignore, --force ignore file errors during startup\n"
2152 " -o, --outfile=filename output file when importing or converting\n"
2153 " -C, --convert=filename convert a version 2 data file to version 3\n"
2154 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2155 " -k, --passphrase-file=file for use when importing or converting\n"
2156 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2158 " --no-passphrase when importing or converting\n"
2159 " --keyid=keyID[,..] public key to use when encrypting\n"
2160 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2161 " --symmetric use conventional encryption with optional signer\n"
2162 " --keyparam=filename custom key parameters to use (gpg default)\n"
2163 " --help this help text\n"
2164 " --version show version and compile time features\n"),
2170 unlink_stale_socket (const char *sock
, const char *pidfile
)
2172 log_write (_ ("removing stale socket %s"), sock
);
2178 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2179 char **pidfile
, int create
, mode_t mode
, int terminate
)
2187 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2188 *pidfile
= str_dup (buf
);
2189 fd
= open (buf
, O_RDONLY
);
2192 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2196 if (!create
&& errno
!= ENOENT
)
2198 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2203 else if (!create
&& !terminate
)
2206 log_write ("%s: %s", *pidfile
, strerror (errno
));
2212 snprintf (buf
, buflen
, "%i", getpid ());
2213 ssize_t ret
= write (fd
, buf
, strlen (buf
));
2215 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
,
2216 pwmd_strerror (gpg_error_from_syserror ()));
2221 len
= read (fd
, buf
, buflen
);
2225 unlink_stale_socket (path
, *pidfile
);
2229 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2233 unlink_stale_socket (path
, *pidfile
);
2238 if (kill (pid
, 0) == -1)
2240 unlink_stale_socket (path
, *pidfile
);
2246 if (kill (pid
, SIGTERM
) == -1)
2247 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2250 log_write (_ ("an instance for socket %s is already running"), path
);
2258 parse_debug_level (const char *str
, unsigned *debug
, int *gpgme
, int *tls
)
2264 for (p
= str
; p
&& *p
; p
++)
2266 if (*p
== 'a') // assuan debug flags
2276 level
|= ASSUAN_LOG_INIT
;
2279 level
|= ASSUAN_LOG_CTX
;
2282 level
|= ASSUAN_LOG_ENGINE
;
2285 level
|= ASSUAN_LOG_DATA
;
2288 level
|= ASSUAN_LOG_SYSIO
;
2291 level
|= ASSUAN_LOG_CONTROL
;
2306 else if (*p
== 'g' || *p
== 't') // gpgme and TLS debug level
2314 if (!isdigit (*++p
))
2323 if (tl
< 0 || gl
< 0 || gl
> 9)
2326 while (isdigit (*p
))
2330 if (*(p
+1) && *(p
+1) != ',')
2350 main (int argc
, char *argv
[])
2353 struct sockaddr_un addr
;
2355 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2356 char *socketarg
= NULL
;
2357 char *datadir
= NULL
;
2358 char *pidfile
= NULL
;
2362 char **cache_push
= NULL
;
2363 char *import
= NULL
, *keyid
= NULL
, *sign_keyid
= NULL
;
2364 char *keyparam
= NULL
;
2365 int estatus
= EXIT_FAILURE
;
2367 char *outfile
= NULL
;
2370 int show_version
= 0;
2373 char *keyfile
= NULL
;
2378 int gpgme_level
= -1;
2380 /* Must maintain the same order as longopts[] */
2383 OPT_VERSION
, OPT_HELP
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2384 OPT_FORCE
, OPT_RCFILE
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2385 OPT_KEYID
, OPT_SIGN_KEYID
, OPT_SYMMETRIC
, OPT_KEYPARAM
, OPT_KILL
,
2388 const char *optstring
= "nf:C:k:I:o:s";
2389 const struct option longopts
[] = {
2390 {"version", no_argument
, 0, 0},
2391 {"help", no_argument
, 0, 0},
2392 {"homedir", required_argument
, 0, 0},
2393 {"no-fork", no_argument
, 0, 'n'},
2394 {"disable_dump", no_argument
, 0, 0},
2395 {"force", no_argument
, 0, 0},
2396 {"rcfile", required_argument
, 0, 'f'},
2397 {"passphrase-file", required_argument
, 0, 'k'},
2398 {"import", required_argument
, 0, 'I'},
2399 {"outfile", required_argument
, 0, 'o'},
2400 {"keyid", required_argument
, 0, 0},
2401 {"sign-keyid", required_argument
, 0, 0},
2402 {"symmetric", no_argument
, 0, 's'},
2403 {"keyparam", required_argument
, 0, 0},
2404 {"kill", no_argument
, 0, 0},
2405 {"debug", required_argument
, 0, 0},
2413 #ifdef HAVE_SETRLIMIT
2416 rl
.rlim_cur
= rl
.rlim_max
= 0;
2418 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2419 err (EXIT_FAILURE
, "setrlimit()");
2422 #ifdef HAVE_PR_SET_DUMPABLE
2423 prctl (PR_SET_DUMPABLE
, 0);
2428 setlocale (LC_ALL
, "");
2429 bindtextdomain ("pwmd", LOCALEDIR
);
2430 textdomain ("pwmd");
2433 if (setup_crypto ())
2434 exit (EXIT_FAILURE
);
2437 tls_level
= tls_level
== -1 ? 1 : tls_level
;
2438 gnutls_global_set_log_level (tls_level
);
2442 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2448 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2469 rcfile
= str_dup (optarg
);
2475 usage (argv
[0], EXIT_FAILURE
);
2481 if (parse_debug_level (optarg
, &assuan_level
, &gpgme_level
,
2483 usage (argv
[0], EXIT_FAILURE
);
2492 usage (argv
[0], EXIT_SUCCESS
);
2495 homedir
= str_dup (optarg
);
2500 case OPT_DISABLE_DUMP
:
2507 rcfile
= str_dup (optarg
);
2509 case OPT_PASSPHRASE_FILE
:
2521 case OPT_SIGN_KEYID
:
2522 sign_keyid
= optarg
;
2531 usage (argv
[0], EXIT_FAILURE
);
2539 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2541 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2542 "Compile time features:\n%s"), PACKAGE_STRING
,
2545 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2573 exit (EXIT_SUCCESS
);
2578 homedir
= str_dup(PWMD_HOMEDIR
);
2580 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2583 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2584 err (EXIT_FAILURE
, "%s", homedir
);
2587 rcfile
= str_asprintf ("%s/config", homedir
);
2589 pthread_key_create (&last_error_key
, free_key
);
2590 #ifndef HAVE_PTHREAD_CANCEL
2591 pthread_key_create (&signal_thread_key
, free_key
);
2594 pthread_mutexattr_t attr
;
2595 pthread_mutexattr_init (&attr
);
2596 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2597 pthread_mutex_init (&rcfile_mutex
, &attr
);
2598 global_config
= config_parse (rcfile
, 0);
2601 pthread_mutexattr_destroy (&attr
);
2602 pthread_mutex_destroy (&rcfile_mutex
);
2603 exit (EXIT_FAILURE
);
2606 p
= config_get_string ("global", "gpg_homedir");
2608 datadir
= str_asprintf ("%s/.gnupg", homedir
);
2610 datadir
= expand_homedir (p
);
2613 if (mkdir (datadir
, 0700) == -1 && errno
!= EEXIST
)
2614 err (EXIT_FAILURE
, "%s", datadir
);
2616 if (gpgme_level
!= -1)
2618 char s
[2] = { gpgme_level
+ '0', 0 };
2620 if (getenv ("GPGME_DEBUG"))
2621 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2624 gpgme_set_global_flag ("debug", s
);
2627 rc
= gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP
, NULL
, datadir
);
2630 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2631 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2632 err (EXIT_FAILURE
, "%s", buf
);
2634 datadir
= str_dup (buf
);
2635 pthread_cond_init (&rcfile_cond
, NULL
);
2636 pthread_mutex_init (&cn_mutex
, &attr
);
2637 pthread_mutexattr_destroy (&attr
);
2641 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2642 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2645 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2647 log_write ("setpriority(): %s",
2648 pwmd_strerror (gpg_error_from_errno (errno
)));
2652 #ifdef HAVE_MLOCKALL
2653 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2655 log_write ("mlockall(): %s",
2656 pwmd_strerror (gpg_error_from_errno (errno
)));
2664 log_write ("pwmd: ERR %i: %s", rc
, pwmd_strerror (rc
));
2665 exit (EXIT_FAILURE
);
2670 char **keyids
= NULL
, **sign_keyids
= NULL
;
2672 if (!outfile
|| !*outfile
|| argc
!= optind
)
2673 usage (argv
[0], EXIT_FAILURE
);
2676 keyids
= str_split (keyid
, ",", 0);
2678 sign_keyids
= str_split (sign_keyid
, ",", 0);
2679 rc
= xml_import (import
, outfile
, keyids
, sign_keyids
, keyfile
, keyparam
, sym
);
2681 strv_free (sign_keyids
);
2684 if (gpg_err_source (rc
) == GPG_ERR_SOURCE_UNKNOWN
)
2685 rc
= gpg_error (rc
);
2687 log_write ("%s: %u: %s", import
, rc
, pwmd_strerror (rc
));
2690 config_free (global_config
);
2692 exit (rc
? EXIT_FAILURE
: EXIT_SUCCESS
);
2695 p
= config_get_string ("global", "socket_path");
2697 p
= str_asprintf ("%s/socket", homedir
);
2699 socketarg
= expand_homedir (p
);
2703 disable_list_and_dump
= config_get_boolean ("global",
2704 "disable_list_and_dump");
2706 disable_list_and_dump
= secure
;
2708 cache_push
= config_get_list ("global", "cache_push");
2710 while (optind
< argc
)
2712 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2713 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2716 if (strchr (socketarg
, '/') == NULL
)
2718 socketdir
= getcwd (buf
, sizeof (buf
));
2719 socketname
= str_dup (socketarg
);
2720 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2724 socketname
= str_dup (strrchr (socketarg
, '/'));
2726 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2727 socketdir
= str_dup (socketarg
);
2728 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2731 if (chdir (datadir
))
2733 log_write ("%s: %s", datadir
,
2734 pwmd_strerror (gpg_error_from_errno (errno
)));
2735 unlink (socketpath
);
2739 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
2741 if (!terminate
&& x
)
2745 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2750 * bind() doesn't like the full pathname of the socket or any non alphanum
2751 * characters so change to the directory where the socket is wanted then
2752 * create it then change to datadir.
2754 if (chdir (socketdir
))
2756 log_write ("%s: %s", socketdir
,
2757 pwmd_strerror (gpg_error_from_errno (errno
)));
2763 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2765 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2769 addr
.sun_family
= AF_UNIX
;
2770 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2772 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2775 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2777 if (errno
== EADDRINUSE
)
2780 log_write (_("Either there is another pwmd running or '%s' is a \n"
2781 "stale socket. Please remove it manually."), socketpath
);
2788 char *t
= config_get_string ("global", "socket_perms");
2793 mode
= strtol (t
, NULL
, 8);
2797 if (chmod (socketname
, mode
) == -1)
2799 log_write ("%s: %s", socketname
,
2800 pwmd_strerror (gpg_error_from_errno (errno
)));
2810 xfree (--socketname
);
2812 if (chdir (datadir
))
2814 log_write ("%s: %s", datadir
,
2815 pwmd_strerror (gpg_error_from_errno (errno
)));
2822 if (config_get_boolean ("global", "enable_tcp"))
2824 if (!start_stop_tls (0))
2833 * Set the cache entry for a file. Prompts for the password.
2837 for (opt
= 0; cache_push
[opt
]; opt
++)
2839 struct crypto_s
*crypto
= NULL
;
2840 char *pw_file
= config_get_string (cache_push
[opt
],
2842 gpg_error_t rc
= crypto_init (&crypto
, NULL
, cache_push
[opt
],
2843 pw_file
!= NULL
, pw_file
);
2847 crypto
->flags
|= pw_file
? CRYPTO_FLAG_KEYFILE
: 0;
2848 crypto
->keyfile
= pw_file
;
2855 estatus
= EXIT_FAILURE
;
2859 rc
= do_cache_push (crypto
);
2862 log_write ("ERR %u: %s", rc
, pwmd_strerror(rc
));
2863 strv_free (cache_push
);
2865 estatus
= EXIT_FAILURE
;
2866 crypto_free (crypto
);
2870 log_write ("%s: %s", crypto
->filename
, pwmd_strerror(rc
));
2872 log_write (_("Successfully added '%s' to the cache."),
2875 crypto_free (crypto
);
2878 strv_free (cache_push
);
2879 log_write (!nofork
? _("Done. Daemonizing...") :
2880 _("Done. Waiting for connections..."));
2883 if (listen (sockfd
, 128) == -1)
2885 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2894 log_write ("fork(): %s",
2895 pwmd_strerror (gpg_error_from_errno (errno
)));
2904 _exit (EXIT_SUCCESS
);
2908 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
2911 pthread_key_create (&thread_name_key
, free_key
);
2912 estatus
= server_loop (sockfd
, &socketpath
);
2915 if (socketpath
&& do_unlink
)
2917 unlink (socketpath
);
2923 gnutls_global_deinit ();
2924 tls_deinit_params ();
2928 #ifdef HAVE_PTHREAD_CANCEL
2929 pthread_cancel (rcfile_tid
);
2931 pthread_kill (rcfile_tid
, SIGUSR2
);
2932 pthread_cond_signal (&rcfile_cond
);
2934 pthread_join (rcfile_tid
, NULL
);
2937 pthread_cond_destroy (&rcfile_cond
);
2938 pthread_mutex_destroy (&rcfile_mutex
);
2939 pthread_key_delete (last_error_key
);
2940 #ifndef HAVE_PTHREAD_CANCEL
2941 pthread_key_delete (signal_thread_key
);
2945 config_free (global_config
);
2947 free_invoking_users (invoking_users
);
2949 xfree (home_directory
);
2951 xmlCleanupParser ();
2952 xmlCleanupGlobals ();
2958 if (estatus
== EXIT_SUCCESS
&& !terminate
)
2959 log_write (_("pwmd exiting normally"));
2961 pthread_key_delete (thread_name_key
);
2970 gpg_error_t
lock_flock (assuan_context_t ctx
, const char *filename
,
2976 *fd
= open (filename
, O_RDONLY
);
2978 return gpg_error_from_syserror ();
2980 TRY_FLOCK (ctx
, *fd
, type
, rc
);
2991 void unlock_flock (int *fd
)