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
);
139 pthread_cleanup_push(cleanup_mutex_cb
, &rcfile_mutex
);
142 gboolean b
= disable_list_and_dump
;
146 pthread_cond_wait(&rcfile_cond
, &rcfile_mutex
);
147 users
= g_key_file_get_string_list(keyfileh
, "global", "allowed", NULL
, NULL
);
148 log_write(_("reloading configuration file '%s'"), rcfile
);
149 k
= parse_rcfile(FALSE
, cmdline
);
151 g_key_file_free(keyfileh
);
153 cache_push_from_rcfile();
157 disable_list_and_dump
= !disable_list_and_dump
? b
: TRUE
;
158 g_key_file_set_string_list(keyfileh
, "global", "allowed",
159 (const gchar
**)users
, g_strv_length(users
));
162 /* Kill existing listening threads since the configured listening
163 * protocols may have changed. */
164 start_stop_tls(TRUE
);
165 start_stop_tls(FALSE
);
169 pthread_cleanup_pop(1);
173 gpg_error_t
send_error(assuan_context_t ctx
, gpg_error_t e
)
175 struct client_s
*client
= assuan_get_pointer(ctx
);
177 if (gpg_err_source(e
) == GPG_ERR_SOURCE_UNKNOWN
)
184 return assuan_process_done(ctx
, 0);
187 log_write("%s", pwmd_strerror(e
));
191 if (gpg_err_code(e
) == GPG_ERR_BAD_DATA
) {
192 xmlErrorPtr xe
= client
->xml_error
;
195 xe
= xmlGetLastError();
197 log_write("%s", xe
->message
);
198 if (client
->last_error
)
199 g_free(client
->last_error
);
201 client
->last_error
= g_strdup(xe
->message
);
204 e
= assuan_process_done(ctx
, assuan_set_error(ctx
, e
,
205 xe
? xe
->message
: NULL
));
207 if (xe
== client
->xml_error
)
212 client
->xml_error
= NULL
;
216 return assuan_process_done(ctx
, assuan_set_error(ctx
, e
, pwmd_strerror(e
)));
219 int assuan_log_cb(assuan_context_t ctx
, void *data
, unsigned cat
,
222 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
224 gboolean match
= FALSE
;
226 pthread_mutex_lock(&m
);
227 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock
, &m
);
228 t
= g_strv_length(debug_level
);
230 for (i
= 0; i
< t
; i
++) {
231 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"init")
232 && cat
== ASSUAN_LOG_INIT
) {
237 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"ctx")
238 && cat
== ASSUAN_LOG_CTX
) {
243 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"engine")
244 && cat
== ASSUAN_LOG_ENGINE
) {
249 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"data")
250 && cat
== ASSUAN_LOG_DATA
) {
255 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"sysio")
256 && cat
== ASSUAN_LOG_SYSIO
) {
261 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"control")
262 && cat
== ASSUAN_LOG_CONTROL
) {
272 if ((fd
= open(logfile
, O_WRONLY
|O_CREAT
|O_APPEND
, 0600)) == -1)
275 pthread_cleanup_push(cleanup_fd_cb
, &fd
);
276 write(fd
, msg
, strlen(msg
));
277 pthread_cleanup_pop(1);
282 fprintf(stderr
, "%s%s", data
? (gchar
*)data
: "", msg
);
287 pthread_cleanup_pop(1);
291 void log_write(const gchar
*fmt
, ...)
301 pthread_t tid
= pthread_self();
302 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
304 if ((!logfile
&& !isatty(STDERR_FILENO
) && !log_syslog
) || !fmt
)
307 pthread_mutex_lock(&m
);
308 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock
, &m
);
309 pthread_cleanup_push(cleanup_fd_cb
, &fd
);
311 if (!cmdline
&& logfile
) {
312 if ((fd
= open(logfile
, O_WRONLY
|O_CREAT
|O_APPEND
, 0600)) == -1)
318 if (g_vasprintf(&args
, fmt
, ap
) != -1) {
320 pthread_cleanup_push(g_free
, args
);
321 fprintf(stderr
, "%s\n", args
);
323 pthread_cleanup_pop(1);
326 pthread_cleanup_push(g_free
, args
);
327 name
= pthread_getspecific(thread_name_key
);
328 name
= print_fmt(buf
, sizeof(buf
), "%s(%p): ",
329 name
? name
: _("unknown"), (pthread_t
*)tid
);
331 if (!cmdline
&& log_syslog
&& !nofork
)
332 syslog(LOG_INFO
, "%s%s", name
, args
);
335 tm
= localtime(&now
);
336 strftime(tbuf
, sizeof(tbuf
), "%b %d %Y %H:%M:%S ", tm
);
337 tbuf
[sizeof(tbuf
) - 1] = 0;
339 if (args
[strlen(args
)-1] == '\n')
340 args
[strlen(args
)-1] = 0;
342 line
= g_strdup_printf("%s %i %s%s\n", tbuf
, getpid(), name
,
344 pthread_cleanup_pop(1);
346 pthread_cleanup_push(g_free
, line
);
347 if (logfile
&& fd
!= -1) {
348 write(fd
, line
, strlen(line
));
353 fprintf(stdout
, "%s", line
);
357 pthread_cleanup_pop(1);
363 pthread_cleanup_pop(1);
364 pthread_cleanup_pop(0);
365 pthread_mutex_unlock(&m
);
369 static gint
secure_mem_check(const void *arg
)
375 static gpg_error_t
setup_crypto()
377 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
379 if (!gcry_check_version(GCRYPT_VERSION
)) {
380 fprintf(stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
381 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
382 gcry_check_version(NULL
));
383 return GPG_ERR_UNKNOWN_VERSION
;
386 gcry_set_allocation_handler(g_malloc
, g_malloc
, NULL
, g_realloc
, g_free
);
390 static gpg_error_t
validate_peer(struct client_s
*cl
)
393 gboolean allowed
= FALSE
;
394 assuan_peercred_t peercred
;
402 rc
= assuan_get_peercred(cl
->ctx
, &peercred
);
406 users
= g_key_file_get_string_list(keyfileh
, "global", "allowed", NULL
, NULL
);
409 for (gchar
**p
= users
; *p
; p
++) {
410 struct passwd pw
, *result
;
411 struct group gr
, *gresult
;
415 size_t len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
424 return GPG_ERR_ENOMEM
;
427 if (!getgrnam_r(*(p
)+1, &gr
, buf
, len
, &gresult
) && gresult
) {
428 if (gresult
->gr_gid
== peercred
->gid
) {
434 len
= sysconf(_SC_GETPW_R_SIZE_MAX
);
439 gchar
*tbuf
= g_malloc(len
);
441 for (gchar
**t
= gresult
->gr_mem
; *t
; t
++) {
442 if (!getpwnam_r(*t
, &pw
, tbuf
, len
, &result
) && result
) {
443 if (result
->pw_uid
== peercred
->uid
) {
458 size_t len
= sysconf(_SC_GETPW_R_SIZE_MAX
);
467 return GPG_ERR_ENOMEM
;
470 if (!getpwnam_r(*p
, &pw
, buf
, len
, &result
) && result
) {
471 if (result
->pw_uid
== peercred
->uid
) {
485 log_write("peer %s: uid=%i, gid=%i, pid=%i",
486 allowed
? _("accepted") : _("rejected"), peercred
->uid
,
487 peercred
->gid
, peercred
->pid
);
488 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
491 static void xml_error_cb(void *data
, xmlErrorPtr e
)
493 struct client_s
*client
= data
;
496 * Keep the first reported error as the one to show in the error
497 * description. Reset in send_error().
499 if (client
->xml_error
)
502 xmlCopyError(e
, client
->xml_error
);
505 static pid_t
hook_waitpid(assuan_context_t ctx
, pid_t pid
, int action
,
506 int *status
, int options
)
508 return waitpid(pid
, status
, options
);
511 static ssize_t
hook_read(assuan_context_t ctx
, assuan_fd_t fd
, void *data
,
515 struct client_s
*client
= assuan_get_pointer(ctx
);
517 if (client
->thd
->remote
)
518 return tls_read_hook(ctx
, (gint
)fd
, data
, len
);
521 return read((gint
)fd
, data
, len
);
524 static ssize_t
hook_write(assuan_context_t ctx
, assuan_fd_t fd
,
525 const void *data
, size_t len
)
528 struct client_s
*client
= assuan_get_pointer(ctx
);
530 if (client
->thd
->remote
)
531 return tls_write_hook(ctx
, (gint
)fd
, data
, len
);
534 return write((gint
)fd
, data
, len
);
537 static gboolean
new_connection(struct client_s
*cl
)
540 static struct assuan_malloc_hooks mhooks
= { g_malloc
, g_realloc
, g_free
};
541 static struct assuan_system_hooks shooks
= {
542 ASSUAN_SYSTEM_HOOKS_VERSION
,
550 NULL
, //sendmsg both are used for FD passing
559 if (cl
->thd
->remote
) {
560 gchar
*prio
= get_key_file_string("global", "tls_cipher_suite");
562 cl
->thd
->tls
= tls_init(cl
->thd
->fd
, prio
);
569 rc
= assuan_new_ext(&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
570 debug_level
? assuan_log_cb
: NULL
, NULL
);
574 assuan_ctx_set_system_hooks(cl
->ctx
, &shooks
);
575 rc
= assuan_init_socket_server(cl
->ctx
, cl
->thd
->fd
, 2);
579 assuan_set_pointer(cl
->ctx
, cl
);
580 assuan_set_hello_line(cl
->ctx
, PACKAGE_STRING
);
581 rc
= register_commands(cl
->ctx
);
585 rc
= assuan_accept(cl
->ctx
);
589 rc
= validate_peer(cl
);
590 /* May not be implemented on all platforms. */
591 if (rc
&& gpg_err_code(rc
) != GPG_ERR_ASS_GENERAL
)
594 rc
= init_client_crypto(&cl
->crypto
);
598 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
599 cl
->crypto
->client_ctx
= cl
->ctx
;
600 xmlSetStructuredErrorFunc(cl
, xml_error_cb
);
604 log_write("%s", pwmd_strerror(rc
));
609 * This is called after a client_thread() terminates. Set with
610 * pthread_cleanup_push().
612 static void cleanup_cb(void *arg
)
614 struct client_thread_s
*cn
= arg
;
615 struct client_s
*cl
= cn
->cl
;
617 MUTEX_LOCK(&cn_mutex
);
618 cn_thread_list
= g_slist_remove(cn_thread_list
, cn
);
619 MUTEX_UNLOCK(&cn_mutex
);
626 gnutls_deinit(cn
->tls
->ses
);
633 assuan_release(cl
->ctx
);
634 else if (cl
->thd
&& cl
->thd
->fd
!= -1)
638 cleanup_crypto(&cl
->crypto
);
647 while (cn
->msg_queue
) {
648 struct status_msg_s
*msg
= cn
->msg_queue
;
650 cn
->msg_queue
= msg
->next
;
655 if (cn
->status_msg_pipe
[0] != -1)
656 close(cn
->status_msg_pipe
[0]);
658 if (cn
->status_msg_pipe
[1] != -1)
659 close(cn
->status_msg_pipe
[1]);
661 pthread_mutex_destroy(&cn
->status_mutex
);
662 log_write(_("exiting, fd=%i"), cn
->fd
);
664 send_status_all(STATUS_CLIENTS
, NULL
);
665 pthread_cond_signal(&quit_cond
);
668 static gpg_error_t
send_msg_queue(struct client_thread_s
*thd
)
670 MUTEX_LOCK(&thd
->status_mutex
);
674 read(thd
->status_msg_pipe
[0], &c
, 1);
676 while (thd
->msg_queue
) {
677 struct status_msg_s
*msg
= thd
->msg_queue
;
679 thd
->msg_queue
= thd
->msg_queue
->next
;
680 MUTEX_UNLOCK(&thd
->status_mutex
);
681 rc
= send_status(thd
->cl
->ctx
, msg
->s
, msg
->line
);
682 MUTEX_LOCK(&thd
->status_mutex
);
690 MUTEX_UNLOCK(&thd
->status_mutex
);
694 static void *client_thread(void *data
)
696 struct client_thread_s
*thd
= data
;
697 struct client_s
*cl
= g_malloc0(sizeof(struct client_s
));
699 #ifdef HAVE_PR_SET_NAME
700 prctl(PR_SET_NAME
, "client");
702 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
705 log_write("%s(%i): %s", __FILE__
, __LINE__
,
706 pwmd_strerror(GPG_ERR_ENOMEM
));
710 MUTEX_LOCK(&cn_mutex
);
711 pthread_cleanup_push(cleanup_cb
, thd
);
714 MUTEX_UNLOCK(&cn_mutex
);
716 if (new_connection(cl
)) {
717 gboolean finished
= FALSE
;
720 send_status_all(STATUS_CLIENTS
, NULL
);
721 rc
= send_status(cl
->ctx
, STATUS_CACHE
, NULL
);
723 log_write("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror(rc
));
733 FD_SET(thd
->fd
, &rfds
);
734 FD_SET(thd
->status_msg_pipe
[0], &rfds
);
735 n
= thd
->fd
> thd
->status_msg_pipe
[0] ? thd
->fd
: thd
->status_msg_pipe
[0];
737 n
= select(n
+1, &rfds
, NULL
, NULL
, NULL
);
739 log_write("%s", strerror(errno
));
743 if (FD_ISSET(thd
->status_msg_pipe
[0], &rfds
)) {
744 rc
= send_msg_queue(thd
);
745 if (rc
&& gpg_err_code(rc
) != GPG_ERR_EPIPE
) {
746 log_write("%s(%i): %s", __FUNCTION__
, __LINE__
,
752 if (!FD_ISSET(thd
->fd
, &rfds
))
755 rc
= assuan_process_next(cl
->ctx
, &eof
);
757 if (gpg_err_code(rc
) == GPG_ERR_EOF
|| eof
)
760 log_write("assuan_process_next(): %s", pwmd_strerror(rc
));
761 rc
= send_error(cl
->ctx
, rc
);
764 log_write("assuan_process_done(): %s", pwmd_strerror(rc
));
769 /* Since the msg queue pipe fd's are non-blocking, check for
770 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
771 * client has already disconnected and will be converted to
772 * GPG_ERR_EOF during assuan_process_next().
774 rc
= send_msg_queue(thd
);
775 if (rc
&& gpg_err_code(rc
) != GPG_ERR_EPIPE
) {
776 log_write("%s(%i): %s", __FUNCTION__
, __LINE__
,
783 pthread_cleanup_pop(1);
787 static gboolean
xml_import(const gchar
*filename
, const gchar
*outfile
,
788 const gchar
*keygrip
, const char *sign_keygrip
, const gchar
*keyfile
,
789 gboolean no_passphrase
, const gchar
*cipher
, const gchar
*params
,
790 gulong s2k_count
, guint64 iterations
)
799 struct crypto_s
*crypto
;
800 gint algo
= cipher
? cipher_string_to_gcrypt((gchar
*)cipher
) :
804 log_write("%s", pwmd_strerror(GPG_ERR_CIPHER_ALGO
));
808 if (stat(filename
, &st
) == -1) {
809 log_write("%s: %s", filename
, pwmd_strerror(gpg_error_from_syserror()));
813 rc
= init_client_crypto(&crypto
);
817 memcpy(&crypto
->save
.hdr
, &crypto
->hdr
, sizeof(file_header_t
));
818 crypto
->save
.hdr
.flags
= set_cipher_flag(crypto
->save
.hdr
.flags
, algo
);
819 log_write(_("Importing XML from '%s'. Output will be written to '%s' ..."),
822 if ((fd
= open(filename
, O_RDONLY
)) == -1) {
823 log_write("%s: %s", filename
, pwmd_strerror(gpg_error_from_syserror()));
827 if ((xmlbuf
= xmalloc(st
.st_size
+1)) == NULL
) {
829 log_write("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror(GPG_ERR_ENOMEM
));
833 if (read(fd
, xmlbuf
, st
.st_size
) == -1) {
834 rc
= gpg_error_from_syserror();
836 log_write("%s: %s", filename
, pwmd_strerror(rc
));
841 xmlbuf
[st
.st_size
] = 0;
843 * Make sure the document validates.
845 if ((doc
= xmlReadDoc(xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
) {
846 log_write("xmlReadDoc() failed");
852 xmlNodePtr n
= xmlDocGetRootElement(doc
);
853 if (!xmlStrEqual(n
->name
, (xmlChar
*)"pwmd")) {
854 log_write(_("Could not find root \"pwmd\" element."));
855 rc
= GPG_ERR_BAD_DATA
;
859 rc
= validate_import(n
? n
->children
: n
);
862 log_write("%s", pwmd_strerror(rc
));
867 xmlDocDumpMemory(doc
, &xml
, &len
);
869 crypto
->save
.s2k_count
= (gulong
)s2k_count
;
870 crypto
->save
.hdr
.iterations
= iterations
;
871 rc
= set_pinentry_options(crypto
->agent
);
873 rc
= export_common(crypto
, keygrip
, sign_keygrip
, no_passphrase
, xml
,
874 len
, outfile
, params
, keyfile
);
878 send_error(NULL
, rc
);
882 cleanup_crypto(&crypto
);
886 cleanup_crypto(&crypto
);
890 static gboolean
do_cache_push(const gchar
*filename
, struct crypto_s
*crypto
)
897 struct cache_data_s
*cdata
;
901 log_write(_("Trying to add datafile '%s' to the file cache ..."),
904 if (valid_filename(filename
) == FALSE
) {
905 log_write(_("%s: Invalid characters in filename"), filename
);
909 rc
= read_data_file(filename
, crypto
);
911 log_write("%s", pwmd_strerror(rc
));
915 if ((key
= get_key_file_string(filename
, "passphrase"))) {
916 log_write(_("Trying the passphrase specified in config ..."));
917 keylen
= strlen(key
);
919 else if ((key
= get_key_file_string(filename
, "passphrase_file"))) {
920 gint fd
= open((gchar
*)key
, O_RDONLY
);
923 log_write(_("Trying the passphrase using file '%s' ..."), key
);
925 log_write("%s: %s", key
, pwmd_strerror(gpg_error_from_syserror()));
930 stat((gchar
*)key
, &st
);
932 key
= g_malloc(st
.st_size
);
933 if (read(fd
, key
, st
.st_size
) != st
.st_size
) {
934 log_write("short read() count");
944 rc
= set_agent_passphrase(crypto
, key
, keylen
);
947 log_write("%s", pwmd_strerror(rc
));
952 crypto
->filename
= g_strdup(filename
);
953 rc
= decrypt_data(NULL
, crypto
);
955 log_write("%s", pwmd_strerror(rc
));
959 doc
= parse_doc((gchar
*)crypto
->plaintext
, crypto
->plaintext_len
);
961 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM
));
965 gcry_md_hash_buffer(GCRY_MD_MD5
, md5file
, filename
, strlen(filename
));
966 cdata
= g_malloc0(sizeof(struct cache_data_s
));
969 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM
));
973 rc
= get_checksum(filename
, &crc
, &len
);
975 log_write("%s", pwmd_strerror(rc
));
977 free_cache_data_once(cdata
);
982 rc
= encrypt_xml(NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
983 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
984 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
986 log_write("%s", pwmd_strerror(rc
));
988 free_cache_data_once(cdata
);
992 gcry_sexp_build((gcry_sexp_t
*)&cdata
->pubkey
, NULL
, "%S", crypto
->pkey_sexp
);
993 gcry_sexp_build((gcry_sexp_t
*)&cdata
->sigkey
, NULL
, "%S", crypto
->sigpkey_sexp
);
994 gint timeout
= get_key_file_integer(filename
, "cache_timeout");
995 cache_add_file(md5file
, crypto
->grip
, cdata
, timeout
);
996 log_write(_("Successfully added '%s' to the cache."), filename
);
1000 static gpg_error_t
init_client_thread(gint fd
, const gchar
*addr
)
1003 struct client_thread_s
*new = g_malloc0(sizeof(struct client_thread_s
));
1007 return GPG_ERR_ENOMEM
;
1010 MUTEX_LOCK(&cn_mutex
);
1011 pthread_cleanup_push(cleanup_mutex_cb
, &cn_mutex
);
1013 if (pipe(new->status_msg_pipe
) == -1)
1014 rc
= gpg_error_from_syserror();
1017 fcntl(new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1018 fcntl(new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1019 pthread_mutex_init(&new->status_mutex
, NULL
);
1024 new->remote
= addr
? TRUE
: FALSE
;
1027 rc
= create_thread(client_thread
, new, &new->tid
, TRUE
);
1029 close(new->status_msg_pipe
[0]);
1030 close(new->status_msg_pipe
[1]);
1031 pthread_mutex_destroy(&new->status_mutex
);
1036 cn_thread_list
= g_slist_append(cn_thread_list
, new);
1038 log_write(_("new connection: tid=%p, fd=%i, addr=%s"),
1039 (pthread_t
*)new->tid
, fd
, addr
);
1041 log_write(_("new connection: tid=%p, fd=%i"),
1042 (pthread_t
*)new->tid
, fd
);
1045 pthread_cleanup_pop(1);
1050 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1057 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1058 static void *get_in_addr(struct sockaddr
*sa
)
1060 if (sa
->sa_family
== AF_INET
)
1061 return &(((struct sockaddr_in
*)sa
)->sin_addr
);
1063 return &(((struct sockaddr_in6
*)sa
)->sin6_addr
);
1066 static void *tcp_accept_thread(void *arg
)
1068 gint sockfd
= *(gint
*)arg
;
1070 #ifdef HAVE_PR_SET_NAME
1071 prctl(PR_SET_NAME
, "tcp_accept");
1073 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1076 struct sockaddr_storage raddr
;
1077 socklen_t slen
= sizeof(raddr
);
1081 gchar s
[INET6_ADDRSTRLEN
];
1083 fd
= accept(sockfd
, (struct sockaddr
*)&raddr
, &slen
);
1085 if (errno
!= EAGAIN
) {
1086 if (!quit
) // probably EBADF
1087 log_write("accept(): %s", strerror(errno
));
1098 inet_ntop(raddr
.ss_family
, get_in_addr((struct sockaddr
*)&raddr
),
1100 (void)init_client_thread(fd
, s
);
1101 t
= get_key_file_string("global", "tcp_wait");
1102 n
= strtol(t
, NULL
, 10);
1108 /* Just in case accept() failed for some reason other than EBADF */
1113 static gboolean
start_stop_tls_with_protocol(gboolean ipv6
, gboolean term
)
1115 struct addrinfo hints
, *servinfo
, *p
;
1116 gint port
= get_key_file_integer("global", "tcp_port");
1120 gint
*fd
= ipv6
? &tls6_fd
: &tls_fd
;
1122 if (term
|| get_key_file_boolean("global", "enable_tcp") == FALSE
) {
1123 if (tls6_fd
!= -1) {
1124 pthread_cancel(tls6_tid
);
1125 pthread_join(tls6_tid
, NULL
);
1126 shutdown(tls6_fd
, SHUT_RDWR
);
1132 pthread_cancel(tls_tid
);
1133 pthread_join(tls_tid
, NULL
);
1134 shutdown(tls_fd
, SHUT_RDWR
);
1139 /* A client may still be connected. */
1140 if (!quit
&& x509_cred
!= NULL
)
1141 tls_deinit_params();
1146 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1149 memset(&hints
, 0, sizeof(hints
));
1150 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1151 hints
.ai_socktype
= SOCK_STREAM
;
1152 hints
.ai_flags
= AI_PASSIVE
;
1154 if ((n
= getaddrinfo(NULL
, print_fmt(buf
, sizeof(buf
), "%i", port
),
1155 &hints
, &servinfo
)) == -1) {
1156 log_write("getaddrinfo(): %s", gai_strerror(n
));
1160 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
) {
1161 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1162 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1165 if ((*fd
= socket(p
->ai_family
, p
->ai_socktype
,
1166 p
->ai_protocol
)) == -1) {
1167 log_write("socket(): %s", strerror(errno
));
1171 if (setsockopt(*fd
, SOL_SOCKET
, SO_REUSEADDR
, &n
,
1172 sizeof(int)) == -1) {
1173 log_write("setsockopt(): %s", strerror(errno
));
1174 freeaddrinfo(servinfo
);
1178 if (bind(*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1) {
1180 log_write("bind(): %s", strerror(errno
));
1188 freeaddrinfo(servinfo
);
1191 log_write("%s", _("could not bind"));
1195 #ifdef HAVE_DECL_SO_BINDTODEVICE
1196 if (g_key_file_has_key(keyfileh
, "global", "tcp_interface", NULL
)) {
1197 gchar
*tmp
= get_key_file_string("global", "tcp_interface");
1199 if (setsockopt(*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
, 1)
1201 log_write("setsockopt(): %s", strerror(errno
));
1210 if (x509_cred
== NULL
) {
1211 rc
= tls_init_params();
1216 if (listen(*fd
, 0) == -1) {
1217 log_write("listen(): %s", strerror(errno
));
1222 rc
= create_thread(tcp_accept_thread
, fd
, &tls6_tid
, FALSE
);
1224 rc
= create_thread(tcp_accept_thread
, fd
, &tls_tid
, FALSE
);
1227 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1235 start_stop_tls_with_protocol(FALSE
, TRUE
);
1247 static gboolean
start_stop_tls(gboolean term
)
1249 gchar
*s
= get_key_file_string("global", "tcp_bind");
1255 if (!g_strcmp0(s
, "any")) {
1256 b
= start_stop_tls_with_protocol(FALSE
, term
);
1258 b
= start_stop_tls_with_protocol(TRUE
, term
);
1260 else if (!g_strcmp0(s
, "ipv4"))
1261 b
= start_stop_tls_with_protocol(FALSE
, term
);
1262 else if (!g_strcmp0(s
, "ipv6"))
1263 b
= start_stop_tls_with_protocol(TRUE
, term
);
1272 static void *accept_thread(void *arg
)
1274 gint sockfd
= *(gint
*)arg
;
1276 #ifdef HAVE_PR_SET_NAME
1277 prctl(PR_SET_NAME
, "accept");
1279 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1282 socklen_t slen
= sizeof(struct sockaddr_un
);
1283 struct sockaddr_un raddr
;
1286 fd
= accept(sockfd
, (struct sockaddr
*)&raddr
, &slen
);
1288 if (errno
!= EAGAIN
) {
1289 if (!quit
) // probably EBADF
1290 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1297 (void)init_client_thread(fd
, NULL
);
1300 /* Just in case accept() failed for some reason other than EBADF */
1305 static void *cache_timer_thread(void *arg
)
1307 #ifdef HAVE_PR_SET_NAME
1308 prctl(PR_SET_NAME
, "cache timer");
1310 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1314 cache_adjust_timeout();
1320 static void catch_sigabrt(int sig
)
1328 static gboolean
signal_loop(sigset_t sigset
)
1330 gboolean done
= FALSE
;
1331 gboolean sigint
= FALSE
;
1334 gint sig
= sigwaitinfo(&sigset
, NULL
);
1337 if (errno
!= EAGAIN
)
1338 log_write("sigwaitinfo(): %s", strerror(errno
));
1343 log_write(_("caught signal %i (%s)"), sig
, strsignal(sig
));
1347 pthread_cond_signal(&rcfile_cond
);
1350 // not really handled here.
1351 catch_sigabrt(SIGABRT
);
1354 log_write(_("clearing file cache"));
1356 send_status_all(STATUS_CACHE
, NULL
);
1371 static void catchsig(int sig
)
1373 log_write("Caught SIGSEGV. Exiting.");
1374 #ifdef HAVE_BACKTRACE
1375 BACKTRACE(__FUNCTION__
);
1380 static void *waiting_for_exit(void *arg
)
1382 #ifdef HAVE_PR_SET_NAME
1383 prctl(PR_SET_NAME
, "exiting");
1385 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1386 log_write(_("waiting for all clients to disconnect"));
1387 MUTEX_LOCK(&quit_mutex
);
1388 pthread_cleanup_push(cleanup_mutex_cb
, &quit_mutex
);
1391 MUTEX_LOCK(&cn_mutex
);
1392 gint n
= g_slist_length(cn_thread_list
);
1393 MUTEX_UNLOCK(&cn_mutex
);
1397 log_write(_("%i clients remain"), n
);
1398 pthread_cond_wait(&quit_cond
, &quit_mutex
);
1401 pthread_cleanup_pop(1);
1402 kill(getpid(), SIGUSR2
);
1406 static gboolean
server_loop(gint sockfd
, gchar
**socketpath
)
1408 pthread_t accept_tid
;
1409 pthread_t cache_timeout_tid
;
1410 gboolean cancel_timeout_thread
= FALSE
, cancel_accept_thread
= FALSE
;
1413 gboolean segv
= FALSE
;
1417 sigemptyset(&sigset
);
1420 sigaddset(&sigset
, SIGTERM
);
1421 sigaddset(&sigset
, SIGINT
);
1423 /* Clears the file cache. */
1424 sigaddset(&sigset
, SIGUSR1
);
1426 /* Configuration file reloading. */
1427 sigaddset(&sigset
, SIGHUP
);
1429 /* For exiting cleanly. */
1430 sigaddset(&sigset
, SIGUSR2
);
1432 /* Clears the cache and exits when something bad happens. */
1433 signal(SIGABRT
, catch_sigabrt
);
1434 sigaddset(&sigset
, SIGABRT
);
1435 sigprocmask(SIG_BLOCK
, &sigset
, NULL
);
1437 /* Ignored everywhere. When a client disconnects abnormally this signal
1438 * gets raised. It isn't needed though because client_thread() will check
1439 * for rcs even after the client disconnects. */
1440 signal(SIGPIPE
, SIG_IGN
);
1442 /* Can show a backtrace of the stack in the log. */
1443 signal(SIGSEGV
, catchsig
);
1446 /* Needs to be done after the fork(). */
1447 if (!start_stop_tls(FALSE
)) {
1453 pthread_mutex_init(&quit_mutex
, NULL
);
1454 pthread_cond_init(&quit_cond
, NULL
);
1455 log_write(_("%s started for user %s"), PACKAGE_STRING
, g_get_user_name());
1456 #ifndef HAVE_DECL_SO_PEERCRED
1457 log_write(_("Peer credential checking is NOT supported on this OS."));
1460 if (get_key_file_boolean("global", "enable_tcp"))
1461 log_write(_("Listening on %s and TCP port %i"), *socketpath
,
1462 get_key_file_integer("global", "tcp_port"));
1464 log_write(_("Listening on %s"), *socketpath
);
1466 log_write(_("Listening on %s"), *socketpath
);
1469 rc
= create_thread(reload_rcfile_thread
, NULL
, &rcfile_tid
, FALSE
);
1471 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1476 rc
= create_thread(cache_timer_thread
, NULL
, &cache_timeout_tid
, TRUE
);
1478 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1483 cancel_timeout_thread
= TRUE
;
1484 rc
= create_thread(accept_thread
, &sockfd
, &accept_tid
, TRUE
);
1486 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1491 cancel_accept_thread
= TRUE
;
1492 sigdelset(&sigset
, SIGUSR2
);
1494 signal_loop(sigset
);
1500 * We're out of the main server loop. This happens when a signal was sent
1501 * to terminate the daemon. We'll wait for all clients to disconnect
1502 * before exiting but exit immediately if another termination signal is
1505 if (cancel_accept_thread
)
1506 pthread_cancel(accept_tid
);
1508 shutdown(sockfd
, SHUT_RDWR
);
1510 unlink(*socketpath
);
1511 g_free(*socketpath
);
1513 MUTEX_LOCK(&cn_mutex
);
1514 n
= g_slist_length(cn_thread_list
);
1515 MUTEX_UNLOCK(&cn_mutex
);
1520 rc
= create_thread(waiting_for_exit
, NULL
, &tid
, TRUE
);
1522 sigaddset(&sigset
, SIGUSR2
);
1523 if (signal_loop(sigset
)) {
1524 log_write(_("Received second termination request. Exiting."));
1525 pthread_cancel(tid
);
1529 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1533 if (cancel_timeout_thread
)
1534 pthread_cancel(cache_timeout_tid
);
1536 MUTEX_LOCK(&cn_mutex
);
1538 n
= g_slist_length(cn_thread_list
);
1540 for (i
= 0; i
< n
; i
++) {
1541 struct client_thread_s
*thd
= g_slist_nth_data(cn_thread_list
, i
);
1543 if (thd
->fd
!= -1) {
1550 MUTEX_UNLOCK(&cn_mutex
);
1552 start_stop_tls(TRUE
);
1556 pthread_cond_destroy(&quit_cond
);
1557 pthread_mutex_destroy(&quit_mutex
);
1558 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
1561 static void startup_failure()
1563 log_write(_("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
1567 /* This is called from cache.c:clear_once(). See
1568 * command.c:clearcache_command() for details about lock checking.
1570 static gpg_error_t
free_cache_data(file_cache_t
*cache
)
1572 gpg_error_t rc
= GPG_ERR_NO_DATA
;
1574 struct client_thread_s
*found
= NULL
;
1575 gboolean self
= FALSE
;
1581 MUTEX_LOCK(&cn_mutex
);
1582 pthread_cleanup_push(cleanup_mutex_cb
, &cn_mutex
);
1583 t
= g_slist_length(cn_thread_list
);
1585 for (i
= 0; i
< t
; i
++) {
1586 struct client_thread_s
*thd
= g_slist_nth_data(cn_thread_list
, i
);
1591 if (!memcmp(thd
->cl
->md5file
, cache
->filename
,
1592 sizeof(cache
->filename
))) {
1593 if (pthread_equal(pthread_self(), thd
->tid
)) {
1599 /* Continue trying to find a client who has the same file open and
1600 * also has a lock. */
1601 rc
= cache_lock_mutex(thd
->cl
->ctx
, thd
->cl
->md5file
, -1, FALSE
, -1);
1610 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
1611 rc
= cache_lock_mutex(found
->cl
->ctx
, found
->cl
->md5file
, -1, FALSE
, -1);
1613 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
) {
1614 free_cache_data_once(cache
->data
);
1616 cache
->defer_clear
= FALSE
;
1617 cache
->timeout
= -1;
1620 cache_unlock_mutex(found
->cl
->md5file
, FALSE
);
1626 cache
->defer_clear
= TRUE
;
1628 pthread_cleanup_pop(1);
1633 static gboolean
convert_v2_datafile(const gchar
*filename
, const gchar
*cipher
,
1634 const gchar
*keyfile
, const gchar
*keygrip
, const gchar
*sign_keygrip
,
1635 gboolean nopass
, const gchar
*outfile
, const gchar
*keyparam
,
1636 gulong s2k_count
, guint64 iterations
)
1639 gpointer data
= NULL
;
1641 struct crypto_s
*crypto
= NULL
;
1645 if (outfile
[0] == '-' && outfile
[1] == 0)
1648 log_write(_("Converting version 2 data file \"%s\" ..."), filename
);
1649 if (access(filename
, R_OK
) == -1) {
1650 log_write("%s: %s", filename
, pwmd_strerror(gpg_error_from_syserror()));
1655 log_write(_("Using passphrase file \"%s\" for decryption ..."),
1657 if (access(keyfile
, R_OK
) == -1) {
1658 log_write("%s: %s", keyfile
,
1659 pwmd_strerror(gpg_error_from_syserror()));
1664 rc
= read_v2_datafile(filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
1666 log_write("%s", pwmd_strerror(rc
));
1671 algo
= cipher_string_to_gcrypt(cipher
);
1673 rc
= GPG_ERR_CIPHER_ALGO
;
1679 xmlDocPtr doc
= parse_doc(data
, datalen
);
1682 rc
= GPG_ERR_BAD_DATA
;
1686 rc
= convert_pre_212_elements(doc
);
1690 xmlDocDumpFormatMemory(doc
, (xmlChar
**)&data
, (gint
*)&datalen
, 0);
1692 rc
= GPG_ERR_ENOMEM
;
1700 rc
= init_client_crypto(&crypto
);
1702 rc
= set_pinentry_options(crypto
->agent
);
1704 memcpy(&crypto
->save
.hdr
, &crypto
->hdr
,
1705 sizeof(file_header_t
));
1706 crypto
->save
.hdr
.flags
= set_cipher_flag(crypto
->save
.hdr
.flags
, algo
);
1707 crypto
->save
.s2k_count
= (gulong
)s2k_count
;
1708 crypto
->save
.hdr
.iterations
= iterations
;
1709 rc
= export_common(crypto
, keygrip
, sign_keygrip
, nopass
, data
,
1710 datalen
, outfile
, keyparam
,
1711 no_passphrase_file
? NULL
: keyfile
);
1713 log_write(_("Output written to \"%s\"."), outfile
);
1722 cleanup_crypto(&crypto
);
1725 log_write("%s", pwmd_strerror(rc
));
1726 return rc
? FALSE
: TRUE
;
1729 int main(int argc
, char *argv
[])
1732 struct sockaddr_un addr
;
1733 gchar buf
[PATH_MAX
];
1734 gchar
*socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
1735 gchar
*socketarg
= NULL
;
1736 gchar
*datadir
= NULL
;
1740 gchar
**cache_push
= NULL
;
1741 gchar
*import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
1742 gchar
*keyparam
= NULL
;
1743 gboolean rcfile_spec
= FALSE
;
1744 gint estatus
= EXIT_FAILURE
;
1746 gchar
*outfile
= NULL
;
1747 GMemVTable mtable
= { xmalloc
, xrealloc
, xfree
, xcalloc
, NULL
, NULL
};
1749 gboolean secure
= FALSE
;
1750 gint show_version
= 0;
1751 gboolean force
= FALSE
;
1752 gboolean no_passphrase
= FALSE
;
1754 gchar
*convertfile
= NULL
;
1755 gchar
*cipher
= NULL
;
1756 gchar
*keyfile
= NULL
;
1757 glong s2k_count
= -1;
1758 guint64 iterations
= 0;
1759 GError
*error
= NULL
;
1760 gchar
*debug_level_opt
= NULL
;
1761 GOptionContext
*context
;
1762 GOptionEntry options
[] =
1764 { "version", 0, 0, G_OPTION_ARG_NONE
, &show_version
,
1765 "version information", NULL
},
1766 { "no-fork", 'n', 0, G_OPTION_ARG_NONE
, &nofork
,
1767 "run as a foreground process", NULL
},
1768 { "disable-dump", 'D', 0, G_OPTION_ARG_NONE
, &secure
,
1769 "disable the LIST, XPATH and DUMP commands", NULL
},
1770 { "rcfile", 'f', 0, G_OPTION_ARG_FILENAME
, &rcfile
,
1771 "load the specified rcfile (~/.pwmd/config)", "filename" },
1772 { "ignore", 0, 0, G_OPTION_ARG_NONE
, &force
,
1773 "ignore cache failures on startup", NULL
},
1774 { "outfile", 'o', 0, G_OPTION_ARG_FILENAME
, &outfile
,
1775 "output file when importing (- for stdout)", "filename" },
1776 { "convert", 'C', 0, G_OPTION_ARG_FILENAME
, &convertfile
,
1777 "convert a version 2 data file to version 3", "filename" },
1778 { "passphrase-file", 'k', 0, G_OPTION_ARG_FILENAME
, &keyfile
,
1779 "for decryption when converting", "filename" },
1780 { "no-passphrase-file", 0, 0, G_OPTION_ARG_NONE
, &no_passphrase_file
,
1781 "no --passphrase-file after conversion", NULL
},
1782 { "import", 'I', 0, G_OPTION_ARG_FILENAME
, &import
,
1783 "import an XML file", "filename" },
1784 { "keygrip", 0, 0, G_OPTION_ARG_STRING
, &keygrip
,
1785 "the public keygrip to use for encryption", "hexstring"},
1786 { "sign-keygrip", 0, 0, G_OPTION_ARG_STRING
, &sign_keygrip
,
1787 "the keygrip to use for signing of the data", "hexstring"},
1788 { "keyparam", 0, 0, G_OPTION_ARG_STRING
, &keyparam
,
1789 "alternate key parameters to use (RSA-2048)", "s-exp"},
1790 { "no-passphrase", 0, 0, G_OPTION_ARG_NONE
, &no_passphrase
,
1791 "for the imported/converted keypair", NULL
},
1792 { "cipher", 0, 0, G_OPTION_ARG_STRING
, &cipher
,
1793 "encryption cipher, see man page (aes256)", "string" },
1794 { "s2k-count", 0, 0, G_OPTION_ARG_INT64
, &s2k_count
,
1795 "hash iteration count >65536 (calibrated)", "iterations" },
1796 { "cipher-iterations", 0, 0, G_OPTION_ARG_INT64
, &iterations
,
1797 "cipher iteration count (N+1)", "iterations" },
1798 { "debug-level", 0, 0, G_OPTION_ARG_STRING
, &debug_level_opt
,
1799 "protocol output, see man page", "keywords"},
1800 { "homedir", 'I', 0, G_OPTION_ARG_STRING
, &homedir
,
1801 "home directory for pwmd", "directory" },
1806 #ifdef HAVE_SETRLIMIT
1809 rl
.rlim_cur
= rl
.rlim_max
= 0;
1811 if (setrlimit(RLIMIT_CORE
, &rl
) != 0)
1812 err(EXIT_FAILURE
, "setrlimit()");
1817 setlocale(LC_ALL
, "");
1818 bindtextdomain("pwmd", LOCALEDIR
);
1825 g_mem_set_vtable(&mtable
);
1826 g_thread_init(NULL
);
1833 gnutls_global_set_mem_functions(g_malloc
, g_malloc
, secure_mem_check
,
1835 gnutls_global_init();
1836 gnutls_global_set_log_function(tls_log
);
1837 gnutls_global_set_log_level(1);
1841 xmlMemSetup(g_free
, g_malloc
, g_realloc
, g_strdup
);
1848 context
= g_option_context_new("- Password Manager Daemon");
1849 g_option_context_add_main_entries(context
, options
, NULL
);
1850 if (!g_option_context_parse(context
, &argc
, &argv
, &error
))
1852 g_print("Option parsing failed: %s\n", error
->message
);
1858 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
1860 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
1861 "Compile time features:\n%s"), PACKAGE_STRING
, PACKAGE_BUGREPORT
,
1892 homedir
= g_strdup_printf("%s/.pwmd", g_get_home_dir());
1894 if (mkdir(homedir
, 0700) == -1 && errno
!= EEXIST
)
1895 err(EXIT_FAILURE
, "%s", homedir
);
1897 g_snprintf(buf
, sizeof(buf
), "%s/data", homedir
);
1898 if (mkdir(buf
, 0700) == -1 && errno
!= EEXIST
)
1899 err(EXIT_FAILURE
, "%s", buf
);
1901 datadir
= g_strdup(buf
);
1902 pthread_mutexattr_t attr
;
1903 pthread_mutexattr_init(&attr
);
1904 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
1905 pthread_mutex_init(&rcfile_mutex
, &attr
);
1906 pthread_cond_init(&rcfile_cond
, NULL
);
1907 pthread_mutex_init(&cn_mutex
, &attr
);
1908 pthread_mutexattr_destroy(&attr
);
1909 pthread_key_create(&last_error_key
, free_key
);
1912 rcfile
= g_strdup_printf("%s/config", homedir
);
1916 if ((keyfileh
= parse_rcfile(rcfile_spec
, cmdline
)) == NULL
)
1919 if (debug_level_opt
)
1920 debug_level
= g_strsplit(debug_level_opt
, ",", 0);
1922 if (g_key_file_has_key(keyfileh
, "global", "syslog", NULL
) == TRUE
)
1923 log_syslog
= g_key_file_get_boolean(keyfileh
, "global", "syslog", NULL
);
1925 if (log_syslog
== TRUE
)
1926 openlog("pwmd", LOG_NDELAY
|LOG_PID
, LOG_DAEMON
);
1928 if (g_key_file_has_key(keyfileh
, "global", "priority", NULL
)) {
1929 x
= g_key_file_get_integer(keyfileh
, "global", "priority", NULL
);
1932 if (setpriority(PRIO_PROCESS
, 0, x
) == -1) {
1933 log_write("setpriority(): %s", pwmd_strerror(gpg_error_from_syserror()));
1938 #ifdef HAVE_MLOCKALL
1939 if (disable_mlock
== FALSE
&& mlockall(MCL_CURRENT
|MCL_FUTURE
) == -1) {
1940 log_write("mlockall(): %s", pwmd_strerror(gpg_error_from_syserror()));
1945 rc
= cache_init(free_cache_data
);
1947 log_write("pwmd: gpg-agent: %s",
1948 gpg_err_code(rc
) == GPG_ERR_UNKNOWN_VERSION
1949 ? _("incompatible version: 2.1.0 or later required")
1950 : pwmd_strerror(rc
));
1954 if (s2k_count
== -1)
1955 s2k_count
= get_key_file_ulong(NULL
, "s2k_count");
1959 gchar
*tmp
= g_option_context_get_help(context
, TRUE
, NULL
);
1960 fprintf(stderr
, "%s", tmp
);
1965 estatus
= convert_v2_datafile(convertfile
, cipher
, keyfile
, keygrip
,
1966 sign_keygrip
, no_passphrase
, outfile
, keyparam
,
1967 (gulong
)s2k_count
, iterations
);
1968 g_key_file_free(keyfileh
);
1975 gchar
*tmp
= g_option_context_get_help(context
, TRUE
, NULL
);
1976 fprintf(stderr
, "%s", tmp
);
1981 if (outfile
[0] == '-' && outfile
[1] == 0)
1984 estatus
= xml_import(import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
1985 no_passphrase
, cipher
, keyparam
, (gulong
)s2k_count
, iterations
);
1986 g_key_file_free(keyfileh
);
1991 g_option_context_free(context
);
1992 p
= g_key_file_get_string(keyfileh
, "global", "socket_path", NULL
);
1994 p
= g_strdup_printf("%s/socket", homedir
);
1996 socketarg
= expand_homedir(p
);
1999 if (secure
== FALSE
&& g_key_file_has_key(keyfileh
, "global", "disable_list_and_dump", NULL
) == TRUE
) {
2000 n
= g_key_file_get_boolean(keyfileh
, "global", "disable_list_and_dump", NULL
);
2001 disable_list_and_dump
= n
;
2004 disable_list_and_dump
= secure
;
2006 setup_logging(keyfileh
);
2008 if (g_key_file_has_key(keyfileh
, "global", "cache_push", NULL
) == TRUE
)
2009 cache_push
= g_key_file_get_string_list(keyfileh
, "global", "cache_push", NULL
, NULL
);
2011 for (gint n
= 1; n
< argc
; n
++) {
2012 if (strv_printf(&cache_push
, "%s", argv
[n
]) == FALSE
)
2013 errx(EXIT_FAILURE
, "%s", pwmd_strerror(GPG_ERR_ENOMEM
));
2016 if (strchr(socketarg
, '/') == NULL
) {
2017 socketdir
= g_get_current_dir();
2018 socketname
= g_strdup(socketarg
);
2019 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
2022 socketname
= g_strdup(strrchr(socketarg
, '/'));
2024 socketarg
[strlen(socketarg
) - strlen(socketname
) -1] = 0;
2025 socketdir
= g_strdup(socketarg
);
2026 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
2029 if (chdir(datadir
)) {
2030 log_write("%s: %s", datadir
, pwmd_strerror(gpg_error_from_syserror()));
2036 * Set the cache entry for a file. Prompts for the password.
2039 struct crypto_s
*crypto
;
2040 gpg_error_t rc
= init_client_crypto(&crypto
);
2043 estatus
= EXIT_FAILURE
;
2047 rc
= set_pinentry_options(crypto
->agent
);
2049 estatus
= EXIT_FAILURE
;
2053 for (opt
= 0; cache_push
[opt
]; opt
++) {
2054 if (!do_cache_push(cache_push
[opt
], crypto
) && !force
) {
2055 g_strfreev(cache_push
);
2057 estatus
= EXIT_FAILURE
;
2058 cleanup_crypto(&crypto
);
2062 cleanup_crypto_stage1(crypto
);
2065 (void)kill_scd(crypto
->agent
);
2066 cleanup_crypto(&crypto
);
2067 g_strfreev(cache_push
);
2068 log_write(!nofork
? _("Done. Daemonizing...") : _("Done. Waiting for connections..."));
2071 clear_rcfile_keys();
2074 * bind() doesn't like the full pathname of the socket or any non alphanum
2075 * characters so change to the directory where the socket is wanted then
2076 * create it then change to datadir.
2078 if (chdir(socketdir
)) {
2079 log_write("%s: %s", socketdir
, pwmd_strerror(gpg_error_from_syserror()));
2085 if ((sockfd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) == -1) {
2086 log_write("socket(): %s", pwmd_strerror(gpg_error_from_syserror()));
2090 addr
.sun_family
= AF_UNIX
;
2091 g_snprintf(addr
.sun_path
, sizeof(addr
.sun_path
), "%s", socketname
);
2093 if (bind(sockfd
, (struct sockaddr
*)&addr
, sizeof(struct sockaddr
)) == -1) {
2094 log_write("bind(): %s", pwmd_strerror(gpg_error_from_syserror()));
2096 if (errno
== EADDRINUSE
)
2097 log_write(_("Either there is another pwmd running or '%s' is a \n"
2098 "stale socket. Please remove it manually."), socketpath
);
2104 if (g_key_file_has_key(keyfileh
, "global", "socket_perms", NULL
) == TRUE
) {
2105 gchar
*t
= g_key_file_get_string(keyfileh
, "global", "socket_perms", NULL
);
2106 mode_t mode
= strtol(t
, NULL
, 8);
2107 mode_t mask
= umask(0);
2111 if (chmod(socketname
, mode
) == -1) {
2112 log_write("%s: %s", socketname
, pwmd_strerror(gpg_error_from_syserror()));
2122 g_free(--socketname
);
2124 if (chdir(datadir
)) {
2125 log_write("%s: %s", datadir
, pwmd_strerror(gpg_error_from_syserror()));
2133 if (listen(sockfd
, 0) == -1) {
2134 log_write("listen(): %s", pwmd_strerror(gpg_error_from_syserror()));
2143 log_write("fork(): %s", pwmd_strerror(gpg_error_from_syserror()));
2152 _exit(EXIT_SUCCESS
);
2156 pthread_key_create(&thread_name_key
, free_key
);
2157 pthread_setspecific(thread_name_key
, g_strdup("main"));
2158 estatus
= server_loop(sockfd
, &socketpath
);
2161 if (socketpath
&& do_unlink
) {
2168 gnutls_global_deinit();
2170 pthread_cancel(rcfile_tid
);
2171 pthread_join(rcfile_tid
, NULL
);
2172 pthread_cond_destroy(&rcfile_cond
);
2173 pthread_mutex_destroy(&rcfile_mutex
);
2176 g_key_file_free(keyfileh
);
2180 xmlCleanupGlobals();
2182 if (estatus
== EXIT_SUCCESS
)
2183 log_write(_("pwmd exiting normally"));
2185 #if defined(DEBUG) && !defined(MEM_DEBUG)