2 Copyright (C) 2006-2020 Ben Kibbey <bjk@luxsci.net>
4 This file is part of pwmd.
6 Pwmd is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 2 of the License, or
9 (at your option) any later version.
11 Pwmd is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
29 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
47 #include <sys/resource.h>
62 #ifdef HAVE_GETOPT_LONG
67 #include "getopt_long.h"
70 #ifdef HAVE_PR_SET_NAME
71 #include <sys/prctl.h>
74 #include "pwmd-error.h"
77 #include "util-misc.h"
83 #include "util-string.h"
95 static unsigned assuan_level
;
97 #ifndef HAVE_PTHREAD_CANCEL
98 #define INIT_SIGNAL(s, cb) do { \
99 int *n = xmalloc (sizeof (int)); \
101 pthread_setspecific (signal_thread_key, n); \
102 struct sigaction act; \
104 sigemptyset (&sigset); \
105 sigaddset (&sigset, s); \
106 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
107 memset (&act, 0, sizeof(act)); \
108 act.sa_flags = SA_SIGINFO; \
109 act.sa_mask = sigset; \
110 act.sa_sigaction = cb; \
111 sigaction (s, &act, NULL); \
115 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
117 int *n
= (int *) pthread_getspecific (signal_thread_key
);
126 int n
= config_get_boolean ("global", "enable_logging");
130 char *p
= config_get_string ("global", "log_path");
132 if (!p
|| (logfile
&& p
&& log_fd
!= -1 && strcmp(p
, logfile
)))
143 logfile
= expand_homedir (p
);
157 log_syslog
= config_get_boolean ("global", "syslog");
159 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
163 reload_rcfile_thread (void *arg
)
165 #ifndef HAVE_PTHREAD_CANCEL
166 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
169 #ifdef HAVE_PR_SET_NAME
170 prctl (PR_SET_NAME
, "reload rcfile");
172 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
173 MUTEX_LOCK (&rcfile_mutex
);
179 struct slist_s
*keep
= NULL
;
180 struct slist_s
*config
;
181 int b
= disable_list_and_dump
;
187 pthread_cleanup_push (release_mutex_cb
, &rcfile_mutex
);
188 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
190 keep
= config_keep_save ();
191 log_write (_("reloading configuration file '%s'"), rcfile
);
194 prio
= config_get_string ("global", "tls_cipher_suite");
196 config
= config_parse (rcfile
, 1);
199 config_free (global_config
);
200 global_config
= config
;
204 config_keep_restore (keep
);
205 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
208 /* Restart listening sockets since they may have changed. */
212 prio2
= config_get_string ("global", "tls_cipher_suite");
213 if ((prio2
&& (!prio
|| strcmp (prio
, prio2
))) || (prio
&& !prio2
))
219 crypto_set_keepalive ();
220 pthread_cleanup_pop (0);
223 MUTEX_UNLOCK (&rcfile_mutex
);
227 #define PROCESS_DONE(client,rc) (client && client->bulk_p) ? rc : \
228 assuan_process_done (client ? client->ctx : NULL, rc)
230 send_error (assuan_context_t ctx
, gpg_error_t e
)
232 struct client_s
*client
= assuan_get_pointer (ctx
);
234 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
241 return PROCESS_DONE (client
, 0);
245 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
249 if (client
&& client
->xml_error
)
251 log_write ("%s", client
->xml_error
->message
);
252 xfree (client
->last_error
);
253 client
->last_error
= NULL
;
254 if (client
->xml_error
->message
)
255 client
->last_error
= str_dup (client
->xml_error
->message
);
257 e
= PROCESS_DONE (client
, assuan_set_error (ctx
, e
,
258 client
->xml_error
->message
259 ? client
->xml_error
->message
261 xmlResetLastError ();
262 xmlResetError (client
->xml_error
);
263 xfree (client
->xml_error
);
264 client
->xml_error
= NULL
;
268 return PROCESS_DONE (client
, assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
272 log_write (const char *fmt
, ...)
278 pthread_t tid
= pthread_self ();
279 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
281 if ((!logfile
&& !nofork
&& !log_syslog
&& !cmdline
) || !fmt
)
285 pthread_cleanup_push (release_mutex_cb
, &m
);
287 if (!cmdline
&& logfile
&& log_fd
== -1)
289 log_fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600);
291 warn ("%s", logfile
);
296 if (str_vasprintf (&args
, fmt
, ap
) != -1)
298 pthread_cleanup_push (xfree
, args
);
301 fprintf (stderr
, "pwmd: %s\n", args
);
306 char *name
= pthread_getspecific (thread_name_key
);
312 snprintf (buf
, sizeof (buf
), "%s: ", name
+1);
314 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
,
318 snprintf (buf
, sizeof (buf
), "%p: ", (pthread_t
*)tid
);
321 if (!cmdline
&& log_syslog
&& !nofork
)
322 syslog (LOG_INFO
, "%s%s", name
, args
);
325 struct tm
*tm
= localtime (&now
);
327 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
328 tbuf
[sizeof (tbuf
) - 1] = 0;
330 if (args
[strlen (args
) - 1] == '\n')
331 args
[strlen (args
) - 1] = 0;
333 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
, args
);
336 pthread_cleanup_push (xfree
, line
);
337 if (logfile
&& log_fd
!= -1)
339 ssize_t ret
= write (log_fd
, line
, strlen (line
));
346 fprintf (stdout
, "%s", line
);
350 pthread_cleanup_pop (1);
353 pthread_cleanup_pop (1);
358 if (log_fd
!= -1 && log_keepopen
<= 0)
364 pthread_cleanup_pop (1);
372 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION
))
374 fprintf (stderr
, _("gpgrt_check_version(): Incompatible libgpg-error. "
375 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION
,
376 gpgrt_check_version (NULL
));
377 return GPG_ERR_UNKNOWN_VERSION
;
381 gpgrt_set_alloc_func (xrealloc_gpgrt
);
383 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION
))
385 fprintf (stderr
, _("assuan_check_version(): Incompatible libassuan. "
386 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION
,
387 assuan_check_version (NULL
));
388 return GPG_ERR_UNKNOWN_VERSION
;
391 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION
))
393 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
394 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION
,
395 gcry_check_version (NULL
));
396 return GPG_ERR_UNKNOWN_VERSION
;
399 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
401 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION
))
403 fprintf (stderr
, _("gpgme_check_version(): Incompatible libgpgme. "
404 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION
,
405 gpgme_check_version (NULL
));
406 return GPG_ERR_UNKNOWN_VERSION
;
409 rc
= gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP
);
412 fprintf (stderr
, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc
));
413 return GPG_ERR_UNKNOWN_VERSION
;
416 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
418 gpgme_set_locale (NULL
, LC_CTYPE
, setlocale (LC_CTYPE
, NULL
));
419 gpgme_set_locale (NULL
, LC_MESSAGES
, setlocale (LC_MESSAGES
, NULL
));
423 if (gnutls_global_init ())
425 fprintf(stderr
, _("gnutls_global_init() failed.\n"));
426 return GPG_ERR_UNKNOWN_VERSION
;
429 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION
))
431 fprintf (stderr
, _("gnutls_check_version(): Incompatible libgnutls. "
432 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION
,
433 gnutls_check_version (NULL
));
434 return GPG_ERR_UNKNOWN_VERSION
;
437 gnutls_global_set_log_function (tls_log
);
438 gnutls_global_set_audit_log_function (tls_audit_log
);
444 xml_error_cb (void *data
, xmlErrorPtr e
)
446 struct client_s
*client
= data
;
449 * Keep the first reported error as the one to show in the error
450 * description. Reset in send_error().
452 if (client
->xml_error
)
455 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
456 xmlCopyError (e
, client
->xml_error
);
460 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
461 int *status
, int options
)
465 return waitpid (pid
, status
, options
);
469 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
473 struct client_s
*client
= assuan_get_pointer (ctx
);
475 if (client
->thd
->remote
)
476 return tls_read_hook (ctx
, (int) fd
, data
, len
);
480 return read ((int) fd
, data
, len
);
484 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
485 const void *data
, size_t len
)
489 struct client_s
*client
= assuan_get_pointer (ctx
);
491 if (client
->thd
->remote
)
492 return tls_write_hook (ctx
, (int) fd
, data
, len
);
496 return write ((int) fd
, data
, len
);
500 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
503 struct client_s
*client
= data
;
504 const char *str
= NULL
;
509 if (!(assuan_level
& cat
))
517 case ASSUAN_LOG_INIT
:
518 str
= "ASSUAN[INIT]";
523 case ASSUAN_LOG_ENGINE
:
524 str
= "ASSUAN[ENGINE]";
526 case ASSUAN_LOG_DATA
:
527 str
= "ASSUAN[DATA]";
529 case ASSUAN_LOG_SYSIO
:
530 str
= "ASSUAN[SYSIO]";
532 case ASSUAN_LOG_CONTROL
:
533 str
= "ASSUAN[CONTROL]";
536 str
= "ASSUAN[UNKNOWN]";
540 log_write ("%s: %s", str
, msg
);
545 new_connection (struct client_s
*cl
)
548 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
549 static struct assuan_system_hooks shooks
= {
550 ASSUAN_SYSTEM_HOOKS_VERSION
,
558 NULL
, //sendmsg both are used for FD passing
569 char *prio
= config_get_string ("global", "tls_cipher_suite");
571 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
572 if (fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
) == -1)
575 cl
->thd
->tls
= tls_init_client (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
582 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
587 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
588 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
,
589 ASSUAN_SOCKET_SERVER_ACCEPTED
);
593 assuan_set_pointer (cl
->ctx
, cl
);
594 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING PWMD_GIT_HASH
);
595 rc
= register_commands (cl
->ctx
);
599 rc
= assuan_accept (cl
->ctx
);
603 rc
= validate_peer (cl
);
604 /* May not be implemented on all platforms. */
605 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
608 MUTEX_LOCK (&cn_mutex
);
609 cl
->thd
->state
= CLIENT_STATE_INIT
;
610 MUTEX_UNLOCK (&cn_mutex
);
611 cl
->lock_timeout
= config_get_integer ("global", "lock_timeout");
612 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
616 log_write ("%s", pwmd_strerror (rc
));
621 * This is called after a client is cancelled or disconnects. Set with
622 * pthread_cleanup_push().
625 free_client_cb (void *arg
)
627 struct client_thread_s
*cn
= arg
;
628 struct client_s
*cl
= cn
->cl
;
631 #ifndef HAVE_PTHREAD_CANCEL
632 tmp
= pthread_getspecific (signal_thread_key
);
634 pthread_setspecific (signal_thread_key
, NULL
);
637 MUTEX_LOCK (&cn_mutex
);
638 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
639 MUTEX_UNLOCK (&cn_mutex
);
643 unlock_flock (&cl
->flock_fd
);
646 xmlResetError (cl
->xml_error
);
648 xfree (cl
->xml_error
);
653 gnutls_deinit (cn
->tls
->ses
);
660 assuan_release (cl
->ctx
);
661 else if (cl
->thd
&& cl
->thd
->fd
!= -1)
665 crypto_free (cl
->crypto
);
676 while (cn
->msg_queue
)
678 struct status_msg_s
*msg
= cn
->msg_queue
;
680 cn
->msg_queue
= msg
->next
;
685 if (cn
->status_msg_pipe
[0] != -1)
686 close (cn
->status_msg_pipe
[0]);
688 if (cn
->status_msg_pipe
[1] != -1)
689 close (cn
->status_msg_pipe
[1]);
691 pthread_mutex_destroy (&cn
->status_mutex
);
692 log_write (_("exiting, fd=%i"), cn
->fd
);
693 send_status_all (STATUS_CLIENTS
, NULL
);
697 xfree (cn
->peeraddr
);
700 if (cn
->eof
) // Not pthread_exit() or pthread_cancel().
702 tmp
= pthread_getspecific (thread_name_key
);
704 pthread_setspecific (thread_name_key
, NULL
);
707 (void)cache_kill_scd ();
714 MUTEX_LOCK (&cn_mutex
);
715 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
717 while (slist_length (cn_thread_list
))
719 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
721 free_client_cb (thd
);
725 pthread_cleanup_pop (1);
729 send_msg_queue (struct client_thread_s
*thd
)
731 MUTEX_LOCK (&thd
->status_mutex
);
736 ret
= read (thd
->status_msg_pipe
[0], &c
, 1);
737 rc
= gpg_error_from_syserror ();
738 if (ret
== -1 && gpg_err_code (rc
) != GPG_ERR_EAGAIN
)
739 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
743 thd
->wrote_status
= 0;
745 while (thd
->msg_queue
)
747 struct status_msg_s
*msg
= thd
->msg_queue
;
749 thd
->msg_queue
= thd
->msg_queue
->next
;
750 MUTEX_UNLOCK (&thd
->status_mutex
);
751 pthread_cleanup_push (xfree
, msg
);
752 pthread_cleanup_push (xfree
, msg
->line
);
753 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
754 pthread_cleanup_pop (1);
755 pthread_cleanup_pop (1);
756 MUTEX_LOCK (&thd
->status_mutex
);
761 MUTEX_UNLOCK (&thd
->status_mutex
);
762 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
763 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
769 client_thread (void *data
)
771 struct client_thread_s
*thd
= data
;
772 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
773 struct slist_s
*list
;
775 #ifndef HAVE_PTHREAD_CANCEL
776 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
779 #ifdef HAVE_PR_SET_NAME
780 prctl (PR_SET_NAME
, "client");
782 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
786 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
787 pwmd_strerror (GPG_ERR_ENOMEM
));
791 MUTEX_LOCK (&cn_mutex
);
792 pthread_cleanup_push (free_client_cb
, thd
);
797 list
= slist_append (cn_thread_list
, thd
);
799 cn_thread_list
= list
;
802 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
803 pwmd_strerror (GPG_ERR_ENOMEM
));
804 MUTEX_UNLOCK (&cn_mutex
);
808 if (fcntl (thd
->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
) == -1)
809 rc
= gpg_error_from_errno (errno
);
812 if (fcntl (thd
->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
) == -1)
813 rc
= gpg_error_from_errno (errno
);
815 MUTEX_UNLOCK (&cn_mutex
);
819 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
823 if (new_connection (cl
))
825 struct pollfd fds
[2];
828 fds
[0].events
= POLLIN
;
829 fds
[1].fd
= thd
->status_msg_pipe
[0];
830 fds
[1].events
= POLLIN
;
832 send_status_all (STATUS_CLIENTS
, NULL
);
833 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
836 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
845 n
= poll (fds
, sizeof(fds
)/sizeof(fds
[0]), 100);
848 log_write ("%s", strerror (errno
));
853 if (thd
->remote
&& thd
->tls
&& thd
->tls
->rehandshake
)
859 if (thd
->tls
->rehandshake
== 1)
861 prio
= config_get_string ("global", "tls_cipher_suite");
864 thd
->tls
->rehandshake
= 0;
868 ret
= gnutls_priority_set_direct (thd
->tls
->ses
, prio
, &e
);
869 if (ret
== GNUTLS_E_SUCCESS
)
871 rc
= send_status (cl
->ctx
, STATUS_REHANDSHAKE
, NULL
);
874 rc
= assuan_send_data (cl
->ctx
, NULL
, 0);
877 ret
= gnutls_rehandshake (thd
->tls
->ses
);
880 log_write ("%s", gnutls_strerror (ret
));
881 thd
->tls
->rehandshake
= 0;
884 thd
->tls
->rehandshake
= 2;
889 log_write ("%s", pwmd_strerror (rc
));
892 log_write ("%s: %s", gnutls_strerror (ret
), e
);
903 if (fds
[1].revents
& POLLIN
)
906 if (!thd
->remote
|| (thd
->tls
&& !thd
->tls
->rehandshake
))
909 rc
= send_msg_queue (thd
);
910 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
915 #ifdef HAVE_PTHREAD_CANCEL
916 if (!(fds
[0].revents
& POLLIN
))
918 if (thd
->fd
!= -1 && !(fds
[0].revents
& POLLIN
))
922 rc
= assuan_process_next (cl
->ctx
, &eof
);
925 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
928 log_write ("assuan_process_next(): rc=%u %s", rc
,
930 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
933 rc
= send_error (cl
->ctx
, rc
);
936 log_write ("assuan_process_done(): rc=%u %s", rc
,
942 /* Since the msg queue pipe fd's are non-blocking, check for
943 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
944 * client has already disconnected and will be converted to
945 * GPG_ERR_EOF during assuan_process_next().
948 if (!thd
->remote
|| (thd
->tls
&& !thd
->tls
->rehandshake
))
951 rc
= send_msg_queue (thd
);
952 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
959 /* Don't do pthread_exit() here because any set pthread_cleanup_push
960 * functions would be called after a command failed but then the client
961 * exited normally which may lead to a double free. */
963 pthread_cleanup_pop (1);
968 xml_import (const char *filename
, const char *outfile
, char **keyid
,
969 char *sign_keyid
, char *keyfile
, const char *userid
,
970 const char *algo
, long expire
, int no_passphrase
, int symmetric
)
976 xmlChar
*xmlbuf
= NULL
;
978 struct crypto_s
*crypto
= NULL
;
980 if (strcmp (filename
, "-"))
982 rc
= open_check_file (filename
, &fd
, &st
, 0);
986 xmlbuf
= xmalloc (st
.st_size
+ 1);
990 return GPG_ERR_ENOMEM
;
993 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
995 rc
= gpg_error_from_errno (errno
);
1001 xmlbuf
[st
.st_size
] = 0;
1006 #define BUFSIZE 8196
1007 size_t size
= 0, xlen
= 0;
1014 tmp
= xrealloc (xmlbuf
, size
+BUFSIZE
+1);
1018 return GPG_ERR_ENOMEM
;
1023 ret
= read (STDIN_FILENO
, &xmlbuf
[xlen
], BUFSIZE
);
1026 rc
= gpg_error_from_syserror ();
1032 if (!ret
|| ret
< BUFSIZE
)
1039 doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
);
1042 return GPG_ERR_BAD_DATA
;
1044 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1045 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1046 rc
= GPG_ERR_BAD_DATA
;
1050 rc
= xml_validate_import (NULL
, n
? n
->children
: n
);
1053 rc
= crypto_init (&crypto
, NULL
, filename
, keyfile
!= NULL
, keyfile
);
1058 crypto
->flags
|= CRYPTO_FLAG_KEYFILE
;
1059 crypto
->keyfile
= str_dup (keyfile
);
1062 xmlDocDumpMemory (doc
, &crypto
->plaintext
, &len
);
1064 crypto
->plaintext_size
= len
;
1066 rc
= GPG_ERR_ENOMEM
;
1073 if (!symmetric
&& !keyid
)
1075 crypto
->save
.userid
= str_dup (userid
);
1076 crypto
->save
.algo
= algo
? str_dup (algo
) : NULL
;
1077 crypto
->save
.expire
= expire
;
1079 crypto
->save
.flags
|= GPGME_CREATE_NOPASSWD
;
1081 rc
= crypto_genkey (NULL
, crypto
);
1086 crypto
->save
.pubkey
= strv_dup (keyid
);
1089 crypto
->save
.sigkey
= str_dup (sign_keyid
);
1094 crypto
->flags
|= symmetric
? CRYPTO_FLAG_SYMMETRIC
: 0;
1095 rc
= crypto_encrypt (NULL
, crypto
);
1101 if (!strcmp (outfile
, "-"))
1104 xfree (crypto
->plaintext
);
1105 crypto
->plaintext
= NULL
;
1106 xfree (crypto
->filename
);
1107 crypto
->filename
= outfile
? str_dup (outfile
) : NULL
;
1108 rc
= crypto_write_file (crypto
, NULL
, NULL
);
1112 crypto_free (crypto
);
1117 do_cache_push (struct crypto_s
*crypto
)
1121 struct cache_data_s
*cdata
;
1126 log_write (_("Adding '%s' to the cache..."),
1129 if (valid_filename (crypto
->filename
) == 0)
1131 log_write (_("%s: Invalid characters in filename"), crypto
->filename
);
1132 return GPG_ERR_INV_VALUE
;
1135 rc
= lock_flock (NULL
, crypto
->filename
, LOCK_SH
, &fd
);
1137 rc
= crypto_decrypt (NULL
, crypto
);
1144 rc
= xml_parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_size
, &doc
);
1148 log_write ("%s", pwmd_strerror (rc
));
1152 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1157 return GPG_ERR_ENOMEM
;
1160 rc
= get_checksum (crypto
->filename
, &crc
, &len
);
1165 cache_free_data_once (cdata
);
1170 rc
= cache_encrypt (crypto
);
1173 cdata
->doc
= crypto
->plaintext
;
1174 cdata
->size
= crypto
->plaintext_size
;
1175 crypto
->plaintext
= NULL
;
1176 cdata
->pubkey
= crypto
->pubkey
;
1177 cdata
->sigkey
= crypto
->sigkey
;
1178 crypto
->pubkey
= NULL
;
1179 crypto
->sigkey
= NULL
;
1184 cache_free_data_once (cdata
);
1188 long timeout
= config_get_long (crypto
->filename
, "cache_timeout");
1189 rc
= cache_add_file (crypto
->filename
, cdata
, timeout
);
1194 init_client (int fd
, const char *addr
)
1197 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1202 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (ENOMEM
));
1203 return GPG_ERR_ENOMEM
;
1206 MUTEX_LOCK (&cn_mutex
);
1207 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
1208 new->conntime
= time (NULL
);
1210 if (pipe (new->status_msg_pipe
) == -1)
1211 rc
= gpg_error_from_errno (errno
);
1213 pthread_mutex_init (&new->status_mutex
, NULL
);
1218 new->remote
= addr
? 1 : 0;
1220 new->peeraddr
= str_dup (addr
);
1223 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1226 close (new->status_msg_pipe
[0]);
1227 close (new->status_msg_pipe
[1]);
1228 pthread_mutex_destroy (&new->status_mutex
);
1235 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1236 (pthread_t
*) new->tid
, fd
, addr
);
1238 log_write (_("new connection: tid=%p, fd=%i"),
1239 (pthread_t
*) new->tid
, fd
);
1242 pthread_cleanup_pop (1);
1248 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1255 do_tls_accept (struct pollfd
*fds
)
1257 struct sockaddr_storage raddr
;
1258 socklen_t slen
= sizeof (raddr
);
1260 char s
[INET6_ADDRSTRLEN
];
1262 if (!(fds
->revents
& POLLIN
))
1265 memset (&raddr
, 0, sizeof (raddr
));
1266 fd
= accept (fds
->fd
, (struct sockaddr
*) &raddr
, &slen
);
1271 if (errno
!= EAGAIN
&& !quit
)
1272 log_write ("%s: %s", __FUNCTION__
,
1273 pwmd_strerror (gpg_error_from_syserror()));
1275 return gpg_error_from_errno (e
);
1278 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
), s
,
1280 (void) init_client (fd
, s
);
1286 accept_thread (void *arg
)
1288 int sockfd
= *(int *) arg
;
1289 #ifndef HAVE_PTHREAD_CANCEL
1290 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1293 #ifdef HAVE_PR_SET_NAME
1294 prctl (PR_SET_NAME
, "accept");
1296 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1300 socklen_t slen
= sizeof (struct sockaddr_un
);
1301 struct sockaddr_un raddr
;
1303 struct pollfd fds
[3];
1306 memset (fds
, 0, sizeof (fds
));
1308 fds
[s
++].events
= POLLIN
;
1314 fds
[s
++].events
= POLLIN
;
1321 fds
[s
].fd
= tls6_fd
;
1322 fds
[s
++].events
= POLLIN
;
1325 fds
[s
].fd
= tls6_fd
;
1328 s
= poll (fds
, s
, 500);
1332 log_write ("%s", strerror (errno
));
1338 if (fds
[0].revents
& POLLIN
)
1340 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1343 if (errno
== EMFILE
|| errno
== ENFILE
)
1344 log_write ("%s: %s", __FUNCTION__
,
1345 pwmd_strerror (gpg_error_from_errno (errno
)));
1346 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
1348 if (!quit
) // probably EBADF
1349 log_write ("%s: %s", __FUNCTION__
,
1350 pwmd_strerror (gpg_error_from_errno (errno
)));
1358 (void) init_client (fd
, NULL
);
1362 if (tls_fd
!= -1 && fds
[1].fd
== tls_fd
)
1363 (void)do_tls_accept (&fds
[1]);
1365 if (tls6_fd
!= -1 && fds
[1].fd
== tls6_fd
)
1366 (void)do_tls_accept (&fds
[1]);
1368 if (tls6_fd
!= -1 && fds
[2].fd
== tls6_fd
)
1369 (void)do_tls_accept (&fds
[2]);
1373 /* Just in case accept() failed for some reason other than EBADF */
1379 cache_timer_thread (void *arg
)
1382 #ifndef HAVE_PTHREAD_CANCEL
1383 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1388 #ifdef HAVE_PR_SET_NAME
1389 prctl (PR_SET_NAME
, "timer");
1391 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1395 struct timeval tv
= { 1, 0 };
1396 unsigned keepalive
= config_get_integer ("global", "keepalive_interval");
1399 select (0, NULL
, NULL
, NULL
, &tv
);
1400 cache_adjust_timeout ();
1402 if (keepalive
&& ++k
>= keepalive
)
1404 send_status_all (STATUS_KEEPALIVE
, NULL
);
1413 signal_loop (sigset_t sigset
)
1421 sigwait (&sigset
, &sig
);
1422 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1427 pthread_cond_signal (&rcfile_cond
);
1430 log_write (_("clearing file cache"));
1431 cache_clear (NULL
, NULL
, 1, 0);
1432 send_status_all (STATUS_CACHE
, NULL
);
1447 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
1448 #ifdef HAVE_BACKTRACE
1449 BACKTRACE (__FUNCTION__
);
1455 cancel_all_clients ()
1459 MUTEX_LOCK (&cn_mutex
);
1460 t
= slist_length (cn_thread_list
);
1461 for (i
= 0; i
< t
; i
++)
1463 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
1465 #ifdef HAVE_PTHREAD_CANCEL
1466 pthread_cancel (thd
->tid
);
1468 pthread_kill (thd
->tid
, SIGUSR2
);
1472 while (slist_length (cn_thread_list
))
1474 MUTEX_UNLOCK (&cn_mutex
);
1476 MUTEX_LOCK (&cn_mutex
);
1479 MUTEX_UNLOCK (&cn_mutex
);
1483 server_loop (int sockfd
, char **socketpath
)
1485 pthread_t cache_timeout_tid
;
1486 pthread_t accept_tid
;
1487 int cancel_timeout_thread
= 0;
1488 int cancel_accept_thread
= 0;
1489 int cancel_rcfile_thread
= 0;
1496 sigemptyset (&sigset
);
1499 sigaddset (&sigset
, SIGTERM
);
1500 sigaddset (&sigset
, SIGINT
);
1502 /* Clears the file cache. */
1503 sigaddset (&sigset
, SIGUSR1
);
1505 /* Configuration file reloading. */
1506 sigaddset (&sigset
, SIGHUP
);
1508 #ifndef HAVE_PTHREAD_CANCEL
1510 The socket, cache and rcfile threads use this signal when
1511 pthread_cancel() is unavailable. Prevent the main thread from
1512 catching this signal from another process.
1514 sigaddset (&sigset
, SIGUSR2
);
1517 /* An assertion failure. */
1518 signal (SIGABRT
, catchsig
);
1520 sigaddset (&sigset
, SIGABRT
);
1521 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
1523 #ifndef HAVE_PTHREAD_CANCEL
1524 /* Remove this signal from the watched signals in signal_loop(). */
1525 sigdelset (&sigset
, SIGUSR2
);
1528 /* Can show a backtrace of the stack in the log. */
1529 signal (SIGSEGV
, catchsig
);
1531 char *p
= get_username (getuid());
1532 log_write (_("%s started for user %s"), PACKAGE_STRING PWMD_GIT_HASH
, p
);
1536 if (config_get_boolean ("global", "enable_tcp"))
1537 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
1538 config_get_integer ("global", "tcp_port"));
1540 log_write (_("Listening on %s"), *socketpath
);
1542 log_write (_("Listening on %s"), *socketpath
);
1545 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
1548 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1549 pwmd_strerror (rc
));
1553 cancel_rcfile_thread
= 1;
1554 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
1557 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1558 pwmd_strerror (rc
));
1562 cancel_timeout_thread
= 1;
1563 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
1566 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1567 pwmd_strerror (rc
));
1571 cancel_accept_thread
= 1;
1573 signal_loop (sigset
);
1579 * We're out of the main server loop. This happens when a signal was sent
1580 * to terminate the daemon. Cancel all clients and exit.
1582 if (cancel_accept_thread
)
1584 #ifdef HAVE_PTHREAD_CANCEL
1585 n
= pthread_cancel (accept_tid
);
1587 n
= pthread_kill (accept_tid
, SIGUSR2
);
1590 pthread_join (accept_tid
, NULL
);
1593 if (cancel_timeout_thread
)
1595 #ifdef HAVE_PTHREAD_CANCEL
1596 n
= pthread_cancel (cache_timeout_tid
);
1598 n
= pthread_kill (cache_timeout_tid
, SIGUSR2
);
1601 pthread_join (cache_timeout_tid
, NULL
);
1607 shutdown (sockfd
, SHUT_RDWR
);
1609 unlink (*socketpath
);
1610 xfree (*socketpath
);
1612 MUTEX_LOCK (&cn_mutex
);
1613 n
= slist_length (cn_thread_list
);
1614 MUTEX_UNLOCK (&cn_mutex
);
1617 cancel_all_clients ();
1619 free_all_clients ();
1621 if (cancel_rcfile_thread
)
1623 #ifdef HAVE_PTHREAD_CANCEL
1624 pthread_cancel (rcfile_tid
);
1626 pthread_kill (rcfile_tid
, SIGUSR2
);
1627 pthread_cond_signal (&rcfile_cond
);
1629 pthread_join (rcfile_tid
, NULL
);
1634 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;
1638 usage (const char *pn
, int status
)
1640 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
1642 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
1643 " --homedir alternate pwmd home directory (~/.pwmd)\n"
1644 " -f, --rcfile=filename load the specified configuration file\n"
1645 " (~/.pwmd/config)\n"
1646 " --kill terminate an existing instance of pwmd\n"
1647 " -n, --no-fork run as a foreground process\n"
1648 " --disable-dump disable the LIST, XPATH and DUMP commands\n"
1649 " --ignore, --force ignore cache pushing errors during startup\n"
1650 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
1651 " -k, --passphrase-file=file for use when importing\n"
1652 " -o, --outfile=filename output file when importing\n"
1653 " --keyid=fpr[,..] public key to use when encrypting\n"
1654 " --sign-keyid=fpr fingerprint of the signing key to use\n"
1655 " -s, --symmetric use conventional encryption with optional signer\n"
1656 " --userid=string name and email address to use when importing\n"
1657 " --algo=string algorithm to use when importing (engine default)\n"
1658 " --expire=seconds key expiry time when importing (3 years)\n"
1659 " --no-passphrase don't require a passphrase when importing\n"
1660 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
1661 " --help this help text\n"
1662 " --version show version and compile time features\n"),
1668 unlink_stale_socket (const char *sock
, const char *pidfile
)
1670 log_write (_ ("removing stale socket %s"), sock
);
1676 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
1677 char **pidfile
, int create
, mode_t mode
, int terminate
)
1685 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
1686 *pidfile
= str_dup (buf
);
1687 fd
= open (buf
, O_RDONLY
);
1690 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
1694 if (!create
&& errno
!= ENOENT
)
1696 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
1701 else if (!create
&& !terminate
)
1704 log_write ("%s: %s", *pidfile
, strerror (errno
));
1710 snprintf (buf
, buflen
, "%i", getpid ());
1711 ssize_t ret
= write (fd
, buf
, strlen (buf
));
1713 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
,
1714 pwmd_strerror (gpg_error_from_syserror ()));
1722 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
,
1723 pwmd_strerror (GPG_ERR_BUFFER_TOO_SHORT
));
1727 len
= read (fd
, buf
, buflen
);
1731 unlink_stale_socket (path
, *pidfile
);
1735 if (sscanf (buf
, "%li", &pid
) != 1 || pid
== 0)
1739 unlink_stale_socket (path
, *pidfile
);
1744 if (kill (pid
, 0) == -1)
1746 unlink_stale_socket (path
, *pidfile
);
1752 if (kill (pid
, SIGTERM
) == -1)
1753 log_write ("%s: %s", path
, pwmd_strerror (errno
));
1756 log_write (_ ("an instance for socket %s is already running"), path
);
1764 parse_debug_level (const char *str
, unsigned *debug
, int *gpgme
, int *tls
)
1770 for (p
= str
; p
&& *p
; p
++)
1772 if (*p
== 'a') // assuan debug flags
1782 level
|= ASSUAN_LOG_INIT
;
1785 level
|= ASSUAN_LOG_CTX
;
1788 level
|= ASSUAN_LOG_ENGINE
;
1791 level
|= ASSUAN_LOG_DATA
;
1794 level
|= ASSUAN_LOG_SYSIO
;
1797 level
|= ASSUAN_LOG_CONTROL
;
1812 else if (*p
== 'g' || *p
== 't') // gpgme and TLS debug level
1820 if (!isdigit (*++p
))
1829 if (tl
< 0 || gl
< 0 || gl
> 9)
1832 while (isdigit (*p
))
1836 if (*(p
+1) && *(p
+1) != ',')
1856 main (int argc
, char *argv
[])
1859 struct sockaddr_un addr
;
1861 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
1862 char *socketarg
= NULL
;
1863 char *datadir
= NULL
;
1864 char *pidfile
= NULL
;
1868 char **cache_push
= NULL
;
1869 char *import
= NULL
, *keyid
= NULL
, *sign_keyid
= NULL
;
1870 char *userid
= NULL
;
1873 int no_passphrase
= 0;
1874 int estatus
= EXIT_FAILURE
;
1876 char *outfile
= NULL
;
1879 int show_version
= 0;
1882 char *keyfile
= NULL
;
1887 int gpgme_level
= -1;
1890 /* Must maintain the same order as longopts[] */
1893 OPT_VERSION
, OPT_HELP
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
1894 OPT_FORCE
, OPT_RCFILE
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
1895 OPT_KEYID
, OPT_SIGN_KEYID
, OPT_SYMMETRIC
, OPT_USERID
, OPT_ALGO
, OPT_EXPIRE
,
1896 OPT_NOPASSPHRASE
, OPT_KILL
, OPT_DEBUG
1898 const char *optstring
= "nf:C:k:I:o:s";
1899 const struct option longopts
[] = {
1900 {"version", no_argument
, 0, 0},
1901 {"help", no_argument
, 0, 0},
1902 {"homedir", required_argument
, 0, 0},
1903 {"no-fork", no_argument
, 0, 'n'},
1904 {"disable_dump", no_argument
, 0, 0},
1905 {"force", no_argument
, 0, 0},
1906 {"rcfile", required_argument
, 0, 'f'},
1907 {"passphrase-file", required_argument
, 0, 'k'},
1908 {"import", required_argument
, 0, 'I'},
1909 {"outfile", required_argument
, 0, 'o'},
1910 {"keyid", required_argument
, 0, 0},
1911 {"sign-keyid", required_argument
, 0, 0},
1912 {"symmetric", no_argument
, 0, 's'},
1913 {"userid", required_argument
, 0, 0},
1914 {"algo", required_argument
, 0, 0},
1915 {"expire", required_argument
, 0, 0},
1916 {"no-passphrase", no_argument
, 0, 0},
1917 {"kill", no_argument
, 0, 0},
1918 {"debug", required_argument
, 0, 0},
1924 expire
= time (NULL
) + DEFAULT_EXPIRE
;
1927 #ifdef HAVE_SETRLIMIT
1930 rl
.rlim_cur
= rl
.rlim_max
= 0;
1932 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
1933 err (EXIT_FAILURE
, "setrlimit()");
1936 #ifdef HAVE_PR_SET_DUMPABLE
1937 prctl (PR_SET_DUMPABLE
, 0);
1942 setlocale (LC_ALL
, "");
1943 bindtextdomain ("pwmd", LOCALEDIR
);
1944 textdomain ("pwmd");
1947 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
1965 rcfile
= str_dup (optarg
);
1971 usage (argv
[0], EXIT_FAILURE
);
1977 if (parse_debug_level (optarg
, &assuan_level
, &gpgme_level
,
1979 usage (argv
[0], EXIT_FAILURE
);
1988 usage (argv
[0], EXIT_SUCCESS
);
1991 homedir
= str_dup (optarg
);
1996 case OPT_DISABLE_DUMP
:
2003 rcfile
= str_dup (optarg
);
2005 case OPT_PASSPHRASE_FILE
:
2017 case OPT_SIGN_KEYID
:
2018 sign_keyid
= optarg
;
2028 expire
= strtoul (optarg
, &p
, 10);
2030 if (!errno
&& p
&& *p
)
2031 rc
= GPG_ERR_INV_VALUE
;
2032 else if (expire
== ULONG_MAX
)
2033 rc
= GPG_ERR_INV_VALUE
;
2035 rc
= gpg_error_from_syserror ();
2038 usage (argv
[0], EXIT_FAILURE
);
2040 case OPT_NOPASSPHRASE
:
2047 usage (argv
[0], EXIT_FAILURE
);
2055 "Copyright (C) 2006-2020\n"
2057 "Released under the terms of the GPL v2.\n\n"
2058 "Compile time features:\n%s"), PACKAGE_STRING PWMD_GIT_HASH
,
2061 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2089 exit (EXIT_SUCCESS
);
2092 if (gpgme_level
!= -1)
2094 char s
[2] = { gpgme_level
+ '0', 0 };
2096 if (getenv ("GPGME_DEBUG"))
2097 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2100 gpgme_set_global_flag ("debug", s
);
2103 if (setup_crypto ())
2104 exit (EXIT_FAILURE
);
2107 tls_level
= tls_level
== -1 ? 1 : tls_level
;
2108 gnutls_global_set_log_level (tls_level
);
2114 errx (EXIT_FAILURE
, "%s", "xml_init() failed");
2118 homedir
= str_dup(PWMD_HOMEDIR
);
2120 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2123 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2124 err (EXIT_FAILURE
, "%s", homedir
);
2127 rcfile
= str_asprintf ("%s/config", homedir
);
2129 pthread_key_create (&last_error_key
, free_key
);
2130 #ifndef HAVE_PTHREAD_CANCEL
2131 pthread_key_create (&signal_thread_key
, free_key
);
2134 pthread_mutexattr_t attr
;
2135 pthread_mutexattr_init (&attr
);
2136 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2137 pthread_mutex_init (&rcfile_mutex
, &attr
);
2138 global_config
= config_parse (rcfile
, 0);
2141 pthread_mutexattr_destroy (&attr
);
2142 pthread_mutex_destroy (&rcfile_mutex
);
2143 exit (EXIT_FAILURE
);
2146 p
= config_get_string ("global", "gpg_homedir");
2148 datadir
= str_asprintf ("%s/.gnupg", homedir
);
2150 datadir
= expand_homedir (p
);
2153 if (mkdir (datadir
, 0700) == -1 && errno
!= EEXIST
)
2154 err (EXIT_FAILURE
, "%s", datadir
);
2156 rc
= gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP
, NULL
, datadir
);
2158 errx (EXIT_FAILURE
, "%s: %s", datadir
, pwmd_strerror (rc
));
2161 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2162 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2163 err (EXIT_FAILURE
, "%s", buf
);
2165 datadir
= str_dup (buf
);
2166 pthread_cond_init (&rcfile_cond
, NULL
);
2167 pthread_mutex_init (&cn_mutex
, &attr
);
2168 pthread_mutexattr_destroy (&attr
);
2172 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2173 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2176 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2178 log_write ("setpriority(): %s",
2179 pwmd_strerror (gpg_error_from_errno (errno
)));
2183 #ifdef HAVE_MLOCKALL
2184 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2186 log_write ("mlockall(): %s",
2187 pwmd_strerror (gpg_error_from_errno (errno
)));
2195 log_write ("pwmd: ERR %i: %s", rc
, pwmd_strerror (rc
));
2196 exit (EXIT_FAILURE
);
2201 char **keyids
= NULL
;
2203 if (!outfile
|| !*outfile
|| argc
!= optind
)
2204 usage (argv
[0], EXIT_FAILURE
);
2207 keyids
= str_split (keyid
, ",", 0);
2208 else if (!userid
&& !sym
)
2209 usage (argv
[0], EXIT_FAILURE
);
2211 rc
= xml_import (import
, outfile
, keyids
, sign_keyid
, keyfile
, userid
,
2212 algo
, expire
, no_passphrase
, sym
);
2216 if (gpg_err_source (rc
) == GPG_ERR_SOURCE_UNKNOWN
)
2217 rc
= gpg_error (rc
);
2219 log_write ("%s: %u: %s", import
, rc
, pwmd_strerror (rc
));
2222 config_free (global_config
);
2224 exit (rc
? EXIT_FAILURE
: EXIT_SUCCESS
);
2227 p
= config_get_string ("global", "socket_path");
2229 p
= str_asprintf ("%s/socket", homedir
);
2231 socketarg
= expand_homedir (p
);
2235 disable_list_and_dump
= config_get_boolean ("global",
2236 "disable_list_and_dump");
2238 disable_list_and_dump
= secure
;
2240 cache_push
= config_get_list ("global", "cache_push");
2242 while (optind
< argc
)
2244 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2245 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2248 if (!strchr (socketarg
, '/'))
2250 socketdir
= getcwd (buf
, sizeof (buf
));
2251 socketname
= str_dup (socketarg
);
2252 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2256 socketname
= str_dup (strrchr (socketarg
, '/')+1);
2257 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2258 socketdir
= str_dup (socketarg
);
2259 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2262 if (chdir (datadir
))
2264 log_write ("%s: %s", datadir
,
2265 pwmd_strerror (gpg_error_from_errno (errno
)));
2266 unlink (socketpath
);
2270 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
2272 if (!terminate
&& x
)
2276 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2281 * bind() doesn't like the full pathname of the socket or any non alphanum
2282 * characters so change to the directory where the socket is wanted then
2283 * create it then change to datadir.
2285 if (chdir (socketdir
))
2287 log_write ("%s: %s", socketdir
,
2288 pwmd_strerror (gpg_error_from_errno (errno
)));
2294 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2296 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2300 addr
.sun_family
= AF_UNIX
;
2301 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2303 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2306 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2308 if (errno
== EADDRINUSE
)
2311 log_write (_("Either there is another pwmd running or '%s' is a \n"
2312 "stale socket. Please remove it manually."), socketpath
);
2319 char *t
= config_get_string ("global", "socket_perms");
2324 mode
= strtol (t
, NULL
, 8);
2328 if (chmod (socketname
, mode
) == -1)
2330 log_write ("%s: %s", socketname
,
2331 pwmd_strerror (gpg_error_from_errno (errno
)));
2341 if (chdir (datadir
))
2343 log_write ("%s: %s", datadir
,
2344 pwmd_strerror (gpg_error_from_errno (errno
)));
2351 if (config_get_boolean ("global", "enable_tcp"))
2353 if (!tls_start_stop (0))
2362 * Set the cache entry for a file. Prompts for the password.
2366 for (opt
= 0; cache_push
[opt
]; opt
++)
2368 struct crypto_s
*crypto
= NULL
;
2369 char *pw_file
= config_get_string (cache_push
[opt
],
2371 rc
= crypto_init (&crypto
, NULL
, cache_push
[opt
], pw_file
!= NULL
,
2376 crypto
->flags
|= pw_file
? CRYPTO_FLAG_KEYFILE
: 0;
2377 crypto
->keyfile
= pw_file
;
2384 estatus
= EXIT_FAILURE
;
2388 rc
= do_cache_push (crypto
);
2391 log_write ("ERR %u: %s", rc
, pwmd_strerror(rc
));
2392 strv_free (cache_push
);
2393 log_write (_ ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2394 cache_clear (NULL
, NULL
, 1, 0);
2395 estatus
= EXIT_FAILURE
;
2396 crypto_free (crypto
);
2397 (void)cache_kill_scd ();
2401 log_write ("%s: %s", crypto
->filename
, pwmd_strerror(rc
));
2403 log_write (_("Successfully added '%s' to the cache."),
2406 crypto_free (crypto
);
2409 (void)cache_kill_scd ();
2410 strv_free (cache_push
);
2411 log_write (!nofork
? _("Done. Daemonizing...") :
2412 _("Done. Waiting for connections..."));
2415 backlog
= config_get_integer ("global", "backlog");
2416 if (listen (sockfd
, backlog
) == -1)
2418 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2422 /* A client should set these with the OPTION command. */
2423 unsetenv ("DISPLAY");
2424 unsetenv ("GPG_TTY");
2432 log_write ("fork(): %s",
2433 pwmd_strerror (gpg_error_from_errno (errno
)));
2442 _exit (EXIT_SUCCESS
);
2446 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
2450 pthread_key_create (&thread_name_key
, free_key
);
2451 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
2452 estatus
= server_loop (sockfd
, &socketpath
);
2455 if (socketpath
&& do_unlink
)
2457 unlink (socketpath
);
2463 gnutls_global_deinit ();
2464 tls_deinit_params ();
2466 pthread_cond_destroy (&rcfile_cond
);
2467 pthread_mutex_destroy (&rcfile_mutex
);
2468 pthread_key_delete (last_error_key
);
2469 #ifndef HAVE_PTHREAD_CANCEL
2470 pthread_key_delete (signal_thread_key
);
2474 config_free (global_config
);
2476 free_invoking_users (invoking_users
);
2478 xfree (home_directory
);
2486 if (estatus
== EXIT_SUCCESS
&& !terminate
)
2487 log_write (_("pwmd exiting normally"));
2489 pthread_key_delete (thread_name_key
);
2499 gpg_error_t
lock_flock (assuan_context_t ctx
, const char *filename
,
2505 rc
= open_check_file (filename
, fd
, NULL
, 1);
2509 TRY_FLOCK (ctx
, *fd
, type
, rc
);
2520 void unlock_flock (int *fd
)