1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
3 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
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/>.
41 #include <glib/gprintf.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
50 #include <sys/resource.h>
59 #ifdef HAVE_PR_SET_NAME
60 #include <sys/prctl.h>
63 #include "pwmd-error.h"
78 static gboolean exiting
;
79 static gboolean cmdline
;
81 static gboolean nofork
;
82 static pthread_cond_t quit_cond
;
83 static pthread_mutex_t quit_mutex
;
84 static gboolean no_passphrase_file
= FALSE
;
88 static pthread_t tls_tid
;
89 static pthread_t tls6_tid
;
91 static gboolean
start_stop_tls(gboolean term
);
94 static gboolean
do_cache_push(const gchar
*filename
, struct crypto_s
*crypto
);
95 static gboolean
signal_loop(sigset_t sigset
);
97 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
99 static void cache_push_from_rcfile()
101 struct crypto_s
*crypto
;
102 gpg_error_t rc
= init_client_crypto(&crypto
);
105 log_write("%s: %s", __FUNCTION__
, pwmd_strerror(rc
));
109 rc
= set_agent_option(crypto
->agent
, "pinentry-mode", "error");
111 log_write("%s: %s", __FUNCTION__
, pwmd_strerror(rc
));
115 if (g_key_file_has_key(keyfileh
, "global", "cache_push", NULL
)) {
116 gchar
**cache_push
= g_key_file_get_string_list(keyfileh
, "global",
117 "cache_push", NULL
, NULL
);
120 for (p
= cache_push
; *p
; p
++) {
121 (void)do_cache_push(*p
, crypto
);
122 cleanup_crypto_stage1(crypto
);
125 g_strfreev(cache_push
);
128 (void)kill_scd(crypto
->agent
);
129 cleanup_crypto(&crypto
);
132 static void *reload_rcfile_thread(void *arg
)
134 #ifdef HAVE_PR_SET_NAME
135 prctl(PR_SET_NAME
, "reload rcfile");
137 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
138 MUTEX_LOCK(&rcfile_mutex
);
141 gboolean b
= disable_list_and_dump
;
145 pthread_cond_wait(&rcfile_cond
, &rcfile_mutex
);
146 users
= g_key_file_get_string_list(keyfileh
, "global", "allowed", NULL
, NULL
);
147 log_write(_("reloading configuration file '%s'"), rcfile
);
148 k
= parse_rcfile(FALSE
, cmdline
);
150 g_key_file_free(keyfileh
);
152 cache_push_from_rcfile();
156 disable_list_and_dump
= !disable_list_and_dump
? b
: TRUE
;
157 g_key_file_set_string_list(keyfileh
, "global", "allowed",
158 (const gchar
**)users
, g_strv_length(users
));
161 /* Kill existing listening threads since the configured listening
162 * protocols may have changed. */
163 start_stop_tls(TRUE
);
164 start_stop_tls(FALSE
);
171 gpg_error_t
send_error(assuan_context_t ctx
, gpg_error_t e
)
173 struct client_s
*client
= assuan_get_pointer(ctx
);
175 if (gpg_err_source(e
) == GPG_ERR_SOURCE_UNKNOWN
)
182 return assuan_process_done(ctx
, 0);
185 log_write("%s", pwmd_strerror(e
));
189 if (gpg_err_code(e
) == GPG_ERR_BAD_DATA
) {
190 xmlErrorPtr xe
= client
->xml_error
;
193 xe
= xmlGetLastError();
195 log_write("%s", xe
->message
);
196 if (client
->last_error
)
197 g_free(client
->last_error
);
199 client
->last_error
= g_strdup(xe
->message
);
202 e
= assuan_process_done(ctx
, assuan_set_error(ctx
, e
,
203 xe
? xe
->message
: NULL
));
205 if (xe
== client
->xml_error
)
210 client
->xml_error
= NULL
;
214 return assuan_process_done(ctx
, assuan_set_error(ctx
, e
, pwmd_strerror(e
)));
217 int assuan_log_cb(assuan_context_t ctx
, void *data
, unsigned cat
,
220 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
222 gboolean match
= FALSE
;
224 pthread_mutex_lock(&m
);
225 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock
, &m
);
226 t
= g_strv_length(debug_level
);
228 for (i
= 0; i
< t
; i
++) {
229 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"init")
230 && cat
== ASSUAN_LOG_INIT
) {
235 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"ctx")
236 && cat
== ASSUAN_LOG_CTX
) {
241 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"engine")
242 && cat
== ASSUAN_LOG_ENGINE
) {
247 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"data")
248 && cat
== ASSUAN_LOG_DATA
) {
253 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"sysio")
254 && cat
== ASSUAN_LOG_SYSIO
) {
259 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"control")
260 && cat
== ASSUAN_LOG_CONTROL
) {
270 if ((fd
= open(logfile
, O_WRONLY
|O_CREAT
|O_APPEND
, 0600)) == -1)
273 pthread_cleanup_push(cleanup_fd_cb
, &fd
);
274 write(fd
, msg
, strlen(msg
));
275 pthread_cleanup_pop(1);
280 fprintf(stderr
, "%s%s", data
? (gchar
*)data
: "", msg
);
285 pthread_cleanup_pop(1);
289 void log_write(const gchar
*fmt
, ...)
299 pthread_t tid
= pthread_self();
300 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
302 if ((!logfile
&& !isatty(STDERR_FILENO
) && !log_syslog
) || !fmt
)
305 pthread_mutex_lock(&m
);
306 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock
, &m
);
307 pthread_cleanup_push(cleanup_fd_cb
, &fd
);
309 if (!cmdline
&& logfile
) {
310 if ((fd
= open(logfile
, O_WRONLY
|O_CREAT
|O_APPEND
, 0600)) == -1)
316 if (g_vasprintf(&args
, fmt
, ap
) != -1) {
318 pthread_cleanup_push(g_free
, args
);
319 fprintf(stderr
, "%s\n", args
);
321 pthread_cleanup_pop(1);
324 pthread_cleanup_push(g_free
, args
);
325 name
= pthread_getspecific(thread_name_key
);
326 name
= print_fmt(buf
, sizeof(buf
), "%s(%p): ",
327 name
? name
: _("unknown"), (pthread_t
*)tid
);
329 if (!cmdline
&& log_syslog
&& !nofork
)
330 syslog(LOG_INFO
, "%s%s", name
, args
);
333 tm
= localtime(&now
);
334 strftime(tbuf
, sizeof(tbuf
), "%b %d %Y %H:%M:%S ", tm
);
335 tbuf
[sizeof(tbuf
) - 1] = 0;
337 if (args
[strlen(args
)-1] == '\n')
338 args
[strlen(args
)-1] = 0;
340 line
= g_strdup_printf("%s %i %s%s\n", tbuf
, getpid(), name
,
342 pthread_cleanup_pop(1);
344 pthread_cleanup_push(g_free
, line
);
345 if (logfile
&& fd
!= -1) {
346 write(fd
, line
, strlen(line
));
351 fprintf(stdout
, "%s", line
);
355 pthread_cleanup_pop(1);
361 pthread_cleanup_pop(1);
362 pthread_cleanup_pop(0);
363 pthread_mutex_unlock(&m
);
367 static gint
secure_mem_check(const void *arg
)
373 static gpg_error_t
setup_crypto()
375 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
377 if (!gcry_check_version(GCRYPT_VERSION
)) {
378 fprintf(stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
379 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
380 gcry_check_version(NULL
));
381 return GPG_ERR_UNKNOWN_VERSION
;
384 gcry_set_allocation_handler(g_malloc
, g_malloc
, NULL
, g_realloc
, g_free
);
388 static gpg_error_t
validate_peer(struct client_s
*cl
)
391 gboolean allowed
= FALSE
;
392 assuan_peercred_t peercred
;
400 rc
= assuan_get_peercred(cl
->ctx
, &peercred
);
404 users
= g_key_file_get_string_list(keyfileh
, "global", "allowed", NULL
, NULL
);
407 for (gchar
**p
= users
; *p
; p
++) {
408 struct passwd pw
, *result
;
409 struct group gr
, *gresult
;
413 size_t len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
422 return GPG_ERR_ENOMEM
;
425 if (!getgrnam_r(*(p
)+1, &gr
, buf
, len
, &gresult
) && gresult
) {
426 if (gresult
->gr_gid
== peercred
->gid
) {
432 len
= sysconf(_SC_GETPW_R_SIZE_MAX
);
437 gchar
*tbuf
= g_malloc(len
);
439 for (gchar
**t
= gresult
->gr_mem
; *t
; t
++) {
440 if (!getpwnam_r(*t
, &pw
, tbuf
, len
, &result
) && result
) {
441 if (result
->pw_uid
== peercred
->uid
) {
456 size_t len
= sysconf(_SC_GETPW_R_SIZE_MAX
);
465 return GPG_ERR_ENOMEM
;
468 if (!getpwnam_r(*p
, &pw
, buf
, len
, &result
) && result
) {
469 if (result
->pw_uid
== peercred
->uid
) {
483 log_write("peer %s: uid=%i, gid=%i, pid=%i",
484 allowed
? _("accepted") : _("rejected"), peercred
->uid
,
485 peercred
->gid
, peercred
->pid
);
486 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
489 static void xml_error_cb(void *data
, xmlErrorPtr e
)
491 struct client_s
*client
= data
;
494 * Keep the first reported error as the one to show in the error
495 * description. Reset in send_error().
497 if (client
->xml_error
)
500 xmlCopyError(e
, client
->xml_error
);
503 static pid_t
hook_waitpid(assuan_context_t ctx
, pid_t pid
, int action
,
504 int *status
, int options
)
506 return waitpid(pid
, status
, options
);
509 static ssize_t
hook_read(assuan_context_t ctx
, assuan_fd_t fd
, void *data
,
513 struct client_s
*client
= assuan_get_pointer(ctx
);
515 if (client
->thd
->remote
)
516 return tls_read_hook(ctx
, (gint
)fd
, data
, len
);
519 return read((gint
)fd
, data
, len
);
522 static ssize_t
hook_write(assuan_context_t ctx
, assuan_fd_t fd
,
523 const void *data
, size_t len
)
526 struct client_s
*client
= assuan_get_pointer(ctx
);
528 if (client
->thd
->remote
)
529 return tls_write_hook(ctx
, (gint
)fd
, data
, len
);
532 return write((gint
)fd
, data
, len
);
535 static gboolean
new_connection(struct client_s
*cl
)
538 static struct assuan_malloc_hooks mhooks
= { g_malloc
, g_realloc
, g_free
};
539 static struct assuan_system_hooks shooks
= {
540 ASSUAN_SYSTEM_HOOKS_VERSION
,
548 NULL
, //sendmsg both are used for FD passing
557 if (cl
->thd
->remote
) {
558 gchar
*prio
= get_key_file_string("global", "tls_cipher_suite");
560 cl
->thd
->tls
= tls_init(cl
->thd
->fd
, prio
);
567 rc
= assuan_new_ext(&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
568 debug_level
? assuan_log_cb
: NULL
, NULL
);
572 assuan_ctx_set_system_hooks(cl
->ctx
, &shooks
);
573 rc
= assuan_init_socket_server(cl
->ctx
, cl
->thd
->fd
, 2);
577 assuan_set_pointer(cl
->ctx
, cl
);
578 assuan_set_hello_line(cl
->ctx
, PACKAGE_STRING
);
579 rc
= register_commands(cl
->ctx
);
583 rc
= assuan_accept(cl
->ctx
);
587 rc
= validate_peer(cl
);
588 /* May not be implemented on all platforms. */
589 if (rc
&& gpg_err_code(rc
) != GPG_ERR_ASS_GENERAL
)
592 rc
= init_client_crypto(&cl
->crypto
);
596 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
597 cl
->crypto
->client_ctx
= cl
->ctx
;
598 xmlSetStructuredErrorFunc(cl
, xml_error_cb
);
602 log_write("%s", pwmd_strerror(rc
));
607 * This is called after a client_thread() terminates. Set with
608 * pthread_cleanup_push().
610 static void cleanup_cb(void *arg
)
612 struct client_thread_s
*cn
= arg
;
613 struct client_s
*cl
= cn
->cl
;
615 MUTEX_LOCK(&cn_mutex
);
616 cn_thread_list
= g_slist_remove(cn_thread_list
, cn
);
617 MUTEX_UNLOCK(&cn_mutex
);
624 gnutls_deinit(cn
->tls
->ses
);
631 assuan_release(cl
->ctx
);
632 else if (cl
->thd
&& cl
->thd
->fd
!= -1)
636 cleanup_crypto(&cl
->crypto
);
645 while (cn
->msg_queue
) {
646 struct status_msg_s
*msg
= cn
->msg_queue
;
648 cn
->msg_queue
= msg
->next
;
653 if (cn
->status_msg_pipe
[0] != -1)
654 close(cn
->status_msg_pipe
[0]);
656 if (cn
->status_msg_pipe
[1] != -1)
657 close(cn
->status_msg_pipe
[1]);
659 pthread_mutex_destroy(&cn
->status_mutex
);
660 log_write(_("exiting, fd=%i"), cn
->fd
);
662 send_status_all(STATUS_CLIENTS
, NULL
);
663 pthread_cond_signal(&quit_cond
);
666 static gpg_error_t
send_msg_queue(struct client_thread_s
*thd
)
668 MUTEX_LOCK(&thd
->status_mutex
);
672 read(thd
->status_msg_pipe
[0], &c
, 1);
674 while (thd
->msg_queue
) {
675 struct status_msg_s
*msg
= thd
->msg_queue
;
677 thd
->msg_queue
= thd
->msg_queue
->next
;
678 MUTEX_UNLOCK(&thd
->status_mutex
);
679 rc
= send_status(thd
->cl
->ctx
, msg
->s
, msg
->line
);
680 MUTEX_LOCK(&thd
->status_mutex
);
688 MUTEX_UNLOCK(&thd
->status_mutex
);
692 static void *client_thread(void *data
)
694 struct client_thread_s
*thd
= data
;
695 struct client_s
*cl
= g_malloc0(sizeof(struct client_s
));
697 #ifdef HAVE_PR_SET_NAME
698 prctl(PR_SET_NAME
, "client");
700 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
703 log_write("%s(%i): %s", __FILE__
, __LINE__
,
704 pwmd_strerror(GPG_ERR_ENOMEM
));
708 MUTEX_LOCK(&cn_mutex
);
709 pthread_cleanup_push(cleanup_cb
, thd
);
712 MUTEX_UNLOCK(&cn_mutex
);
714 if (new_connection(cl
)) {
715 gboolean finished
= FALSE
;
718 send_status_all(STATUS_CLIENTS
, NULL
);
719 rc
= send_status(cl
->ctx
, STATUS_CACHE
, NULL
);
721 log_write("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror(rc
));
731 FD_SET(thd
->fd
, &rfds
);
732 FD_SET(thd
->status_msg_pipe
[0], &rfds
);
733 n
= thd
->fd
> thd
->status_msg_pipe
[0] ? thd
->fd
: thd
->status_msg_pipe
[0];
735 n
= select(n
+1, &rfds
, NULL
, NULL
, NULL
);
737 log_write("%s", strerror(errno
));
741 if (FD_ISSET(thd
->status_msg_pipe
[0], &rfds
)) {
742 rc
= send_msg_queue(thd
);
743 if (rc
&& gpg_err_code(rc
) != GPG_ERR_EPIPE
) {
744 log_write("%s(%i): %s", __FUNCTION__
, __LINE__
,
750 if (!FD_ISSET(thd
->fd
, &rfds
))
753 rc
= assuan_process_next(cl
->ctx
, &eof
);
755 if (gpg_err_code(rc
) == GPG_ERR_EOF
|| eof
)
758 log_write("assuan_process_next(): %s", pwmd_strerror(rc
));
759 rc
= send_error(cl
->ctx
, rc
);
762 log_write("assuan_process_done(): %s", pwmd_strerror(rc
));
767 /* Since the msg queue pipe fd's are non-blocking, check for
768 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
769 * client has already disconnected and will be converted to
770 * GPG_ERR_EOF during assuan_process_next().
772 rc
= send_msg_queue(thd
);
773 if (rc
&& gpg_err_code(rc
) != GPG_ERR_EPIPE
) {
774 log_write("%s(%i): %s", __FUNCTION__
, __LINE__
,
781 pthread_cleanup_pop(1);
785 static gboolean
xml_import(const gchar
*filename
, const gchar
*outfile
,
786 const gchar
*keygrip
, const char *sign_keygrip
, const gchar
*keyfile
,
787 gboolean no_passphrase
, const gchar
*cipher
, const gchar
*params
,
788 gulong s2k_count
, guint64 iterations
)
797 struct crypto_s
*crypto
;
798 gint algo
= cipher
? cipher_string_to_gcrypt((gchar
*)cipher
) :
802 log_write("%s", pwmd_strerror(GPG_ERR_CIPHER_ALGO
));
806 if (stat(filename
, &st
) == -1) {
807 log_write("%s: %s", filename
, pwmd_strerror(gpg_error_from_syserror()));
811 rc
= init_client_crypto(&crypto
);
815 memcpy(&crypto
->save
.hdr
, &crypto
->hdr
, sizeof(file_header_t
));
816 crypto
->save
.hdr
.flags
= set_cipher_flag(crypto
->save
.hdr
.flags
, algo
);
817 log_write(_("Importing XML from '%s'. Output will be written to '%s' ..."),
820 if ((fd
= open(filename
, O_RDONLY
)) == -1) {
821 log_write("%s: %s", filename
, pwmd_strerror(gpg_error_from_syserror()));
825 if ((xmlbuf
= xmalloc(st
.st_size
+1)) == NULL
) {
827 log_write("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror(GPG_ERR_ENOMEM
));
831 if (read(fd
, xmlbuf
, st
.st_size
) == -1) {
832 rc
= gpg_error_from_syserror();
834 log_write("%s: %s", filename
, pwmd_strerror(rc
));
839 xmlbuf
[st
.st_size
] = 0;
841 * Make sure the document validates.
843 if ((doc
= xmlReadDoc(xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
) {
844 log_write("xmlReadDoc() failed");
850 xmlNodePtr n
= xmlDocGetRootElement(doc
);
851 if (!xmlStrEqual(n
->name
, (xmlChar
*)"pwmd")) {
852 log_write(_("Could not find root \"pwmd\" element."));
853 rc
= GPG_ERR_BAD_DATA
;
857 rc
= validate_import(n
? n
->children
: n
);
860 log_write("%s", pwmd_strerror(rc
));
865 xmlDocDumpMemory(doc
, &xml
, &len
);
867 crypto
->save
.s2k_count
= (gulong
)s2k_count
;
868 crypto
->save
.hdr
.iterations
= iterations
;
869 rc
= set_pinentry_options(crypto
->agent
);
871 rc
= export_common(crypto
, keygrip
, sign_keygrip
, no_passphrase
, xml
,
872 len
, outfile
, params
, keyfile
);
876 send_error(NULL
, rc
);
880 cleanup_crypto(&crypto
);
884 cleanup_crypto(&crypto
);
888 static gboolean
do_cache_push(const gchar
*filename
, struct crypto_s
*crypto
)
895 struct cache_data_s
*cdata
;
899 log_write(_("Trying to add datafile '%s' to the file cache ..."),
902 if (valid_filename(filename
) == FALSE
) {
903 log_write(_("%s: Invalid characters in filename"), filename
);
907 rc
= read_data_file(filename
, crypto
);
909 log_write("%s", pwmd_strerror(rc
));
913 if ((key
= get_key_file_string(filename
, "passphrase"))) {
914 log_write(_("Trying the passphrase specified in config ..."));
915 keylen
= strlen(key
);
917 else if ((key
= get_key_file_string(filename
, "passphrase_file"))) {
918 gint fd
= open((gchar
*)key
, O_RDONLY
);
921 log_write(_("Trying the passphrase using file '%s' ..."), key
);
923 log_write("%s: %s", key
, pwmd_strerror(gpg_error_from_syserror()));
928 stat((gchar
*)key
, &st
);
930 key
= g_malloc(st
.st_size
);
931 if (read(fd
, key
, st
.st_size
) != st
.st_size
) {
932 log_write("short read() count");
942 rc
= set_agent_passphrase(crypto
, key
, keylen
);
945 log_write("%s", pwmd_strerror(rc
));
950 crypto
->filename
= g_strdup(filename
);
951 rc
= decrypt_data(NULL
, crypto
);
953 log_write("%s", pwmd_strerror(rc
));
957 doc
= parse_doc((gchar
*)crypto
->plaintext
, crypto
->plaintext_len
);
959 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM
));
963 gcry_md_hash_buffer(GCRY_MD_MD5
, md5file
, filename
, strlen(filename
));
964 cdata
= g_malloc0(sizeof(struct cache_data_s
));
967 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM
));
971 rc
= get_checksum(filename
, &crc
, &len
);
973 log_write("%s", pwmd_strerror(rc
));
975 free_cache_data_once(cdata
);
980 rc
= encrypt_xml(NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
981 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
982 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
984 log_write("%s", pwmd_strerror(rc
));
986 free_cache_data_once(cdata
);
990 gcry_sexp_build((gcry_sexp_t
*)&cdata
->pubkey
, NULL
, "%S", crypto
->pkey_sexp
);
991 gcry_sexp_build((gcry_sexp_t
*)&cdata
->sigkey
, NULL
, "%S", crypto
->sigpkey_sexp
);
992 gint timeout
= get_key_file_integer(filename
, "cache_timeout");
993 cache_add_file(md5file
, crypto
->grip
, cdata
, timeout
);
994 log_write(_("Successfully added '%s' to the cache."), filename
);
998 static gpg_error_t
init_client_thread(gint fd
, const gchar
*addr
)
1001 struct client_thread_s
*new = g_malloc0(sizeof(struct client_thread_s
));
1005 return GPG_ERR_ENOMEM
;
1008 MUTEX_LOCK(&cn_mutex
);
1009 pthread_cleanup_push(cleanup_mutex_cb
, &cn_mutex
);
1011 if (pipe(new->status_msg_pipe
) == -1)
1012 rc
= gpg_error_from_syserror();
1015 fcntl(new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1016 fcntl(new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1017 pthread_mutex_init(&new->status_mutex
, NULL
);
1022 new->remote
= addr
? TRUE
: FALSE
;
1025 rc
= create_thread(client_thread
, new, &new->tid
, TRUE
);
1027 close(new->status_msg_pipe
[0]);
1028 close(new->status_msg_pipe
[1]);
1029 pthread_mutex_destroy(&new->status_mutex
);
1034 cn_thread_list
= g_slist_append(cn_thread_list
, new);
1036 log_write(_("new connection: tid=%p, fd=%i, addr=%s"),
1037 (pthread_t
*)new->tid
, fd
, addr
);
1039 log_write(_("new connection: tid=%p, fd=%i"),
1040 (pthread_t
*)new->tid
, fd
);
1043 pthread_cleanup_pop(1);
1048 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1055 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1056 static void *get_in_addr(struct sockaddr
*sa
)
1058 if (sa
->sa_family
== AF_INET
)
1059 return &(((struct sockaddr_in
*)sa
)->sin_addr
);
1061 return &(((struct sockaddr_in6
*)sa
)->sin6_addr
);
1064 static void *tcp_accept_thread(void *arg
)
1066 gint sockfd
= *(gint
*)arg
;
1068 #ifdef HAVE_PR_SET_NAME
1069 prctl(PR_SET_NAME
, "tcp_accept");
1071 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1074 struct sockaddr_storage raddr
;
1075 socklen_t slen
= sizeof(raddr
);
1079 gchar s
[INET6_ADDRSTRLEN
];
1081 fd
= accept(sockfd
, (struct sockaddr
*)&raddr
, &slen
);
1083 if (errno
!= EAGAIN
) {
1084 if (!quit
) // probably EBADF
1085 log_write("accept(): %s", strerror(errno
));
1096 inet_ntop(raddr
.ss_family
, get_in_addr((struct sockaddr
*)&raddr
),
1098 (void)init_client_thread(fd
, s
);
1099 t
= get_key_file_string("global", "tcp_wait");
1100 n
= strtol(t
, NULL
, 10);
1106 /* Just in case accept() failed for some reason other than EBADF */
1111 static gboolean
start_stop_tls_with_protocol(gboolean ipv6
, gboolean term
)
1113 struct addrinfo hints
, *servinfo
, *p
;
1114 gint port
= get_key_file_integer("global", "tcp_port");
1118 gint
*fd
= ipv6
? &tls6_fd
: &tls_fd
;
1120 if (term
|| get_key_file_boolean("global", "enable_tcp") == FALSE
) {
1121 if (tls6_fd
!= -1) {
1122 pthread_cancel(tls6_tid
);
1123 pthread_join(tls6_tid
, NULL
);
1124 shutdown(tls6_fd
, SHUT_RDWR
);
1130 pthread_cancel(tls_tid
);
1131 pthread_join(tls_tid
, NULL
);
1132 shutdown(tls_fd
, SHUT_RDWR
);
1137 /* A client may still be connected. */
1138 if (!quit
&& x509_cred
!= NULL
)
1139 tls_deinit_params();
1144 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1147 memset(&hints
, 0, sizeof(hints
));
1148 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1149 hints
.ai_socktype
= SOCK_STREAM
;
1150 hints
.ai_flags
= AI_PASSIVE
;
1152 if ((n
= getaddrinfo(NULL
, print_fmt(buf
, sizeof(buf
), "%i", port
),
1153 &hints
, &servinfo
)) == -1) {
1154 log_write("getaddrinfo(): %s", gai_strerror(n
));
1158 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
) {
1159 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1160 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1163 if ((*fd
= socket(p
->ai_family
, p
->ai_socktype
,
1164 p
->ai_protocol
)) == -1) {
1165 log_write("socket(): %s", strerror(errno
));
1169 if (setsockopt(*fd
, SOL_SOCKET
, SO_REUSEADDR
, &n
,
1170 sizeof(int)) == -1) {
1171 log_write("setsockopt(): %s", strerror(errno
));
1172 freeaddrinfo(servinfo
);
1176 if (bind(*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1) {
1178 log_write("bind(): %s", strerror(errno
));
1186 freeaddrinfo(servinfo
);
1189 log_write("%s", _("could not bind"));
1193 #ifdef HAVE_DECL_SO_BINDTODEVICE
1194 if (g_key_file_has_key(keyfileh
, "global", "tcp_interface", NULL
)) {
1195 gchar
*tmp
= get_key_file_string("global", "tcp_interface");
1197 if (setsockopt(*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
, 1)
1199 log_write("setsockopt(): %s", strerror(errno
));
1208 if (x509_cred
== NULL
) {
1209 rc
= tls_init_params();
1214 if (listen(*fd
, 0) == -1) {
1215 log_write("listen(): %s", strerror(errno
));
1220 rc
= create_thread(tcp_accept_thread
, fd
, &tls6_tid
, FALSE
);
1222 rc
= create_thread(tcp_accept_thread
, fd
, &tls_tid
, FALSE
);
1225 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1233 start_stop_tls_with_protocol(FALSE
, TRUE
);
1245 static gboolean
start_stop_tls(gboolean term
)
1247 gchar
*s
= get_key_file_string("global", "tcp_bind");
1253 if (!g_strcmp0(s
, "any")) {
1254 b
= start_stop_tls_with_protocol(FALSE
, term
);
1256 b
= start_stop_tls_with_protocol(TRUE
, term
);
1258 else if (!g_strcmp0(s
, "ipv4"))
1259 b
= start_stop_tls_with_protocol(FALSE
, term
);
1260 else if (!g_strcmp0(s
, "ipv6"))
1261 b
= start_stop_tls_with_protocol(TRUE
, term
);
1270 static void *accept_thread(void *arg
)
1272 gint sockfd
= *(gint
*)arg
;
1274 #ifdef HAVE_PR_SET_NAME
1275 prctl(PR_SET_NAME
, "accept");
1277 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1280 socklen_t slen
= sizeof(struct sockaddr_un
);
1281 struct sockaddr_un raddr
;
1284 fd
= accept(sockfd
, (struct sockaddr
*)&raddr
, &slen
);
1286 if (errno
!= EAGAIN
) {
1287 if (!quit
) // probably EBADF
1288 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1295 (void)init_client_thread(fd
, NULL
);
1298 /* Just in case accept() failed for some reason other than EBADF */
1303 static void *cache_timer_thread(void *arg
)
1305 #ifdef HAVE_PR_SET_NAME
1306 prctl(PR_SET_NAME
, "cache timer");
1308 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1312 cache_adjust_timeout();
1318 static void catch_sigabrt(int sig
)
1326 static gboolean
signal_loop(sigset_t sigset
)
1328 gboolean done
= FALSE
;
1329 gboolean sigint
= FALSE
;
1332 gint sig
= sigwaitinfo(&sigset
, NULL
);
1335 if (errno
!= EAGAIN
)
1336 log_write("sigwaitinfo(): %s", strerror(errno
));
1341 log_write(_("caught signal %i (%s)"), sig
, strsignal(sig
));
1345 pthread_cond_signal(&rcfile_cond
);
1348 // not really handled here.
1349 catch_sigabrt(SIGABRT
);
1352 log_write(_("clearing file cache"));
1354 send_status_all(STATUS_CACHE
, NULL
);
1369 static void catchsig(int sig
)
1371 log_write("Caught SIGSEGV. Exiting.");
1372 #ifdef HAVE_BACKTRACE
1373 BACKTRACE(__FUNCTION__
);
1378 static void *waiting_for_exit(void *arg
)
1380 #ifdef HAVE_PR_SET_NAME
1381 prctl(PR_SET_NAME
, "exiting");
1383 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1384 log_write(_("waiting for all clients to disconnect"));
1385 MUTEX_LOCK(&quit_mutex
);
1386 pthread_cleanup_push(cleanup_mutex_cb
, &quit_mutex
);
1389 MUTEX_LOCK(&cn_mutex
);
1390 gint n
= g_slist_length(cn_thread_list
);
1391 MUTEX_UNLOCK(&cn_mutex
);
1395 log_write(_("%i clients remain"), n
);
1396 pthread_cond_wait(&quit_cond
, &quit_mutex
);
1399 pthread_cleanup_pop(1);
1400 kill(getpid(), SIGUSR2
);
1404 static gboolean
server_loop(gint sockfd
, gchar
**socketpath
)
1406 pthread_t accept_tid
= 0;
1407 pthread_t cache_timeout_tid
= 0;
1410 gboolean segv
= FALSE
;
1414 sigemptyset(&sigset
);
1417 sigaddset(&sigset
, SIGTERM
);
1418 sigaddset(&sigset
, SIGINT
);
1420 /* Clears the file cache. */
1421 sigaddset(&sigset
, SIGUSR1
);
1423 /* Configuration file reloading. */
1424 sigaddset(&sigset
, SIGHUP
);
1426 /* For exiting cleanly. */
1427 sigaddset(&sigset
, SIGUSR2
);
1429 /* Clears the cache and exits when something bad happens. */
1430 signal(SIGABRT
, catch_sigabrt
);
1431 sigaddset(&sigset
, SIGABRT
);
1432 sigprocmask(SIG_BLOCK
, &sigset
, NULL
);
1434 /* Ignored everywhere. When a client disconnects abnormally this signal
1435 * gets raised. It isn't needed though because client_thread() will check
1436 * for rcs even after the client disconnects. */
1437 signal(SIGPIPE
, SIG_IGN
);
1439 /* Can show a backtrace of the stack in the log. */
1440 signal(SIGSEGV
, catchsig
);
1443 /* Needs to be done after the fork(). */
1444 if (!start_stop_tls(FALSE
)) {
1450 pthread_mutex_init(&quit_mutex
, NULL
);
1451 pthread_cond_init(&quit_cond
, NULL
);
1452 log_write(_("%s started for user %s"), PACKAGE_STRING
, g_get_user_name());
1453 #ifndef HAVE_DECL_SO_PEERCRED
1454 log_write(_("Peer credential checking is NOT supported on this OS."));
1457 if (get_key_file_boolean("global", "enable_tcp"))
1458 log_write(_("Listening on %s and TCP port %i"), *socketpath
,
1459 get_key_file_integer("global", "tcp_port"));
1461 log_write(_("Listening on %s"), *socketpath
);
1463 log_write(_("Listening on %s"), *socketpath
);
1466 rc
= create_thread(reload_rcfile_thread
, NULL
, &rcfile_tid
, FALSE
);
1468 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1473 rc
= create_thread(cache_timer_thread
, NULL
, &cache_timeout_tid
, TRUE
);
1475 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1480 rc
= create_thread(accept_thread
, &sockfd
, &accept_tid
, TRUE
);
1482 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1487 sigdelset(&sigset
, SIGUSR2
);
1489 signal_loop(sigset
);
1495 * We're out of the main server loop. This happens when a signal was sent
1496 * to terminate the daemon. We'll wait for all clients to disconnect
1497 * before exiting but exit immediately if another termination signal is
1501 pthread_cancel(accept_tid
);
1503 shutdown(sockfd
, SHUT_RDWR
);
1505 unlink(*socketpath
);
1506 g_free(*socketpath
);
1508 MUTEX_LOCK(&cn_mutex
);
1509 n
= g_slist_length(cn_thread_list
);
1510 MUTEX_UNLOCK(&cn_mutex
);
1515 rc
= create_thread(waiting_for_exit
, NULL
, &tid
, TRUE
);
1517 sigaddset(&sigset
, SIGUSR2
);
1518 if (signal_loop(sigset
)) {
1519 log_write(_("Received second termination request. Exiting."));
1520 pthread_cancel(tid
);
1524 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1528 if (cache_timeout_tid
)
1529 pthread_cancel(cache_timeout_tid
);
1531 MUTEX_LOCK(&cn_mutex
);
1533 n
= g_slist_length(cn_thread_list
);
1535 for (i
= 0; i
< n
; i
++) {
1536 struct client_thread_s
*thd
= g_slist_nth_data(cn_thread_list
, i
);
1538 if (thd
->fd
!= -1) {
1545 MUTEX_UNLOCK(&cn_mutex
);
1547 start_stop_tls(TRUE
);
1551 pthread_cond_destroy(&quit_cond
);
1552 pthread_mutex_destroy(&quit_mutex
);
1553 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
1556 static void startup_failure()
1558 log_write(_("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
1562 /* This is called from cache.c:clear_once(). See
1563 * command.c:clearcache_command() for details about lock checking.
1565 static gpg_error_t
free_cache_data(file_cache_t
*cache
)
1567 gpg_error_t rc
= GPG_ERR_NO_DATA
;
1569 struct client_thread_s
*found
= NULL
;
1570 gboolean self
= FALSE
;
1576 MUTEX_LOCK(&cn_mutex
);
1577 pthread_cleanup_push(cleanup_mutex_cb
, &cn_mutex
);
1578 t
= g_slist_length(cn_thread_list
);
1580 for (i
= 0; i
< t
; i
++) {
1581 struct client_thread_s
*thd
= g_slist_nth_data(cn_thread_list
, i
);
1586 if (!memcmp(thd
->cl
->md5file
, cache
->filename
,
1587 sizeof(cache
->filename
))) {
1588 if (pthread_equal(pthread_self(), thd
->tid
)) {
1594 /* Continue trying to find a client who has the same file open and
1595 * also has a lock. */
1596 rc
= cache_lock_mutex(thd
->cl
->ctx
, thd
->cl
->md5file
, -1, FALSE
, -1);
1605 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
1606 rc
= cache_lock_mutex(found
->cl
->ctx
, found
->cl
->md5file
, -1, FALSE
, -1);
1608 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
) {
1609 free_cache_data_once(cache
->data
);
1611 cache
->defer_clear
= FALSE
;
1612 cache
->timeout
= -1;
1615 cache_unlock_mutex(found
->cl
->md5file
, FALSE
);
1621 cache
->defer_clear
= TRUE
;
1623 pthread_cleanup_pop(1);
1628 static gboolean
convert_v2_datafile(const gchar
*filename
, const gchar
*cipher
,
1629 const gchar
*keyfile
, const gchar
*keygrip
, const gchar
*sign_keygrip
,
1630 gboolean nopass
, const gchar
*outfile
, const gchar
*keyparam
,
1631 gulong s2k_count
, guint64 iterations
)
1634 gpointer data
= NULL
;
1636 struct crypto_s
*crypto
= NULL
;
1640 if (outfile
[0] == '-' && outfile
[1] == 0)
1643 log_write(_("Converting version 2 data file \"%s\" ..."), filename
);
1644 if (access(filename
, R_OK
) == -1) {
1645 log_write("%s: %s", filename
, pwmd_strerror(gpg_error_from_syserror()));
1650 log_write(_("Using passphrase file \"%s\" for decryption ..."),
1652 if (access(keyfile
, R_OK
) == -1) {
1653 log_write("%s: %s", keyfile
,
1654 pwmd_strerror(gpg_error_from_syserror()));
1659 rc
= read_v2_datafile(filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
1661 log_write("%s", pwmd_strerror(rc
));
1666 algo
= cipher_string_to_gcrypt(cipher
);
1668 rc
= GPG_ERR_CIPHER_ALGO
;
1674 xmlDocPtr doc
= parse_doc(data
, datalen
);
1677 rc
= GPG_ERR_BAD_DATA
;
1681 rc
= convert_pre_212_elements(doc
);
1685 xmlDocDumpFormatMemory(doc
, (xmlChar
**)&data
, (gint
*)&datalen
, 0);
1687 rc
= GPG_ERR_ENOMEM
;
1695 rc
= init_client_crypto(&crypto
);
1697 rc
= set_pinentry_options(crypto
->agent
);
1699 memcpy(&crypto
->save
.hdr
, &crypto
->hdr
,
1700 sizeof(file_header_t
));
1701 crypto
->save
.hdr
.flags
= set_cipher_flag(crypto
->save
.hdr
.flags
, algo
);
1702 crypto
->save
.s2k_count
= (gulong
)s2k_count
;
1703 crypto
->save
.hdr
.iterations
= iterations
;
1704 rc
= export_common(crypto
, keygrip
, sign_keygrip
, nopass
, data
,
1705 datalen
, outfile
, keyparam
,
1706 no_passphrase_file
? NULL
: keyfile
);
1708 log_write(_("Output written to \"%s\"."), outfile
);
1717 cleanup_crypto(&crypto
);
1720 log_write("%s", pwmd_strerror(rc
));
1721 return rc
? FALSE
: TRUE
;
1724 int main(int argc
, char *argv
[])
1727 struct sockaddr_un addr
;
1728 gchar buf
[PATH_MAX
];
1729 gchar
*socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
1730 gchar
*socketarg
= NULL
;
1731 gchar
*datadir
= NULL
;
1735 gchar
**cache_push
= NULL
;
1736 gchar
*import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
1737 gchar
*keyparam
= NULL
;
1738 gboolean rcfile_spec
= FALSE
;
1739 gint estatus
= EXIT_FAILURE
;
1741 gchar
*outfile
= NULL
;
1742 GMemVTable mtable
= { xmalloc
, xrealloc
, xfree
, xcalloc
, NULL
, NULL
};
1744 gboolean secure
= FALSE
;
1745 gint show_version
= 0;
1746 gboolean force
= FALSE
;
1747 gboolean no_passphrase
= FALSE
;
1749 gchar
*convertfile
= NULL
;
1750 gchar
*cipher
= NULL
;
1751 gchar
*keyfile
= NULL
;
1752 glong s2k_count
= -1;
1753 guint64 iterations
= 0;
1754 GError
*error
= NULL
;
1755 gchar
*debug_level_opt
= NULL
;
1756 GOptionContext
*context
;
1757 GOptionEntry options
[] =
1759 { "version", 0, 0, G_OPTION_ARG_NONE
, &show_version
,
1760 "version information", NULL
},
1761 { "no-fork", 'n', 0, G_OPTION_ARG_NONE
, &nofork
,
1762 "run as a foreground process", NULL
},
1763 { "disable-dump", 'D', 0, G_OPTION_ARG_NONE
, &secure
,
1764 "disable the LIST, XPATH and DUMP commands", NULL
},
1765 { "rcfile", 'f', 0, G_OPTION_ARG_FILENAME
, &rcfile
,
1766 "load the specified rcfile (~/.pwmd/config)", "filename" },
1767 { "ignore", 0, 0, G_OPTION_ARG_NONE
, &force
,
1768 "ignore cache failures on startup", NULL
},
1769 { "outfile", 'o', 0, G_OPTION_ARG_FILENAME
, &outfile
,
1770 "output file when importing (- for stdout)", "filename" },
1771 { "convert", 'C', 0, G_OPTION_ARG_FILENAME
, &convertfile
,
1772 "convert a version 2 data file to version 3", "filename" },
1773 { "passphrase-file", 'k', 0, G_OPTION_ARG_FILENAME
, &keyfile
,
1774 "for decryption when converting", "filename" },
1775 { "no-passphrase-file", 0, 0, G_OPTION_ARG_NONE
, &no_passphrase_file
,
1776 "no --passphrase-file after conversion", NULL
},
1777 { "import", 'I', 0, G_OPTION_ARG_FILENAME
, &import
,
1778 "import an XML file", "filename" },
1779 { "keygrip", 0, 0, G_OPTION_ARG_STRING
, &keygrip
,
1780 "the public keygrip to use for encryption", "hexstring"},
1781 { "sign-keygrip", 0, 0, G_OPTION_ARG_STRING
, &sign_keygrip
,
1782 "the keygrip to use for signing of the data", "hexstring"},
1783 { "keyparam", 0, 0, G_OPTION_ARG_STRING
, &keyparam
,
1784 "alternate key parameters to use (RSA-2048)", "s-exp"},
1785 { "no-passphrase", 0, 0, G_OPTION_ARG_NONE
, &no_passphrase
,
1786 "for the imported/converted keypair", NULL
},
1787 { "cipher", 0, 0, G_OPTION_ARG_STRING
, &cipher
,
1788 "encryption cipher, see man page (aes256)", "string" },
1789 { "s2k-count", 0, 0, G_OPTION_ARG_INT64
, &s2k_count
,
1790 "hash iteration count >65536 (calibrated)", "iterations" },
1791 { "cipher-iterations", 0, 0, G_OPTION_ARG_INT64
, &iterations
,
1792 "cipher iteration count (N+1)", "iterations" },
1793 { "debug-level", 0, 0, G_OPTION_ARG_STRING
, &debug_level_opt
,
1794 "protocol output, see man page", "keywords"},
1795 { "homedir", 'I', 0, G_OPTION_ARG_STRING
, &homedir
,
1796 "home directory for pwmd", "directory" },
1801 #ifdef HAVE_SETRLIMIT
1804 rl
.rlim_cur
= rl
.rlim_max
= 0;
1806 if (setrlimit(RLIMIT_CORE
, &rl
) != 0)
1807 err(EXIT_FAILURE
, "setrlimit()");
1812 setlocale(LC_ALL
, "");
1813 bindtextdomain("pwmd", LOCALEDIR
);
1820 g_mem_set_vtable(&mtable
);
1821 g_thread_init(NULL
);
1828 gnutls_global_set_mem_functions(g_malloc
, g_malloc
, secure_mem_check
,
1830 gnutls_global_init();
1831 gnutls_global_set_log_function(tls_log
);
1832 gnutls_global_set_log_level(1);
1836 xmlMemSetup(g_free
, g_malloc
, g_realloc
, g_strdup
);
1843 context
= g_option_context_new("- Password Manager Daemon");
1844 g_option_context_add_main_entries(context
, options
, NULL
);
1845 if (!g_option_context_parse(context
, &argc
, &argv
, &error
))
1847 g_print("Option parsing failed: %s\n", error
->message
);
1853 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
1855 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
1856 "Compile time features:\n%s"), PACKAGE_STRING
, PACKAGE_BUGREPORT
,
1887 homedir
= g_strdup_printf("%s/.pwmd", g_get_home_dir());
1889 if (mkdir(homedir
, 0700) == -1 && errno
!= EEXIST
)
1890 err(EXIT_FAILURE
, "%s", homedir
);
1892 g_snprintf(buf
, sizeof(buf
), "%s/data", homedir
);
1893 if (mkdir(buf
, 0700) == -1 && errno
!= EEXIST
)
1894 err(EXIT_FAILURE
, "%s", buf
);
1896 datadir
= g_strdup(buf
);
1897 pthread_mutexattr_t attr
;
1898 pthread_mutexattr_init(&attr
);
1899 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
1900 pthread_mutex_init(&rcfile_mutex
, &attr
);
1901 pthread_cond_init(&rcfile_cond
, NULL
);
1902 pthread_mutex_init(&cn_mutex
, &attr
);
1903 pthread_mutexattr_destroy(&attr
);
1904 pthread_key_create(&last_error_key
, free_key
);
1907 rcfile
= g_strdup_printf("%s/config", homedir
);
1911 if ((keyfileh
= parse_rcfile(rcfile_spec
, cmdline
)) == NULL
)
1914 if (debug_level_opt
)
1915 debug_level
= g_strsplit(debug_level_opt
, ",", 0);
1917 if (g_key_file_has_key(keyfileh
, "global", "syslog", NULL
) == TRUE
)
1918 log_syslog
= g_key_file_get_boolean(keyfileh
, "global", "syslog", NULL
);
1920 if (log_syslog
== TRUE
)
1921 openlog("pwmd", LOG_NDELAY
|LOG_PID
, LOG_DAEMON
);
1923 if (g_key_file_has_key(keyfileh
, "global", "priority", NULL
)) {
1924 x
= g_key_file_get_integer(keyfileh
, "global", "priority", NULL
);
1927 if (setpriority(PRIO_PROCESS
, 0, x
) == -1) {
1928 log_write("setpriority(): %s", pwmd_strerror(gpg_error_from_syserror()));
1933 #ifdef HAVE_MLOCKALL
1934 if (disable_mlock
== FALSE
&& mlockall(MCL_CURRENT
|MCL_FUTURE
) == -1) {
1935 log_write("mlockall(): %s", pwmd_strerror(gpg_error_from_syserror()));
1940 rc
= cache_init(free_cache_data
);
1942 log_write("pwmd: gpg-agent: %s",
1943 gpg_err_code(rc
) == GPG_ERR_UNKNOWN_VERSION
1944 ? _("incompatible version: 2.1.0 or later required")
1945 : pwmd_strerror(rc
));
1949 if (s2k_count
== -1)
1950 s2k_count
= get_key_file_ulong(NULL
, "s2k_count");
1954 gchar
*tmp
= g_option_context_get_help(context
, TRUE
, NULL
);
1955 fprintf(stderr
, "%s", tmp
);
1960 estatus
= convert_v2_datafile(convertfile
, cipher
, keyfile
, keygrip
,
1961 sign_keygrip
, no_passphrase
, outfile
, keyparam
,
1962 (gulong
)s2k_count
, iterations
);
1963 g_key_file_free(keyfileh
);
1970 gchar
*tmp
= g_option_context_get_help(context
, TRUE
, NULL
);
1971 fprintf(stderr
, "%s", tmp
);
1976 if (outfile
[0] == '-' && outfile
[1] == 0)
1979 estatus
= xml_import(import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
1980 no_passphrase
, cipher
, keyparam
, (gulong
)s2k_count
, iterations
);
1981 g_key_file_free(keyfileh
);
1986 g_option_context_free(context
);
1987 p
= g_key_file_get_string(keyfileh
, "global", "socket_path", NULL
);
1989 p
= g_strdup_printf("%s/socket", homedir
);
1991 socketarg
= expand_homedir(p
);
1994 if (secure
== FALSE
&& g_key_file_has_key(keyfileh
, "global", "disable_list_and_dump", NULL
) == TRUE
) {
1995 n
= g_key_file_get_boolean(keyfileh
, "global", "disable_list_and_dump", NULL
);
1996 disable_list_and_dump
= n
;
1999 disable_list_and_dump
= secure
;
2001 setup_logging(keyfileh
);
2003 if (g_key_file_has_key(keyfileh
, "global", "cache_push", NULL
) == TRUE
)
2004 cache_push
= g_key_file_get_string_list(keyfileh
, "global", "cache_push", NULL
, NULL
);
2006 for (gint n
= 1; n
< argc
; n
++) {
2007 if (strv_printf(&cache_push
, "%s", argv
[n
]) == FALSE
)
2008 errx(EXIT_FAILURE
, "%s", pwmd_strerror(GPG_ERR_ENOMEM
));
2011 if (strchr(socketarg
, '/') == NULL
) {
2012 socketdir
= g_get_current_dir();
2013 socketname
= g_strdup(socketarg
);
2014 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
2017 socketname
= g_strdup(strrchr(socketarg
, '/'));
2019 socketarg
[strlen(socketarg
) - strlen(socketname
) -1] = 0;
2020 socketdir
= g_strdup(socketarg
);
2021 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
2024 if (chdir(datadir
)) {
2025 log_write("%s: %s", datadir
, pwmd_strerror(gpg_error_from_syserror()));
2031 * Set the cache entry for a file. Prompts for the password.
2034 struct crypto_s
*crypto
;
2035 gpg_error_t rc
= init_client_crypto(&crypto
);
2038 estatus
= EXIT_FAILURE
;
2042 rc
= set_pinentry_options(crypto
->agent
);
2044 estatus
= EXIT_FAILURE
;
2048 for (opt
= 0; cache_push
[opt
]; opt
++) {
2049 if (!do_cache_push(cache_push
[opt
], crypto
) && !force
) {
2050 g_strfreev(cache_push
);
2052 estatus
= EXIT_FAILURE
;
2053 cleanup_crypto(&crypto
);
2057 cleanup_crypto_stage1(crypto
);
2060 (void)kill_scd(crypto
->agent
);
2061 cleanup_crypto(&crypto
);
2062 g_strfreev(cache_push
);
2063 log_write(!nofork
? _("Done. Daemonizing...") : _("Done. Waiting for connections..."));
2066 clear_rcfile_keys();
2069 * bind() doesn't like the full pathname of the socket or any non alphanum
2070 * characters so change to the directory where the socket is wanted then
2071 * create it then change to datadir.
2073 if (chdir(socketdir
)) {
2074 log_write("%s: %s", socketdir
, pwmd_strerror(gpg_error_from_syserror()));
2080 if ((sockfd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) == -1) {
2081 log_write("socket(): %s", pwmd_strerror(gpg_error_from_syserror()));
2085 addr
.sun_family
= AF_UNIX
;
2086 g_snprintf(addr
.sun_path
, sizeof(addr
.sun_path
), "%s", socketname
);
2088 if (bind(sockfd
, (struct sockaddr
*)&addr
, sizeof(struct sockaddr
)) == -1) {
2089 log_write("bind(): %s", pwmd_strerror(gpg_error_from_syserror()));
2091 if (errno
== EADDRINUSE
)
2092 log_write(_("Either there is another pwmd running or '%s' is a \n"
2093 "stale socket. Please remove it manually."), socketpath
);
2099 if (g_key_file_has_key(keyfileh
, "global", "socket_perms", NULL
) == TRUE
) {
2100 gchar
*t
= g_key_file_get_string(keyfileh
, "global", "socket_perms", NULL
);
2101 mode_t mode
= strtol(t
, NULL
, 8);
2102 mode_t mask
= umask(0);
2106 if (chmod(socketname
, mode
) == -1) {
2107 log_write("%s: %s", socketname
, pwmd_strerror(gpg_error_from_syserror()));
2117 g_free(--socketname
);
2119 if (chdir(datadir
)) {
2120 log_write("%s: %s", datadir
, pwmd_strerror(gpg_error_from_syserror()));
2128 if (listen(sockfd
, 0) == -1) {
2129 log_write("listen(): %s", pwmd_strerror(gpg_error_from_syserror()));
2138 log_write("fork(): %s", pwmd_strerror(gpg_error_from_syserror()));
2147 _exit(EXIT_SUCCESS
);
2151 pthread_key_create(&thread_name_key
, free_key
);
2152 pthread_setspecific(thread_name_key
, g_strdup("main"));
2153 estatus
= server_loop(sockfd
, &socketpath
);
2156 if (socketpath
&& do_unlink
) {
2163 gnutls_global_deinit();
2166 g_key_file_free(keyfileh
);
2168 pthread_cancel(rcfile_tid
);
2169 pthread_join(rcfile_tid
, NULL
);
2170 pthread_cond_destroy(&rcfile_cond
);
2171 pthread_mutex_destroy(&rcfile_mutex
);
2174 xmlCleanupGlobals();
2176 if (estatus
== EXIT_SUCCESS
)
2177 log_write(_("pwmd exiting normally"));
2179 #if defined(DEBUG) && !defined(MEM_DEBUG)