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 #ifndef HAVE_PTHREAD_CANCEL
106 static pthread_key_t signal_thread_key
;
109 pthread_t accept_tid
;
113 static int start_stop_tls (int term
);
116 static gpg_error_t
do_cache_push (struct crypto_s
*crypto
);
117 static int signal_loop (sigset_t sigset
);
119 #ifndef HAVE_PTHREAD_CANCEL
120 #define INIT_SIGNAL(s, cb) do { \
121 struct sigaction act; \
123 sigemptyset (&sigset); \
124 sigaddset (&sigset, s); \
125 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
126 memset (&act, 0, sizeof(act)); \
127 act.sa_flags = SA_SIGINFO; \
128 act.sa_mask = sigset; \
129 act.sa_sigaction = cb; \
130 sigaction (s, &act, NULL); \
133 #define TEST_CANCEL() do { \
134 int *cancel = (int *) pthread_getspecific (signal_thread_key); \
135 if (cancel && *cancel) \
136 pthread_exit (NULL); \
139 #define TEST_CANCEL()
142 #ifndef HAVE_PTHREAD_CANCEL
144 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
146 int *n
= (int *) pthread_getspecific (signal_thread_key
);
149 pthread_setspecific (signal_thread_key
, n
);
156 int n
= config_get_boolean ("global", "enable_logging");
160 char *p
= config_get_string ("global", "log_path");
162 if (!p
|| (logfile
&& p
&& log_fd
!= -1 && strcmp(p
, logfile
)))
173 logfile
= expand_homedir (p
);
187 log_syslog
= config_get_boolean ("global", "syslog");
189 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
193 reload_rcfile_thread (void *arg
)
195 #ifndef HAVE_PTHREAD_CANCEL
196 int *n
= xmalloc (sizeof (int));
199 pthread_setspecific (signal_thread_key
, n
);
200 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
203 #ifdef HAVE_PR_SET_NAME
204 prctl (PR_SET_NAME
, "reload rcfile");
206 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
207 MUTEX_LOCK (&rcfile_mutex
);
211 struct slist_s
*keep
= NULL
;
212 struct slist_s
*config
;
213 int b
= disable_list_and_dump
;
219 pthread_cleanup_push (release_mutex_cb
, &rcfile_mutex
);
220 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
222 keep
= config_keep_save ();
223 log_write (_("reloading configuration file '%s'"), rcfile
);
225 prio
= config_get_string ("global", "tls_cipher_suite");
226 config
= config_parse (rcfile
, 1);
229 config_free (global_config
);
230 global_config
= config
;
234 config_keep_restore (keep
);
235 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
238 /* Restart listening sockets since they may have changed. */
242 prio2
= config_get_string ("global", "tls_cipher_suite");
243 if ((prio2
&& (!prio
|| strcmp (prio
, prio2
))) || (prio
&& !prio2
))
249 crypto_set_keepalive ();
250 pthread_cleanup_pop (0);
253 MUTEX_UNLOCK (&rcfile_mutex
);
258 send_error (assuan_context_t ctx
, gpg_error_t e
)
260 struct client_s
*client
= assuan_get_pointer (ctx
);
262 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
269 return assuan_process_done (ctx
, 0);
273 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
277 if (client
&& client
->xml_error
)
279 log_write ("%s", client
->xml_error
->message
);
280 xfree (client
->last_error
);
281 client
->last_error
= NULL
;
282 if (client
->xml_error
->message
)
283 client
->last_error
= str_dup (client
->xml_error
->message
);
285 e
= assuan_process_done (ctx
,
286 assuan_set_error (ctx
, e
,
287 client
->xml_error
->message
? client
->xml_error
->message
: NULL
));
288 xmlResetLastError ();
289 xmlResetError (client
->xml_error
);
290 xfree (client
->xml_error
);
291 client
->xml_error
= NULL
;
295 return assuan_process_done (ctx
,
296 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
300 log_write (const char *fmt
, ...)
306 pthread_t tid
= pthread_self ();
307 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
309 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
312 pthread_mutex_lock (&m
);
313 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
315 if (!cmdline
&& logfile
&& log_fd
== -1)
317 log_fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600);
319 warn ("%s", logfile
);
324 if (str_vasprintf (&args
, fmt
, ap
) != -1)
328 pthread_cleanup_push (xfree
, args
);
329 fprintf (stderr
, "pwmd: %s\n", args
);
331 pthread_cleanup_pop (1);
335 char *name
= pthread_getspecific (thread_name_key
);
338 pthread_cleanup_push (xfree
, args
);
339 snprintf (buf
, sizeof (buf
),
340 name
&& *name
== '!' ? "%s: " : name
? "%s(%p): " : "%s",
341 name
? *name
== '!' ? name
+1 : name
: "",
342 name
&& *name
== '!' ? 0 : name
? (pthread_t
*) tid
: 0);
345 if (!cmdline
&& log_syslog
&& !nofork
)
346 syslog (LOG_INFO
, "%s%s", name
, args
);
349 struct tm
*tm
= localtime (&now
);
351 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
352 tbuf
[sizeof (tbuf
) - 1] = 0;
354 if (args
[strlen (args
) - 1] == '\n')
355 args
[strlen (args
) - 1] = 0;
357 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
,
359 pthread_cleanup_pop (1);
362 pthread_cleanup_push (xfree
, line
);
363 if (logfile
&& log_fd
!= -1)
365 ssize_t ret
= write (log_fd
, line
, strlen (line
));
372 fprintf (stdout
, "%s", line
);
376 pthread_cleanup_pop (1);
382 pthread_cleanup_pop (0);
384 if (log_fd
!= -1 && log_keepopen
<= 0)
390 pthread_mutex_unlock (&m
);
398 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION
))
400 fprintf (stderr
, _("gpgrt_check_version(): Incompatible libgpg-error. "
401 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION
,
402 gpgrt_check_version (NULL
));
403 return GPG_ERR_UNKNOWN_VERSION
;
407 //gpgrt_set_alloc_func (xrealloc_gpgrt);
409 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION
))
411 fprintf (stderr
, _("assuan_check_version(): Incompatible libassuan. "
412 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION
,
413 assuan_check_version (NULL
));
414 return GPG_ERR_UNKNOWN_VERSION
;
417 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION
))
419 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
420 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION
,
421 gcry_check_version (NULL
));
422 return GPG_ERR_UNKNOWN_VERSION
;
425 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
427 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION
))
429 fprintf (stderr
, _("gpgme_check_version(): Incompatible libgpgme. "
430 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION
,
431 gpgme_check_version (NULL
));
432 return GPG_ERR_UNKNOWN_VERSION
;
435 rc
= gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP
);
438 fprintf (stderr
, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc
));
439 return GPG_ERR_UNKNOWN_VERSION
;
442 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
444 gpgme_set_locale (NULL
, LC_CTYPE
, setlocale (LC_CTYPE
, NULL
));
445 gpgme_set_locale (NULL
, LC_MESSAGES
, setlocale (LC_MESSAGES
, NULL
));
449 if (gnutls_global_init ())
451 fprintf(stderr
, _("gnutls_global_init() failed.\n"));
452 return GPG_ERR_UNKNOWN_VERSION
;
455 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION
))
457 fprintf (stderr
, _("gnutls_check_version(): Incompatible libgnutls. "
458 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION
,
459 gnutls_check_version (NULL
));
460 return GPG_ERR_UNKNOWN_VERSION
;
463 gnutls_global_set_log_function (tls_log
);
464 gnutls_global_set_audit_log_function (tls_audit_log
);
470 do_validate_peer (assuan_context_t ctx
, const char *section
,
471 assuan_peercred_t
* peer
)
476 struct client_s
*client
= assuan_get_pointer (ctx
);
479 return GPG_ERR_FORBIDDEN
;
482 if (client
->thd
->remote
)
483 return tls_validate_access (client
, section
);
486 rc
= assuan_get_peercred (ctx
, peer
);
490 users
= config_get_list (section
, "allowed");
493 for (char **p
= users
; !rc
&& *p
; p
++)
495 rc
= acl_check_common(client
, *p
, (*peer
)->uid
, (*peer
)->gid
,
501 else if (client
->no_access_param
)
504 return allowed
&& !rc
? 0 : rc
? rc
: GPG_ERR_FORBIDDEN
;
507 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
508 #ifdef HAVE_GETGRNAM_R
510 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
513 struct group gr
, *gresult
;
514 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
523 return GPG_ERR_ENOMEM
;
525 err
= getgrnam_r (name
, &gr
, buf
, len
, &gresult
);
528 if (gresult
->gr_gid
== gid
)
535 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
539 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &tbuf
, &rc
);
541 if (!rc
&& result
&& result
->pw_uid
== uid
)
555 rc
= gpg_error_from_errno (err
);
558 return rc
? rc
: !gresult
? 0 : GPG_ERR_EACCES
;
562 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
564 struct group
*gresult
;
568 gresult
= getgrnam (name
);
569 if (!errno
&& gresult
&& gresult
->gr_gid
== gid
)
575 rc
= gpg_error_from_syserror ();
579 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
583 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &buf
, &rc
);
585 if (!rc
&& result
&& result
->pw_uid
== uid
)
600 peer_is_invoker(struct client_s
*client
)
602 struct invoking_user_s
*user
;
605 if (client
->thd
->state
== CLIENT_STATE_UNKNOWN
)
606 return GPG_ERR_EACCES
;
608 for (user
= invoking_users
; user
; user
= user
->next
)
611 if (client
->thd
->remote
)
613 if (user
->type
== INVOKING_TLS
614 && !strcmp(client
->thd
->tls
->fp
, user
->id
))
615 allowed
= user
->not ? 0 : 1;
621 if (user
->type
== INVOKING_GID
)
623 gpg_error_t rc
= acl_check_group (user
->id
,
624 client
->thd
->peer
->uid
,
625 client
->thd
->peer
->gid
,
626 user
->not, &allowed
);
630 else if (user
->type
== INVOKING_UID
&& client
->thd
->peer
->uid
== user
->uid
)
631 allowed
= user
->not ? 0 : 1;
634 return allowed
? 0 : GPG_ERR_EACCES
;
637 #ifdef HAVE_GETGRNAM_R
639 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
640 gid_t gid
, int *allowed
)
650 if (*user
== '-' || *user
== '!')
653 if (*user
== '+') // not implemented yet
656 if (*user
== '#') // TLS fingerprint hash
659 if (not || rw
|| tls
)
665 if (client
->thd
->remote
)
667 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
677 else if (client
->thd
->remote
) // Remote client with no FP in the ACL
681 if (*user
== '@') // all users in group
682 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
687 struct passwd
*pwd
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
689 if (!rc
&& pwd
&& pwd
->pw_uid
== uid
)
699 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
700 gid_t gid
, int *allowed
)
710 if (*user
== '-' || *user
== '!')
713 if (*user
== '+') // not implemented yet
716 if (*user
== '#') // TLS fingerprint hash
719 if (not || rw
|| tls
)
725 if (client
->thd
->remote
)
727 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
737 if (*user
== '@') // all users in group
738 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
743 struct passwd
*result
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
745 if (!rc
&& result
&& result
->pw_uid
== uid
)
756 validate_peer (struct client_s
*cl
)
762 return tls_validate_access (cl
, NULL
);
765 MUTEX_LOCK (&cn_mutex
);
766 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
767 rc
= do_validate_peer (cl
->ctx
, "global", &cl
->thd
->peer
);
768 pthread_cleanup_pop (1);
769 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
770 !rc
? _("accepted") : _("rejected"), cl
->thd
->peer
->uid
,
771 cl
->thd
->peer
->gid
, cl
->thd
->peer
->pid
, rc
);
776 xml_error_cb (void *data
, xmlErrorPtr e
)
778 struct client_s
*client
= data
;
781 * Keep the first reported error as the one to show in the error
782 * description. Reset in send_error().
784 if (client
->xml_error
)
787 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
788 xmlCopyError (e
, client
->xml_error
);
792 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
793 int *status
, int options
)
795 return waitpid (pid
, status
, options
);
799 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
802 struct client_s
*client
= assuan_get_pointer (ctx
);
804 if (client
->thd
->remote
)
805 return tls_read_hook (ctx
, (int) fd
, data
, len
);
808 return read ((int) fd
, data
, len
);
812 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
813 const void *data
, size_t len
)
816 struct client_s
*client
= assuan_get_pointer (ctx
);
818 if (client
->thd
->remote
)
819 return tls_write_hook (ctx
, (int) fd
, data
, len
);
822 return write ((int) fd
, data
, len
);
826 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
829 struct client_s
*client
= data
;
834 if (!(assuan_level
& cat
))
842 case ASSUAN_LOG_INIT
:
843 str
= "ASSUAN[INIT]";
848 case ASSUAN_LOG_ENGINE
:
849 str
= "ASSUAN[ENGINE]";
851 case ASSUAN_LOG_DATA
:
852 str
= "ASSUAN[DATA]";
854 case ASSUAN_LOG_SYSIO
:
855 str
= "ASSUAN[SYSIO]";
857 case ASSUAN_LOG_CONTROL
:
858 str
= "ASSUAN[CONTROL]";
861 str
= "ASSUAN[UNKNOWN]";
865 log_write ("%s: %s", str
, msg
);
870 new_connection (struct client_s
*cl
)
873 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
874 static struct assuan_system_hooks shooks
= {
875 ASSUAN_SYSTEM_HOOKS_VERSION
,
883 NULL
, //sendmsg both are used for FD passing
894 char *prio
= config_get_string ("global", "tls_cipher_suite");
896 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
897 if (fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
) == -1)
900 cl
->thd
->tls
= tls_init_client (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
907 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
912 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
913 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
917 assuan_set_pointer (cl
->ctx
, cl
);
918 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
919 rc
= register_commands (cl
->ctx
);
923 rc
= assuan_accept (cl
->ctx
);
927 rc
= validate_peer (cl
);
928 /* May not be implemented on all platforms. */
929 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
932 MUTEX_LOCK (&cn_mutex
);
933 cl
->thd
->state
= CLIENT_STATE_INIT
;
934 MUTEX_UNLOCK (&cn_mutex
);
935 cl
->lock_timeout
= config_get_integer ("global", "lock_timeout");
936 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
940 log_write ("%s", pwmd_strerror (rc
));
945 * This is called after a client_thread() terminates. Set with
946 * pthread_cleanup_push().
949 free_client_cb (void *arg
)
951 struct client_thread_s
*cn
= arg
;
952 struct client_s
*cl
= cn
->cl
;
954 MUTEX_LOCK (&cn_mutex
);
955 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
956 MUTEX_UNLOCK (&cn_mutex
);
960 unlock_flock (&cl
->flock_fd
);
963 xmlResetError (cl
->xml_error
);
965 xfree (cl
->xml_error
);
970 gnutls_deinit (cn
->tls
->ses
);
977 assuan_release (cl
->ctx
);
978 else if (cl
->thd
&& cl
->thd
->fd
!= -1)
982 crypto_free (cl
->crypto
);
993 while (cn
->msg_queue
)
995 struct status_msg_s
*msg
= cn
->msg_queue
;
997 cn
->msg_queue
= msg
->next
;
1002 if (cn
->status_msg_pipe
[0] != -1)
1003 close (cn
->status_msg_pipe
[0]);
1005 if (cn
->status_msg_pipe
[1] != -1)
1006 close (cn
->status_msg_pipe
[1]);
1008 pthread_mutex_destroy (&cn
->status_mutex
);
1009 log_write (_("exiting, fd=%i"), cn
->fd
);
1010 send_status_all (STATUS_CLIENTS
, NULL
);
1014 xfree (cn
->peeraddr
);
1017 pthread_cond_signal (&quit_cond
);
1023 MUTEX_LOCK (&cn_mutex
);
1024 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
1026 while (slist_length (cn_thread_list
))
1028 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
1030 free_client_cb (thd
);
1034 pthread_cleanup_pop (1);
1039 send_msg_queue (struct client_thread_s
*thd
)
1041 MUTEX_LOCK (&thd
->status_mutex
);
1046 ret
= read (thd
->status_msg_pipe
[0], &c
, 1);
1047 rc
= gpg_error_from_syserror ();
1048 if (ret
== -1 && gpg_err_code (rc
) != GPG_ERR_EAGAIN
)
1049 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
1053 thd
->wrote_status
= 0;
1055 while (thd
->msg_queue
)
1057 struct status_msg_s
*msg
= thd
->msg_queue
;
1059 #ifndef HAVE_PTHREAD_CANCEL
1064 thd
->msg_queue
= thd
->msg_queue
->next
;
1065 MUTEX_UNLOCK (&thd
->status_mutex
);
1066 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
1067 MUTEX_LOCK (&thd
->status_mutex
);
1075 MUTEX_UNLOCK (&thd
->status_mutex
);
1076 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1077 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
1083 client_thread (void *data
)
1085 struct client_thread_s
*thd
= data
;
1086 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1088 #ifdef HAVE_PR_SET_NAME
1089 prctl (PR_SET_NAME
, "client");
1091 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1095 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1096 pwmd_strerror (GPG_ERR_ENOMEM
));
1100 MUTEX_LOCK (&cn_mutex
);
1101 pthread_cleanup_push (free_client_cb
, thd
);
1105 MUTEX_UNLOCK (&cn_mutex
);
1107 if (new_connection (cl
))
1111 struct pollfd fds
[2];
1113 fds
[0].fd
= thd
->fd
;
1114 fds
[0].events
= POLLIN
;
1115 fds
[1].fd
= thd
->status_msg_pipe
[0];
1116 fds
[1].events
= POLLIN
;
1118 send_status_all (STATUS_CLIENTS
, NULL
);
1119 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1122 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1131 n
= poll (fds
, 2, 100);
1134 log_write ("%s", strerror (errno
));
1139 if (thd
->remote
&& thd
->tls
&& thd
->tls
->rehandshake
)
1145 if (thd
->tls
->rehandshake
== 1)
1147 prio
= config_get_string ("global", "tls_cipher_suite");
1150 thd
->tls
->rehandshake
= 0;
1154 ret
= gnutls_priority_set_direct (thd
->tls
->ses
, prio
, &e
);
1155 if (ret
== GNUTLS_E_SUCCESS
)
1157 rc
= send_status (cl
->ctx
, STATUS_REHANDSHAKE
, NULL
);
1160 rc
= assuan_send_data (cl
->ctx
, NULL
, 0);
1163 ret
= gnutls_rehandshake (thd
->tls
->ses
);
1166 log_write ("%s", gnutls_strerror (ret
));
1167 thd
->tls
->rehandshake
= 0;
1170 thd
->tls
->rehandshake
= 2;
1175 log_write ("%s", pwmd_strerror (rc
));
1178 log_write ("%s: %s", gnutls_strerror (ret
), e
);
1189 if (fds
[1].revents
& POLLIN
)
1192 if (!thd
->remote
|| (thd
->tls
&& !thd
->tls
->rehandshake
))
1195 rc
= send_msg_queue (thd
);
1196 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1201 #ifdef HAVE_PTHREAD_CANCEL
1202 if (!(fds
[0].revents
& POLLIN
))
1204 if (thd
->fd
!= -1 && !(fds
[0].revents
& POLLIN
))
1208 rc
= assuan_process_next (cl
->ctx
, &eof
);
1211 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1214 log_write ("assuan_process_next(): rc=%u %s", rc
,
1215 pwmd_strerror (rc
));
1216 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1219 rc
= send_error (cl
->ctx
, rc
);
1222 log_write ("assuan_process_done(): rc=%u %s", rc
,
1223 pwmd_strerror (rc
));
1228 /* Since the msg queue pipe fd's are non-blocking, check for
1229 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1230 * client has already disconnected and will be converted to
1231 * GPG_ERR_EOF during assuan_process_next().
1234 if (!thd
->remote
|| (thd
->tls
&& !thd
->tls
->rehandshake
))
1237 rc
= send_msg_queue (thd
);
1238 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1244 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1245 * functions would be called after a command failed but then the client
1246 * exited normally which may lead to a double free. */
1247 pthread_cleanup_pop (1);
1252 xml_import (const char *filename
, const char *outfile
, char **keyid
,
1253 char **sign_keyid
, char *keyfile
, const char *keyparam
,
1262 struct crypto_s
*crypto
= NULL
;
1264 if (stat (filename
, &st
) == -1)
1266 rc
= gpg_error_from_errno (errno
);
1270 fd
= open (filename
, O_RDONLY
);
1272 return gpg_error_from_errno (errno
);
1274 xmlbuf
= xmalloc (st
.st_size
+ 1);
1278 return GPG_ERR_ENOMEM
;
1281 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1283 rc
= gpg_error_from_errno (errno
);
1290 xmlbuf
[st
.st_size
] = 0;
1291 // Be sure the document validates.
1292 doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
);
1295 return GPG_ERR_BAD_DATA
;
1297 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1298 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1299 rc
= GPG_ERR_BAD_DATA
;
1303 rc
= xml_validate_import (NULL
, n
? n
->children
: n
);
1306 rc
= crypto_init (&crypto
, NULL
, filename
, keyfile
!= NULL
, keyfile
);
1311 crypto
->flags
|= CRYPTO_FLAG_KEYFILE
;
1312 crypto
->keyfile
= str_dup (keyfile
);
1315 xmlDocDumpMemory (doc
, &crypto
->plaintext
, &len
);
1317 crypto
->plaintext_size
= len
;
1319 rc
= GPG_ERR_ENOMEM
;
1326 if (!symmetric
&& (keyparam
|| !keyid
))
1332 fd
= open (keyparam
, O_RDONLY
);
1334 rc
= gpg_error_from_errno (errno
);
1338 if (stat (keyparam
, &st
) == -1)
1339 rc
= gpg_error_from_errno (errno
);
1343 buf
= xmalloc (st
.st_size
+1);
1345 rc
= GPG_ERR_ENOMEM
;
1349 len
= read (fd
, buf
, st
.st_size
);
1350 if (len
!= st
.st_size
)
1351 rc
= gpg_error_from_errno (errno
);
1364 buf
= crypto_default_key_params ();
1366 rc
= GPG_ERR_ENOMEM
;
1370 rc
= crypto_genkey (NULL
, crypto
, (unsigned char *)buf
);
1376 crypto
->save
.pubkey
= strv_dup (keyid
);
1377 crypto
->save
.sigkey
= strv_dup (sign_keyid
);
1382 crypto
->flags
|= symmetric
? CRYPTO_FLAG_SYMMETRIC
: 0;
1383 rc
= crypto_encrypt (NULL
, crypto
);
1389 if (!strcmp (outfile
, "-"))
1392 xfree (crypto
->plaintext
);
1393 crypto
->plaintext
= NULL
;
1394 xfree (crypto
->filename
);
1395 crypto
->filename
= outfile
? str_dup (outfile
) : NULL
;
1396 rc
= crypto_write_file (crypto
);
1400 crypto_free (crypto
);
1405 do_cache_push (struct crypto_s
*crypto
)
1409 struct cache_data_s
*cdata
;
1414 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1417 if (valid_filename (crypto
->filename
) == 0)
1419 log_write (_("%s: Invalid characters in filename"), crypto
->filename
);
1420 return GPG_ERR_INV_VALUE
;
1423 rc
= lock_flock (NULL
, crypto
->filename
, LOCK_SH
, &fd
);
1425 rc
= crypto_decrypt (NULL
, crypto
);
1432 rc
= xml_parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_size
, &doc
);
1436 log_write ("%s", pwmd_strerror (rc
));
1440 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1445 return GPG_ERR_ENOMEM
;
1448 rc
= get_checksum (crypto
->filename
, &crc
, &len
);
1453 cache_free_data_once (cdata
);
1458 rc
= cache_encrypt (crypto
);
1461 cdata
->doc
= crypto
->plaintext
;
1462 cdata
->size
= crypto
->plaintext_size
;
1463 crypto
->plaintext
= NULL
;
1464 cdata
->pubkey
= crypto
->pubkey
;
1465 cdata
->sigkey
= crypto
->sigkey
;
1466 crypto
->pubkey
= NULL
;
1467 crypto
->sigkey
= NULL
;
1472 cache_free_data_once (cdata
);
1476 int timeout
= config_get_integer (crypto
->filename
, "cache_timeout");
1477 rc
= cache_add_file (crypto
->filename
, cdata
, timeout
);
1482 init_client (int fd
, const char *addr
)
1485 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1490 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (ENOMEM
));
1491 return GPG_ERR_ENOMEM
;
1494 MUTEX_LOCK (&cn_mutex
);
1495 new->conntime
= time (NULL
);
1496 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
1498 if (pipe (new->status_msg_pipe
) == -1)
1499 rc
= gpg_error_from_errno (errno
);
1503 if (fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
) == -1)
1504 rc
= gpg_error_from_errno (errno
);
1507 if (fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
) == -1)
1508 rc
= gpg_error_from_errno (errno
);
1510 pthread_mutex_init (&new->status_mutex
, NULL
);
1516 new->remote
= addr
? 1 : 0;
1519 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1522 close (new->status_msg_pipe
[0]);
1523 close (new->status_msg_pipe
[1]);
1524 pthread_mutex_destroy (&new->status_mutex
);
1530 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1534 cn_thread_list
= list
;
1537 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1538 (pthread_t
*) new->tid
, fd
, addr
);
1540 new->peeraddr
= str_dup (addr
);
1544 log_write (_("new connection: tid=%p, fd=%i"),
1545 (pthread_t
*) new->tid
, fd
);
1548 rc
= GPG_ERR_ENOMEM
;
1551 pthread_cleanup_pop (1);
1557 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1558 pwmd_strerror (rc
));
1564 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1566 get_in_addr (struct sockaddr
*sa
)
1568 if (sa
->sa_family
== AF_INET
)
1569 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1571 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1575 start_stop_tls_with_protocol (int ipv6
, int term
)
1577 struct addrinfo hints
, *servinfo
, *p
;
1578 int port
= config_get_integer ("global", "tcp_port");
1581 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1583 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1587 shutdown (tls6_fd
, SHUT_RDWR
);
1594 shutdown (tls_fd
, SHUT_RDWR
);
1602 memset (&hints
, 0, sizeof (hints
));
1603 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1604 hints
.ai_socktype
= SOCK_STREAM
;
1605 hints
.ai_flags
= AI_PASSIVE
;
1606 snprintf (buf
, sizeof (buf
), "%i", port
);
1608 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1610 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1614 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1618 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1619 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1622 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1624 log_write ("socket(): %s", strerror (errno
));
1628 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1630 log_write ("setsockopt(): %s",
1631 pwmd_strerror (gpg_error_from_errno (errno
)));
1632 freeaddrinfo (servinfo
);
1636 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1639 log_write ("bind(): %s",
1640 pwmd_strerror (gpg_error_from_errno (errno
)));
1648 freeaddrinfo (servinfo
);
1653 #if HAVE_DECL_SO_BINDTODEVICE != 0
1654 char *tmp
= config_get_string ("global", "tcp_interface");
1655 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1656 strlen (tmp
)) == -1)
1658 log_write ("setsockopt(): %s",
1659 pwmd_strerror (gpg_error_from_errno (errno
)));
1667 if (listen (*fd
, 128) == -1)
1669 log_write ("listen(): %s", strerror (errno
));
1676 start_stop_tls_with_protocol (0, 1);
1689 start_stop_tls (int term
)
1691 char *s
= config_get_string ("global", "tcp_bind");
1697 if (!strcmp (s
, "any"))
1699 b
= start_stop_tls_with_protocol (0, term
);
1701 b
= start_stop_tls_with_protocol (1, term
);
1703 else if (!strcmp (s
, "ipv4"))
1704 b
= start_stop_tls_with_protocol (0, term
);
1705 else if (!strcmp (s
, "ipv6"))
1706 b
= start_stop_tls_with_protocol (1, term
);
1713 gpg_error_t rc
= tls_init_params ();
1716 start_stop_tls_with_protocol (0, 1);
1727 do_tls_accept (struct pollfd
*fds
)
1729 struct sockaddr_storage raddr
;
1730 socklen_t slen
= sizeof (raddr
);
1732 char s
[INET6_ADDRSTRLEN
];
1734 if (!(fds
->revents
& POLLIN
))
1737 fd
= accept (fds
->fd
, (struct sockaddr
*) &raddr
, &slen
);
1742 if (errno
!= EAGAIN
&& !quit
)
1743 log_write ("%s: %s", __FUNCTION__
,
1744 pwmd_strerror (gpg_error_from_syserror()));
1746 return gpg_error_from_errno (e
);
1749 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
), s
,
1751 (void) init_client (fd
, s
);
1757 accept_thread (void *arg
)
1759 int sockfd
= *(int *) arg
;
1760 #ifndef HAVE_PTHREAD_CANCEL
1761 int *n
= xmalloc (sizeof (int));
1764 pthread_setspecific (signal_thread_key
, n
);
1765 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1766 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1769 #ifdef HAVE_PR_SET_NAME
1770 prctl (PR_SET_NAME
, "accept");
1772 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1776 socklen_t slen
= sizeof (struct sockaddr_un
);
1777 struct sockaddr_un raddr
;
1779 struct pollfd fds
[3];
1782 memset (fds
, 0, sizeof (fds
));
1784 fds
[s
++].events
= POLLIN
;
1790 fds
[s
++].events
= POLLIN
;
1797 fds
[s
].fd
= tls6_fd
;
1798 fds
[s
++].events
= POLLIN
;
1801 fds
[s
].fd
= tls6_fd
;
1804 s
= poll (fds
, s
, 500);
1808 log_write ("%s", strerror (errno
));
1814 if (fds
[0].revents
& POLLIN
)
1816 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1819 if (errno
== EMFILE
|| errno
== ENFILE
)
1820 log_write ("%s: %s", __FUNCTION__
,
1821 pwmd_strerror (gpg_error_from_errno (errno
)));
1822 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
1824 if (!quit
) // probably EBADF
1825 log_write ("%s: %s", __FUNCTION__
,
1826 pwmd_strerror (gpg_error_from_errno (errno
)));
1834 (void) init_client (fd
, NULL
);
1838 if (tls_fd
!= -1 && fds
[1].fd
== tls_fd
)
1839 (void)do_tls_accept (&fds
[1]);
1841 if (tls6_fd
!= -1 && fds
[1].fd
== tls6_fd
)
1842 (void)do_tls_accept (&fds
[1]);
1844 if (tls6_fd
!= -1 && fds
[2].fd
== tls6_fd
)
1845 (void)do_tls_accept (&fds
[2]);
1849 /* Just in case accept() failed for some reason other than EBADF */
1855 cache_timer_thread (void *arg
)
1858 #ifndef HAVE_PTHREAD_CANCEL
1859 int *n
= xmalloc (sizeof (int));
1862 pthread_setspecific (signal_thread_key
, n
);
1863 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1866 #ifdef HAVE_PR_SET_NAME
1867 prctl (PR_SET_NAME
, "timer");
1869 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1873 struct timeval tv
= { 1, 0 };
1874 unsigned keepalive
= config_get_integer ("global", "keepalive_interval");
1877 select (0, NULL
, NULL
, NULL
, &tv
);
1878 cache_adjust_timeout ();
1880 if (++k
>= keepalive
)
1882 send_status_all (STATUS_KEEPALIVE
, NULL
);
1891 signal_loop (sigset_t sigset
)
1900 sigwait (&sigset
, &sig
);
1903 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1908 pthread_cond_signal (&rcfile_cond
);
1911 log_write (_("clearing file cache"));
1912 cache_clear (NULL
, NULL
, 1);
1913 send_status_all (STATUS_CACHE
, NULL
);
1932 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
1933 #ifdef HAVE_BACKTRACE
1934 BACKTRACE (__FUNCTION__
);
1940 waiting_for_exit (void *arg
)
1943 #ifndef HAVE_PTHREAD_CANCEL
1944 int *n
= xmalloc (sizeof (int));
1947 pthread_setspecific (signal_thread_key
, n
);
1948 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1951 #ifdef HAVE_PR_SET_NAME
1952 prctl (PR_SET_NAME
, "exiting");
1954 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1955 log_write (_("waiting for all clients to disconnect"));
1956 MUTEX_LOCK (&quit_mutex
);
1957 pthread_cleanup_push (release_mutex_cb
, &quit_mutex
);
1964 MUTEX_LOCK (&cn_mutex
);
1965 n
= slist_length (cn_thread_list
);
1966 MUTEX_UNLOCK (&cn_mutex
);
1974 log_write (_("%i clients remain"), n
);
1978 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1979 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1982 kill (getpid (), SIGQUIT
);
1983 pthread_cleanup_pop (1);
1988 server_loop (int sockfd
, char **socketpath
)
1990 pthread_t cache_timeout_tid
;
1991 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1998 sigemptyset (&sigset
);
2001 sigaddset (&sigset
, SIGTERM
);
2002 sigaddset (&sigset
, SIGINT
);
2004 /* Clears the file cache. */
2005 sigaddset (&sigset
, SIGUSR1
);
2007 /* Configuration file reloading. */
2008 sigaddset (&sigset
, SIGHUP
);
2010 /* For exiting cleanly. */
2011 sigaddset (&sigset
, SIGQUIT
);
2013 #ifndef HAVE_PTHREAD_CANCEL
2015 The socket, cache and rcfile threads use this signal when
2016 pthread_cancel() is unavailable. Prevent the main thread from
2017 catching this signal from another process.
2019 sigaddset (&sigset
, SIGUSR2
);
2022 /* An assertion failure. */
2023 signal (SIGABRT
, catchsig
);
2024 sigaddset (&sigset
, SIGABRT
);
2025 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
2027 #ifndef HAVE_PTHREAD_CANCEL
2028 /* Remove this signal from the watched signals in signal_loop(). */
2029 sigdelset (&sigset
, SIGUSR2
);
2032 /* Can show a backtrace of the stack in the log. */
2033 signal (SIGSEGV
, catchsig
);
2035 pthread_mutex_init (&quit_mutex
, NULL
);
2036 pthread_cond_init (&quit_cond
, NULL
);
2037 char *p
= get_username (getuid());
2038 log_write (_("%s started for user %s"), PACKAGE_STRING
, p
);
2042 if (config_get_boolean ("global", "enable_tcp"))
2043 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
2044 config_get_integer ("global", "tcp_port"));
2046 log_write (_("Listening on %s"), *socketpath
);
2048 log_write (_("Listening on %s"), *socketpath
);
2051 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2054 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2055 pwmd_strerror (rc
));
2059 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2062 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2063 pwmd_strerror (rc
));
2067 cancel_timeout_thread
= 1;
2068 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2071 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2072 pwmd_strerror (rc
));
2076 cancel_accept_thread
= 1;
2078 signal_loop (sigset
);
2084 * We're out of the main server loop. This happens when a signal was sent
2085 * to terminate the daemon. We'll wait for all clients to disconnect
2086 * before exiting but exit immediately if another termination signal is
2089 if (cancel_accept_thread
)
2091 #ifdef HAVE_PTHREAD_CANCEL
2092 int n
= pthread_cancel (accept_tid
);
2094 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2097 pthread_join (accept_tid
, NULL
);
2100 if (cancel_timeout_thread
)
2102 #ifdef HAVE_PTHREAD_CANCEL
2103 n
= pthread_cancel (cache_timeout_tid
);
2105 n
= pthread_kill (cache_timeout_tid
, SIGUSR2
);
2108 pthread_join (cache_timeout_tid
, NULL
);
2114 shutdown (sockfd
, SHUT_RDWR
);
2116 unlink (*socketpath
);
2117 xfree (*socketpath
);
2119 MUTEX_LOCK (&cn_mutex
);
2120 n
= slist_length (cn_thread_list
);
2121 MUTEX_UNLOCK (&cn_mutex
);
2127 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2130 if (signal_loop (sigset
))
2132 log_write (_("Received second termination request. Exiting."));
2133 #ifdef HAVE_PTHREAD_CANCEL
2134 pthread_cancel (tid
);
2136 pthread_kill (tid
, SIGUSR2
);
2138 pthread_join (tid
, NULL
);
2142 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2143 pwmd_strerror (rc
));
2146 free_all_clients ();
2148 pthread_cond_destroy (&quit_cond
);
2149 pthread_mutex_destroy (&quit_mutex
);
2150 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2157 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2158 cache_clear (NULL
, NULL
, 1);
2162 usage (const char *pn
, int status
)
2164 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2166 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2167 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2168 " -f, --rcfile=filename load the specfied configuration file\n"
2169 " (~/.pwmd/config)\n"
2170 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2171 " --kill terminate an existing instance of pwmd\n"
2172 " -n, --no-fork run as a foreground process\n"
2173 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2174 " --ignore, --force ignore file errors during startup\n"
2175 " -o, --outfile=filename output file when importing or converting\n"
2176 " -C, --convert=filename convert a version 2 data file to version 3\n"
2177 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2178 " -k, --passphrase-file=file for use when importing or converting\n"
2179 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2181 " --no-passphrase when importing or converting\n"
2182 " --keyid=keyID[,..] public key to use when encrypting\n"
2183 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2184 " --symmetric use conventional encryption with optional signer\n"
2185 " --keyparam=filename custom key parameters to use (gpg default)\n"
2186 " --help this help text\n"
2187 " --version show version and compile time features\n"),
2193 unlink_stale_socket (const char *sock
, const char *pidfile
)
2195 log_write (_ ("removing stale socket %s"), sock
);
2201 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2202 char **pidfile
, int create
, mode_t mode
, int terminate
)
2210 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2211 *pidfile
= str_dup (buf
);
2212 fd
= open (buf
, O_RDONLY
);
2215 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2219 if (!create
&& errno
!= ENOENT
)
2221 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2226 else if (!create
&& !terminate
)
2229 log_write ("%s: %s", *pidfile
, strerror (errno
));
2235 snprintf (buf
, buflen
, "%i", getpid ());
2236 ssize_t ret
= write (fd
, buf
, strlen (buf
));
2238 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
,
2239 pwmd_strerror (gpg_error_from_syserror ()));
2244 len
= read (fd
, buf
, buflen
);
2248 unlink_stale_socket (path
, *pidfile
);
2252 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2256 unlink_stale_socket (path
, *pidfile
);
2261 if (kill (pid
, 0) == -1)
2263 unlink_stale_socket (path
, *pidfile
);
2269 if (kill (pid
, SIGTERM
) == -1)
2270 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2273 log_write (_ ("an instance for socket %s is already running"), path
);
2281 parse_debug_level (const char *str
, unsigned *debug
, int *gpgme
, int *tls
)
2287 for (p
= str
; p
&& *p
; p
++)
2289 if (*p
== 'a') // assuan debug flags
2299 level
|= ASSUAN_LOG_INIT
;
2302 level
|= ASSUAN_LOG_CTX
;
2305 level
|= ASSUAN_LOG_ENGINE
;
2308 level
|= ASSUAN_LOG_DATA
;
2311 level
|= ASSUAN_LOG_SYSIO
;
2314 level
|= ASSUAN_LOG_CONTROL
;
2329 else if (*p
== 'g' || *p
== 't') // gpgme and TLS debug level
2337 if (!isdigit (*++p
))
2346 if (tl
< 0 || gl
< 0 || gl
> 9)
2349 while (isdigit (*p
))
2353 if (*(p
+1) && *(p
+1) != ',')
2373 main (int argc
, char *argv
[])
2376 struct sockaddr_un addr
;
2378 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2379 char *socketarg
= NULL
;
2380 char *datadir
= NULL
;
2381 char *pidfile
= NULL
;
2385 char **cache_push
= NULL
;
2386 char *import
= NULL
, *keyid
= NULL
, *sign_keyid
= NULL
;
2387 char *keyparam
= NULL
;
2388 int estatus
= EXIT_FAILURE
;
2390 char *outfile
= NULL
;
2393 int show_version
= 0;
2396 char *keyfile
= NULL
;
2401 int gpgme_level
= -1;
2403 /* Must maintain the same order as longopts[] */
2406 OPT_VERSION
, OPT_HELP
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2407 OPT_FORCE
, OPT_RCFILE
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2408 OPT_KEYID
, OPT_SIGN_KEYID
, OPT_SYMMETRIC
, OPT_KEYPARAM
, OPT_KILL
,
2411 const char *optstring
= "nf:C:k:I:o:s";
2412 const struct option longopts
[] = {
2413 {"version", no_argument
, 0, 0},
2414 {"help", no_argument
, 0, 0},
2415 {"homedir", required_argument
, 0, 0},
2416 {"no-fork", no_argument
, 0, 'n'},
2417 {"disable_dump", no_argument
, 0, 0},
2418 {"force", no_argument
, 0, 0},
2419 {"rcfile", required_argument
, 0, 'f'},
2420 {"passphrase-file", required_argument
, 0, 'k'},
2421 {"import", required_argument
, 0, 'I'},
2422 {"outfile", required_argument
, 0, 'o'},
2423 {"keyid", required_argument
, 0, 0},
2424 {"sign-keyid", required_argument
, 0, 0},
2425 {"symmetric", no_argument
, 0, 's'},
2426 {"keyparam", required_argument
, 0, 0},
2427 {"kill", no_argument
, 0, 0},
2428 {"debug", required_argument
, 0, 0},
2436 #ifdef HAVE_SETRLIMIT
2439 rl
.rlim_cur
= rl
.rlim_max
= 0;
2441 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2442 err (EXIT_FAILURE
, "setrlimit()");
2445 #ifdef HAVE_PR_SET_DUMPABLE
2446 prctl (PR_SET_DUMPABLE
, 0);
2451 setlocale (LC_ALL
, "");
2452 bindtextdomain ("pwmd", LOCALEDIR
);
2453 textdomain ("pwmd");
2456 if (setup_crypto ())
2457 exit (EXIT_FAILURE
);
2460 tls_level
= tls_level
== -1 ? 1 : tls_level
;
2461 gnutls_global_set_log_level (tls_level
);
2465 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2471 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2492 rcfile
= str_dup (optarg
);
2498 usage (argv
[0], EXIT_FAILURE
);
2504 if (parse_debug_level (optarg
, &assuan_level
, &gpgme_level
,
2506 usage (argv
[0], EXIT_FAILURE
);
2515 usage (argv
[0], EXIT_SUCCESS
);
2518 homedir
= str_dup (optarg
);
2523 case OPT_DISABLE_DUMP
:
2530 rcfile
= str_dup (optarg
);
2532 case OPT_PASSPHRASE_FILE
:
2544 case OPT_SIGN_KEYID
:
2545 sign_keyid
= optarg
;
2554 usage (argv
[0], EXIT_FAILURE
);
2562 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2564 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2565 "Compile time features:\n%s"), PACKAGE_STRING
,
2568 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2596 exit (EXIT_SUCCESS
);
2601 homedir
= str_dup(PWMD_HOMEDIR
);
2603 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2606 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2607 err (EXIT_FAILURE
, "%s", homedir
);
2610 rcfile
= str_asprintf ("%s/config", homedir
);
2612 pthread_key_create (&last_error_key
, free_key
);
2613 #ifndef HAVE_PTHREAD_CANCEL
2614 pthread_key_create (&signal_thread_key
, free_key
);
2617 pthread_mutexattr_t attr
;
2618 pthread_mutexattr_init (&attr
);
2619 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2620 pthread_mutex_init (&rcfile_mutex
, &attr
);
2621 global_config
= config_parse (rcfile
, 0);
2624 pthread_mutexattr_destroy (&attr
);
2625 pthread_mutex_destroy (&rcfile_mutex
);
2626 exit (EXIT_FAILURE
);
2629 p
= config_get_string ("global", "gpg_homedir");
2631 datadir
= str_asprintf ("%s/.gnupg", homedir
);
2633 datadir
= expand_homedir (p
);
2636 if (mkdir (datadir
, 0700) == -1 && errno
!= EEXIST
)
2637 err (EXIT_FAILURE
, "%s", datadir
);
2639 if (gpgme_level
!= -1)
2641 char s
[2] = { gpgme_level
+ '0', 0 };
2643 if (getenv ("GPGME_DEBUG"))
2644 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2647 gpgme_set_global_flag ("debug", s
);
2650 rc
= gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP
, NULL
, datadir
);
2653 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2654 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2655 err (EXIT_FAILURE
, "%s", buf
);
2657 datadir
= str_dup (buf
);
2658 pthread_cond_init (&rcfile_cond
, NULL
);
2659 pthread_mutex_init (&cn_mutex
, &attr
);
2660 pthread_mutexattr_destroy (&attr
);
2664 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2665 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2668 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2670 log_write ("setpriority(): %s",
2671 pwmd_strerror (gpg_error_from_errno (errno
)));
2675 #ifdef HAVE_MLOCKALL
2676 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2678 log_write ("mlockall(): %s",
2679 pwmd_strerror (gpg_error_from_errno (errno
)));
2687 log_write ("pwmd: ERR %i: %s", rc
, pwmd_strerror (rc
));
2688 exit (EXIT_FAILURE
);
2693 char **keyids
= NULL
, **sign_keyids
= NULL
;
2695 if (!outfile
|| !*outfile
|| argc
!= optind
)
2696 usage (argv
[0], EXIT_FAILURE
);
2699 keyids
= str_split (keyid
, ",", 0);
2701 sign_keyids
= str_split (sign_keyid
, ",", 0);
2702 rc
= xml_import (import
, outfile
, keyids
, sign_keyids
, keyfile
, keyparam
, sym
);
2704 strv_free (sign_keyids
);
2707 if (gpg_err_source (rc
) == GPG_ERR_SOURCE_UNKNOWN
)
2708 rc
= gpg_error (rc
);
2710 log_write ("%s: %u: %s", import
, rc
, pwmd_strerror (rc
));
2713 config_free (global_config
);
2715 exit (rc
? EXIT_FAILURE
: EXIT_SUCCESS
);
2718 p
= config_get_string ("global", "socket_path");
2720 p
= str_asprintf ("%s/socket", homedir
);
2722 socketarg
= expand_homedir (p
);
2726 disable_list_and_dump
= config_get_boolean ("global",
2727 "disable_list_and_dump");
2729 disable_list_and_dump
= secure
;
2731 cache_push
= config_get_list ("global", "cache_push");
2733 while (optind
< argc
)
2735 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2736 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2739 if (strchr (socketarg
, '/') == NULL
)
2741 socketdir
= getcwd (buf
, sizeof (buf
));
2742 socketname
= str_dup (socketarg
);
2743 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2747 socketname
= str_dup (strrchr (socketarg
, '/'));
2749 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2750 socketdir
= str_dup (socketarg
);
2751 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2754 if (chdir (datadir
))
2756 log_write ("%s: %s", datadir
,
2757 pwmd_strerror (gpg_error_from_errno (errno
)));
2758 unlink (socketpath
);
2762 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
2764 if (!terminate
&& x
)
2768 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2773 * bind() doesn't like the full pathname of the socket or any non alphanum
2774 * characters so change to the directory where the socket is wanted then
2775 * create it then change to datadir.
2777 if (chdir (socketdir
))
2779 log_write ("%s: %s", socketdir
,
2780 pwmd_strerror (gpg_error_from_errno (errno
)));
2786 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2788 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2792 addr
.sun_family
= AF_UNIX
;
2793 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2795 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2798 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2800 if (errno
== EADDRINUSE
)
2803 log_write (_("Either there is another pwmd running or '%s' is a \n"
2804 "stale socket. Please remove it manually."), socketpath
);
2811 char *t
= config_get_string ("global", "socket_perms");
2816 mode
= strtol (t
, NULL
, 8);
2820 if (chmod (socketname
, mode
) == -1)
2822 log_write ("%s: %s", socketname
,
2823 pwmd_strerror (gpg_error_from_errno (errno
)));
2833 xfree (--socketname
);
2835 if (chdir (datadir
))
2837 log_write ("%s: %s", datadir
,
2838 pwmd_strerror (gpg_error_from_errno (errno
)));
2845 if (config_get_boolean ("global", "enable_tcp"))
2847 if (!start_stop_tls (0))
2856 * Set the cache entry for a file. Prompts for the password.
2860 for (opt
= 0; cache_push
[opt
]; opt
++)
2862 struct crypto_s
*crypto
= NULL
;
2863 char *pw_file
= config_get_string (cache_push
[opt
],
2865 gpg_error_t rc
= crypto_init (&crypto
, NULL
, cache_push
[opt
],
2866 pw_file
!= NULL
, pw_file
);
2870 crypto
->flags
|= pw_file
? CRYPTO_FLAG_KEYFILE
: 0;
2871 crypto
->keyfile
= pw_file
;
2878 estatus
= EXIT_FAILURE
;
2882 rc
= do_cache_push (crypto
);
2885 log_write ("ERR %u: %s", rc
, pwmd_strerror(rc
));
2886 strv_free (cache_push
);
2888 estatus
= EXIT_FAILURE
;
2889 crypto_free (crypto
);
2893 log_write ("%s: %s", crypto
->filename
, pwmd_strerror(rc
));
2895 log_write (_("Successfully added '%s' to the cache."),
2898 crypto_free (crypto
);
2901 strv_free (cache_push
);
2902 log_write (!nofork
? _("Done. Daemonizing...") :
2903 _("Done. Waiting for connections..."));
2906 if (listen (sockfd
, 128) == -1)
2908 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2917 log_write ("fork(): %s",
2918 pwmd_strerror (gpg_error_from_errno (errno
)));
2927 _exit (EXIT_SUCCESS
);
2931 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
2934 pthread_key_create (&thread_name_key
, free_key
);
2935 estatus
= server_loop (sockfd
, &socketpath
);
2938 if (socketpath
&& do_unlink
)
2940 unlink (socketpath
);
2946 gnutls_global_deinit ();
2947 tls_deinit_params ();
2951 #ifdef HAVE_PTHREAD_CANCEL
2952 pthread_cancel (rcfile_tid
);
2954 pthread_kill (rcfile_tid
, SIGUSR2
);
2955 pthread_cond_signal (&rcfile_cond
);
2957 pthread_join (rcfile_tid
, NULL
);
2960 pthread_cond_destroy (&rcfile_cond
);
2961 pthread_mutex_destroy (&rcfile_mutex
);
2962 pthread_key_delete (last_error_key
);
2963 #ifndef HAVE_PTHREAD_CANCEL
2964 pthread_key_delete (signal_thread_key
);
2968 config_free (global_config
);
2970 free_invoking_users (invoking_users
);
2972 xfree (home_directory
);
2974 xmlCleanupParser ();
2975 xmlCleanupGlobals ();
2981 if (estatus
== EXIT_SUCCESS
&& !terminate
)
2982 log_write (_("pwmd exiting normally"));
2984 pthread_key_delete (thread_name_key
);
2993 gpg_error_t
lock_flock (assuan_context_t ctx
, const char *filename
,
2999 *fd
= open (filename
, O_RDONLY
);
3001 return gpg_error_from_syserror ();
3003 TRY_FLOCK (ctx
, *fd
, type
, rc
);
3014 void unlock_flock (int *fd
)