2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
30 #include <sys/socket.h>
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
;
144 gboolean tcp_require_key
= get_key_file_boolean("global",
150 pthread_cond_wait(&rcfile_cond
, &rcfile_mutex
);
151 users
= g_key_file_get_string_list(keyfileh
, "global", "allowed", NULL
, NULL
);
152 log_write(_("reloading configuration file '%s'"), rcfile
);
153 k
= parse_rcfile(FALSE
, cmdline
);
155 g_key_file_free(keyfileh
);
157 cache_push_from_rcfile();
161 disable_list_and_dump
= !disable_list_and_dump
? b
: TRUE
;
163 tcp_require_key
= get_key_file_boolean("global", "tcp_require_key")
164 ? TRUE
: tcp_require_key
;
165 g_key_file_set_boolean(keyfileh
, "global", "tcp_require_key",
168 g_key_file_set_string_list(keyfileh
, "global", "allowed",
169 (const gchar
**)users
, g_strv_length(users
));
172 /* Kill existing listening threads since the configured listening
173 * protocols may have changed. */
174 start_stop_tls(TRUE
);
175 start_stop_tls(FALSE
);
179 pthread_cleanup_pop(1);
183 gpg_error_t
send_error(assuan_context_t ctx
, gpg_error_t e
)
185 struct client_s
*client
= assuan_get_pointer(ctx
);
187 if (gpg_err_source(e
) == GPG_ERR_SOURCE_UNKNOWN
)
194 return assuan_process_done(ctx
, 0);
197 log_write("%s", pwmd_strerror(e
));
201 if (gpg_err_code(e
) == GPG_ERR_BAD_DATA
) {
202 xmlErrorPtr xe
= client
->xml_error
;
205 xe
= xmlGetLastError();
207 log_write("%s", xe
->message
);
208 if (client
->last_error
)
209 g_free(client
->last_error
);
211 client
->last_error
= g_strdup(xe
->message
);
214 e
= assuan_process_done(ctx
, assuan_set_error(ctx
, e
,
215 xe
? xe
->message
: NULL
));
217 if (xe
== client
->xml_error
)
222 client
->xml_error
= NULL
;
226 return assuan_process_done(ctx
, assuan_set_error(ctx
, e
, pwmd_strerror(e
)));
229 int assuan_log_cb(assuan_context_t ctx
, void *data
, unsigned cat
,
232 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
234 gboolean match
= FALSE
;
236 pthread_mutex_lock(&m
);
237 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock
, &m
);
238 t
= g_strv_length(debug_level
);
240 for (i
= 0; i
< t
; i
++) {
241 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"init")
242 && cat
== ASSUAN_LOG_INIT
) {
247 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"ctx")
248 && cat
== ASSUAN_LOG_CTX
) {
253 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"engine")
254 && cat
== ASSUAN_LOG_ENGINE
) {
259 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"data")
260 && cat
== ASSUAN_LOG_DATA
) {
265 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"sysio")
266 && cat
== ASSUAN_LOG_SYSIO
) {
271 if (!g_ascii_strcasecmp(debug_level
[i
], (gchar
*)"control")
272 && cat
== ASSUAN_LOG_CONTROL
) {
282 if ((fd
= open(logfile
, O_WRONLY
|O_CREAT
|O_APPEND
, 0600)) == -1)
285 pthread_cleanup_push(cleanup_fd_cb
, &fd
);
286 write(fd
, msg
, strlen(msg
));
287 pthread_cleanup_pop(1);
292 fprintf(stderr
, "%s%s", data
? (gchar
*)data
: "", msg
);
297 pthread_cleanup_pop(1);
301 void log_write(const gchar
*fmt
, ...)
311 pthread_t tid
= pthread_self();
312 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
314 if ((!logfile
&& !isatty(STDERR_FILENO
) && !log_syslog
) || !fmt
)
317 pthread_mutex_lock(&m
);
318 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock
, &m
);
319 pthread_cleanup_push(cleanup_fd_cb
, &fd
);
321 if (!cmdline
&& logfile
) {
322 if ((fd
= open(logfile
, O_WRONLY
|O_CREAT
|O_APPEND
, 0600)) == -1)
328 if (g_vasprintf(&args
, fmt
, ap
) != -1) {
330 pthread_cleanup_push(g_free
, args
);
331 fprintf(stderr
, "%s\n", args
);
333 pthread_cleanup_pop(1);
336 pthread_cleanup_push(g_free
, args
);
337 name
= pthread_getspecific(thread_name_key
);
338 name
= print_fmt(buf
, sizeof(buf
), "%s(%p): ",
339 name
? name
: _("unknown"), (pthread_t
*)tid
);
341 if (!cmdline
&& log_syslog
&& !nofork
)
342 syslog(LOG_INFO
, "%s%s", name
, args
);
345 tm
= localtime(&now
);
346 strftime(tbuf
, sizeof(tbuf
), "%b %d %Y %H:%M:%S ", tm
);
347 tbuf
[sizeof(tbuf
) - 1] = 0;
349 if (args
[strlen(args
)-1] == '\n')
350 args
[strlen(args
)-1] = 0;
352 line
= g_strdup_printf("%s %i %s%s\n", tbuf
, getpid(), name
,
354 pthread_cleanup_pop(1);
356 pthread_cleanup_push(g_free
, line
);
357 if (logfile
&& fd
!= -1) {
358 write(fd
, line
, strlen(line
));
363 fprintf(stdout
, "%s", line
);
367 pthread_cleanup_pop(1);
373 pthread_cleanup_pop(1);
374 pthread_cleanup_pop(0);
375 pthread_mutex_unlock(&m
);
379 static gint
secure_mem_check(const void *arg
)
385 static gpg_error_t
setup_crypto()
387 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
389 if (!gcry_check_version(GCRYPT_VERSION
)) {
390 fprintf(stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
391 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
392 gcry_check_version(NULL
));
393 return GPG_ERR_UNKNOWN_VERSION
;
396 gcry_set_allocation_handler(g_malloc
, g_malloc
, NULL
, g_realloc
, g_free
);
400 static gpg_error_t
validate_peer(struct client_s
*cl
)
403 gboolean allowed
= FALSE
;
404 assuan_peercred_t peercred
;
412 rc
= assuan_get_peercred(cl
->ctx
, &peercred
);
416 users
= g_key_file_get_string_list(keyfileh
, "global", "allowed", NULL
, NULL
);
419 for (gchar
**p
= users
; *p
; p
++) {
420 struct passwd pw
, *result
;
421 struct group gr
, *gresult
;
425 size_t len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
434 return GPG_ERR_ENOMEM
;
437 if (!getgrnam_r(*(p
)+1, &gr
, buf
, len
, &gresult
) && gresult
) {
438 if (gresult
->gr_gid
== peercred
->gid
) {
444 len
= sysconf(_SC_GETPW_R_SIZE_MAX
);
449 gchar
*tbuf
= g_malloc(len
);
451 for (gchar
**t
= gresult
->gr_mem
; *t
; t
++) {
452 if (!getpwnam_r(*t
, &pw
, tbuf
, len
, &result
) && result
) {
453 if (result
->pw_uid
== peercred
->uid
) {
468 size_t len
= sysconf(_SC_GETPW_R_SIZE_MAX
);
477 return GPG_ERR_ENOMEM
;
480 if (!getpwnam_r(*p
, &pw
, buf
, len
, &result
) && result
) {
481 if (result
->pw_uid
== peercred
->uid
) {
495 log_write("peer %s: uid=%i, gid=%i, pid=%i",
496 allowed
? _("accepted") : _("rejected"), peercred
->uid
,
497 peercred
->gid
, peercred
->pid
);
498 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
501 static void xml_error_cb(void *data
, xmlErrorPtr e
)
503 struct client_s
*client
= data
;
506 * Keep the first reported error as the one to show in the error
507 * description. Reset in send_error().
509 if (client
->xml_error
)
512 xmlCopyError(e
, client
->xml_error
);
515 static pid_t
hook_waitpid(assuan_context_t ctx
, pid_t pid
, int action
,
516 int *status
, int options
)
518 return waitpid(pid
, status
, options
);
521 static ssize_t
hook_read(assuan_context_t ctx
, assuan_fd_t fd
, void *data
,
525 struct client_s
*client
= assuan_get_pointer(ctx
);
527 if (client
->thd
->remote
)
528 return tls_read_hook(ctx
, (gint
)fd
, data
, len
);
531 return read((gint
)fd
, data
, len
);
534 static ssize_t
hook_write(assuan_context_t ctx
, assuan_fd_t fd
,
535 const void *data
, size_t len
)
538 struct client_s
*client
= assuan_get_pointer(ctx
);
540 if (client
->thd
->remote
)
541 return tls_write_hook(ctx
, (gint
)fd
, data
, len
);
544 return write((gint
)fd
, data
, len
);
547 static gboolean
new_connection(struct client_s
*cl
)
550 static struct assuan_malloc_hooks mhooks
= { g_malloc
, g_realloc
, g_free
};
551 static struct assuan_system_hooks shooks
= {
552 ASSUAN_SYSTEM_HOOKS_VERSION
,
560 NULL
, //sendmsg both are used for FD passing
569 if (cl
->thd
->remote
) {
570 gchar
*prio
= get_key_file_string("global", "tls_cipher_suite");
572 cl
->thd
->tls
= tls_init(cl
->thd
->fd
, prio
);
579 rc
= assuan_new_ext(&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
580 debug_level
? assuan_log_cb
: NULL
, NULL
);
584 assuan_ctx_set_system_hooks(cl
->ctx
, &shooks
);
585 rc
= assuan_init_socket_server(cl
->ctx
, cl
->thd
->fd
, 2);
589 assuan_set_pointer(cl
->ctx
, cl
);
590 assuan_set_hello_line(cl
->ctx
, PACKAGE_STRING
);
591 rc
= register_commands(cl
->ctx
);
595 rc
= assuan_accept(cl
->ctx
);
599 rc
= validate_peer(cl
);
600 /* May not be implemented on all platforms. */
601 if (rc
&& gpg_err_code(rc
) != GPG_ERR_ASS_GENERAL
)
604 rc
= init_client_crypto(&cl
->crypto
);
608 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
609 cl
->crypto
->client_ctx
= cl
->ctx
;
610 xmlSetStructuredErrorFunc(cl
, xml_error_cb
);
614 log_write("%s", pwmd_strerror(rc
));
619 * This is called after a client_thread() terminates. Set with
620 * pthread_cleanup_push().
622 static void cleanup_cb(void *arg
)
624 struct client_thread_s
*cn
= arg
;
625 struct client_s
*cl
= cn
->cl
;
627 MUTEX_LOCK(&cn_mutex
);
628 cn_thread_list
= g_slist_remove(cn_thread_list
, cn
);
629 MUTEX_UNLOCK(&cn_mutex
);
636 gnutls_deinit(cn
->tls
->ses
);
643 assuan_release(cl
->ctx
);
644 else if (cl
->thd
&& cl
->thd
->fd
!= -1)
648 cleanup_crypto(&cl
->crypto
);
657 while (cn
->msg_queue
) {
658 struct status_msg_s
*msg
= cn
->msg_queue
;
660 cn
->msg_queue
= msg
->next
;
665 if (cn
->status_msg_pipe
[0] != -1)
666 close(cn
->status_msg_pipe
[0]);
668 if (cn
->status_msg_pipe
[1] != -1)
669 close(cn
->status_msg_pipe
[1]);
671 pthread_mutex_destroy(&cn
->status_mutex
);
672 log_write(_("exiting, fd=%i"), cn
->fd
);
674 send_status_all(STATUS_CLIENTS
, NULL
);
675 pthread_cond_signal(&quit_cond
);
678 static gpg_error_t
send_msg_queue(struct client_thread_s
*thd
)
680 MUTEX_LOCK(&thd
->status_mutex
);
684 read(thd
->status_msg_pipe
[0], &c
, 1);
686 while (thd
->msg_queue
) {
687 struct status_msg_s
*msg
= thd
->msg_queue
;
689 thd
->msg_queue
= thd
->msg_queue
->next
;
690 MUTEX_UNLOCK(&thd
->status_mutex
);
691 rc
= send_status(thd
->cl
->ctx
, msg
->s
, msg
->line
);
692 MUTEX_LOCK(&thd
->status_mutex
);
700 MUTEX_UNLOCK(&thd
->status_mutex
);
704 static void *client_thread(void *data
)
706 struct client_thread_s
*thd
= data
;
707 struct client_s
*cl
= g_malloc0(sizeof(struct client_s
));
709 #ifdef HAVE_PR_SET_NAME
710 prctl(PR_SET_NAME
, "client");
712 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
715 log_write("%s(%i): %s", __FILE__
, __LINE__
,
716 pwmd_strerror(GPG_ERR_ENOMEM
));
720 MUTEX_LOCK(&cn_mutex
);
721 pthread_cleanup_push(cleanup_cb
, thd
);
724 MUTEX_UNLOCK(&cn_mutex
);
726 if (new_connection(cl
)) {
727 gboolean finished
= FALSE
;
730 send_status_all(STATUS_CLIENTS
, NULL
);
731 rc
= send_status(cl
->ctx
, STATUS_CACHE
, NULL
);
733 log_write("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror(rc
));
743 FD_SET(thd
->fd
, &rfds
);
744 FD_SET(thd
->status_msg_pipe
[0], &rfds
);
745 n
= thd
->fd
> thd
->status_msg_pipe
[0] ? thd
->fd
: thd
->status_msg_pipe
[0];
747 n
= select(n
+1, &rfds
, NULL
, NULL
, NULL
);
749 log_write("%s", strerror(errno
));
753 if (FD_ISSET(thd
->status_msg_pipe
[0], &rfds
)) {
754 rc
= send_msg_queue(thd
);
755 if (rc
&& gpg_err_code(rc
) != GPG_ERR_EPIPE
) {
756 log_write("%s(%i): %s", __FUNCTION__
, __LINE__
,
762 if (!FD_ISSET(thd
->fd
, &rfds
))
765 rc
= assuan_process_next(cl
->ctx
, &eof
);
767 if (gpg_err_code(rc
) == GPG_ERR_EOF
|| eof
)
770 log_write("assuan_process_next(): %s", pwmd_strerror(rc
));
771 rc
= send_error(cl
->ctx
, rc
);
774 log_write("assuan_process_done(): %s", pwmd_strerror(rc
));
779 /* Since the msg queue pipe fd's are non-blocking, check for
780 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
781 * client has already disconnected and will be converted to
782 * GPG_ERR_EOF during assuan_process_next().
784 rc
= send_msg_queue(thd
);
785 if (rc
&& gpg_err_code(rc
) != GPG_ERR_EPIPE
) {
786 log_write("%s(%i): %s", __FUNCTION__
, __LINE__
,
793 pthread_cleanup_pop(1);
797 static gboolean
xml_import(const gchar
*filename
, const gchar
*outfile
,
798 const gchar
*keygrip
, const char *sign_keygrip
, const gchar
*keyfile
,
799 gboolean no_passphrase
, const gchar
*cipher
, const gchar
*params
,
800 gulong s2k_count
, guint64 iterations
)
809 struct crypto_s
*crypto
;
810 gint algo
= cipher
? cipher_string_to_gcrypt((gchar
*)cipher
) :
814 log_write("ERR %i: %s", gpg_error(GPG_ERR_CIPHER_ALGO
),
815 pwmd_strerror(GPG_ERR_CIPHER_ALGO
));
819 if (stat(filename
, &st
) == -1) {
820 log_write("%s: %s", filename
, pwmd_strerror(gpg_error_from_syserror()));
824 rc
= init_client_crypto(&crypto
);
828 memcpy(&crypto
->save
.hdr
, &crypto
->hdr
, sizeof(file_header_t
));
829 crypto
->save
.hdr
.flags
= set_cipher_flag(crypto
->save
.hdr
.flags
, algo
);
830 log_write(_("Importing XML from '%s'. Output will be written to '%s' ..."),
833 if ((fd
= open(filename
, O_RDONLY
)) == -1) {
834 log_write("%s: %s", filename
, pwmd_strerror(gpg_error_from_syserror()));
838 if ((xmlbuf
= xmalloc(st
.st_size
+1)) == NULL
) {
840 log_write("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror(GPG_ERR_ENOMEM
));
844 if (read(fd
, xmlbuf
, st
.st_size
) == -1) {
845 rc
= gpg_error_from_syserror();
847 log_write("%s: %s", filename
, pwmd_strerror(rc
));
852 xmlbuf
[st
.st_size
] = 0;
854 * Make sure the document validates.
856 if ((doc
= xmlReadDoc(xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
) {
857 log_write("xmlReadDoc() failed");
863 xmlNodePtr n
= xmlDocGetRootElement(doc
);
864 if (!xmlStrEqual(n
->name
, (xmlChar
*)"pwmd")) {
865 log_write(_("Could not find root \"pwmd\" element."));
866 rc
= GPG_ERR_BAD_DATA
;
870 rc
= validate_import(n
? n
->children
: n
);
873 log_write("ERR %i: %s", rc
, pwmd_strerror(rc
));
878 xmlDocDumpMemory(doc
, &xml
, &len
);
880 crypto
->save
.s2k_count
= (gulong
)s2k_count
;
881 crypto
->save
.hdr
.iterations
= iterations
;
882 rc
= set_pinentry_options(crypto
->agent
);
884 rc
= export_common(crypto
, keygrip
, sign_keygrip
, no_passphrase
, xml
,
885 len
, outfile
, params
, keyfile
);
889 send_error(NULL
, rc
);
893 cleanup_crypto(&crypto
);
897 cleanup_crypto(&crypto
);
901 static gboolean
do_cache_push(const gchar
*filename
, struct crypto_s
*crypto
)
908 struct cache_data_s
*cdata
;
912 log_write(_("Trying to add datafile '%s' to the file cache ..."),
915 if (valid_filename(filename
) == FALSE
) {
916 log_write(_("%s: Invalid characters in filename"), filename
);
920 rc
= read_data_file(filename
, crypto
);
922 log_write("ERR %i: %s", rc
, pwmd_strerror(rc
));
926 if ((key
= get_key_file_string(filename
, "passphrase"))) {
927 log_write(_("Trying the passphrase specified in config ..."));
928 keylen
= strlen(key
);
930 else if ((key
= get_key_file_string(filename
, "passphrase_file"))) {
931 gint fd
= open((gchar
*)key
, O_RDONLY
);
934 log_write(_("Trying the passphrase using file '%s' ..."), key
);
936 log_write("%s: %s", key
, pwmd_strerror(gpg_error_from_syserror()));
941 stat((gchar
*)key
, &st
);
943 key
= g_malloc(st
.st_size
);
944 if (read(fd
, key
, st
.st_size
) != st
.st_size
) {
945 log_write("short read() count");
955 rc
= set_agent_passphrase(crypto
, key
, keylen
);
958 log_write("ERR %i: %s", rc
, pwmd_strerror(rc
));
963 crypto
->filename
= g_strdup(filename
);
964 rc
= decrypt_data(NULL
, crypto
);
966 log_write("ERR %i: %s", rc
, pwmd_strerror(rc
));
970 doc
= parse_doc((gchar
*)crypto
->plaintext
, crypto
->plaintext_len
);
972 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM
));
976 gcry_md_hash_buffer(GCRY_MD_MD5
, md5file
, filename
, strlen(filename
));
977 cdata
= g_malloc0(sizeof(struct cache_data_s
));
980 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM
));
984 rc
= get_checksum(filename
, &crc
, &len
);
986 log_write("ERR %i: %s", rc
, pwmd_strerror(rc
));
988 free_cache_data_once(cdata
);
993 rc
= encrypt_xml(NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
994 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
995 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
997 log_write("ERR %i: %s", rc
, pwmd_strerror(rc
));
999 free_cache_data_once(cdata
);
1003 gcry_sexp_build((gcry_sexp_t
*)&cdata
->pubkey
, NULL
, "%S", crypto
->pkey_sexp
);
1004 gcry_sexp_build((gcry_sexp_t
*)&cdata
->sigkey
, NULL
, "%S", crypto
->sigpkey_sexp
);
1005 gint timeout
= get_key_file_integer(filename
, "cache_timeout");
1006 cache_add_file(md5file
, crypto
->grip
, cdata
, timeout
);
1007 log_write(_("Successfully added '%s' to the cache."), filename
);
1011 static gpg_error_t
init_client_thread(gint fd
, const gchar
*addr
)
1014 struct client_thread_s
*new = g_malloc0(sizeof(struct client_thread_s
));
1018 return GPG_ERR_ENOMEM
;
1021 MUTEX_LOCK(&cn_mutex
);
1022 pthread_cleanup_push(cleanup_mutex_cb
, &cn_mutex
);
1024 if (pipe(new->status_msg_pipe
) == -1)
1025 rc
= gpg_error_from_syserror();
1028 fcntl(new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1029 fcntl(new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1030 pthread_mutex_init(&new->status_mutex
, NULL
);
1035 new->remote
= addr
? TRUE
: FALSE
;
1038 rc
= create_thread(client_thread
, new, &new->tid
, TRUE
);
1040 close(new->status_msg_pipe
[0]);
1041 close(new->status_msg_pipe
[1]);
1042 pthread_mutex_destroy(&new->status_mutex
);
1047 GSList
*list
= g_slist_append(cn_thread_list
, new);
1050 cn_thread_list
= list
;
1052 log_write(_("new connection: tid=%p, fd=%i, addr=%s"),
1053 (pthread_t
*)new->tid
, fd
, addr
);
1055 log_write(_("new connection: tid=%p, fd=%i"),
1056 (pthread_t
*)new->tid
, fd
);
1059 rc
= GPG_ERR_ENOMEM
;
1062 pthread_cleanup_pop(1);
1067 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1074 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1075 static void *get_in_addr(struct sockaddr
*sa
)
1077 if (sa
->sa_family
== AF_INET
)
1078 return &(((struct sockaddr_in
*)sa
)->sin_addr
);
1080 return &(((struct sockaddr_in6
*)sa
)->sin6_addr
);
1083 static void *tcp_accept_thread(void *arg
)
1085 gint sockfd
= *(gint
*)arg
;
1087 #ifdef HAVE_PR_SET_NAME
1088 prctl(PR_SET_NAME
, "tcp_accept");
1090 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1093 struct sockaddr_storage raddr
;
1094 socklen_t slen
= sizeof(raddr
);
1098 gchar s
[INET6_ADDRSTRLEN
];
1100 fd
= accept(sockfd
, (struct sockaddr
*)&raddr
, &slen
);
1102 if (errno
== EMFILE
|| errno
== ENFILE
)
1103 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1104 else if (errno
!= EAGAIN
) {
1105 if (!quit
) // probably EBADF
1106 log_write("accept(): %s", strerror(errno
));
1117 inet_ntop(raddr
.ss_family
, get_in_addr((struct sockaddr
*)&raddr
),
1119 (void)init_client_thread(fd
, s
);
1120 t
= get_key_file_string("global", "tcp_wait");
1121 n
= strtol(t
, NULL
, 10);
1127 /* Just in case accept() failed for some reason other than EBADF */
1132 static gboolean
start_stop_tls_with_protocol(gboolean ipv6
, gboolean term
)
1134 struct addrinfo hints
, *servinfo
, *p
;
1135 gint port
= get_key_file_integer("global", "tcp_port");
1139 gint
*fd
= ipv6
? &tls6_fd
: &tls_fd
;
1141 if (term
|| get_key_file_boolean("global", "enable_tcp") == FALSE
) {
1142 if (tls6_fd
!= -1) {
1143 pthread_cancel(tls6_tid
);
1144 pthread_join(tls6_tid
, NULL
);
1145 shutdown(tls6_fd
, SHUT_RDWR
);
1151 pthread_cancel(tls_tid
);
1152 pthread_join(tls_tid
, NULL
);
1153 shutdown(tls_fd
, SHUT_RDWR
);
1158 /* A client may still be connected. */
1159 if (!quit
&& x509_cred
!= NULL
)
1160 tls_deinit_params();
1165 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1168 memset(&hints
, 0, sizeof(hints
));
1169 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1170 hints
.ai_socktype
= SOCK_STREAM
;
1171 hints
.ai_flags
= AI_PASSIVE
;
1173 if ((n
= getaddrinfo(NULL
, print_fmt(buf
, sizeof(buf
), "%i", port
),
1174 &hints
, &servinfo
)) == -1) {
1175 log_write("getaddrinfo(): %s", gai_strerror(n
));
1179 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
) {
1180 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1181 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1184 if ((*fd
= socket(p
->ai_family
, p
->ai_socktype
,
1185 p
->ai_protocol
)) == -1) {
1186 log_write("socket(): %s", strerror(errno
));
1190 if (setsockopt(*fd
, SOL_SOCKET
, SO_REUSEADDR
, &n
,
1191 sizeof(int)) == -1) {
1192 log_write("setsockopt(): %s", strerror(errno
));
1193 freeaddrinfo(servinfo
);
1197 if (bind(*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1) {
1199 log_write("bind(): %s", strerror(errno
));
1207 freeaddrinfo(servinfo
);
1210 log_write("%s", _("could not bind"));
1214 #ifdef HAVE_DECL_SO_BINDTODEVICE
1215 if (g_key_file_has_key(keyfileh
, "global", "tcp_interface", NULL
)) {
1216 gchar
*tmp
= get_key_file_string("global", "tcp_interface");
1218 if (setsockopt(*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
, 1)
1220 log_write("setsockopt(): %s", strerror(errno
));
1229 if (x509_cred
== NULL
) {
1230 rc
= tls_init_params();
1235 if (listen(*fd
, 0) == -1) {
1236 log_write("listen(): %s", strerror(errno
));
1241 rc
= create_thread(tcp_accept_thread
, fd
, &tls6_tid
, FALSE
);
1243 rc
= create_thread(tcp_accept_thread
, fd
, &tls_tid
, FALSE
);
1246 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1254 start_stop_tls_with_protocol(FALSE
, TRUE
);
1266 static gboolean
start_stop_tls(gboolean term
)
1268 gchar
*s
= get_key_file_string("global", "tcp_bind");
1274 if (!g_strcmp0(s
, "any")) {
1275 b
= start_stop_tls_with_protocol(FALSE
, term
);
1277 b
= start_stop_tls_with_protocol(TRUE
, term
);
1279 else if (!g_strcmp0(s
, "ipv4"))
1280 b
= start_stop_tls_with_protocol(FALSE
, term
);
1281 else if (!g_strcmp0(s
, "ipv6"))
1282 b
= start_stop_tls_with_protocol(TRUE
, term
);
1291 static void *accept_thread(void *arg
)
1293 gint sockfd
= *(gint
*)arg
;
1295 #ifdef HAVE_PR_SET_NAME
1296 prctl(PR_SET_NAME
, "accept");
1298 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1301 socklen_t slen
= sizeof(struct sockaddr_un
);
1302 struct sockaddr_un raddr
;
1305 fd
= accept(sockfd
, (struct sockaddr
*)&raddr
, &slen
);
1307 if (errno
== EMFILE
|| errno
== ENFILE
)
1308 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1309 else if (errno
!= EAGAIN
) {
1310 if (!quit
) // probably EBADF
1311 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1318 (void)init_client_thread(fd
, NULL
);
1321 /* Just in case accept() failed for some reason other than EBADF */
1326 static void *cache_timer_thread(void *arg
)
1328 #ifdef HAVE_PR_SET_NAME
1329 prctl(PR_SET_NAME
, "cache timer");
1331 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1335 cache_adjust_timeout();
1341 static void catch_sigabrt(int sig
)
1349 static gboolean
signal_loop(sigset_t sigset
)
1351 gboolean done
= FALSE
;
1352 gboolean sigint
= FALSE
;
1355 gint sig
= sigwaitinfo(&sigset
, NULL
);
1358 if (errno
!= EAGAIN
)
1359 log_write("sigwaitinfo(): %s", strerror(errno
));
1364 log_write(_("caught signal %i (%s)"), sig
, strsignal(sig
));
1368 pthread_cond_signal(&rcfile_cond
);
1371 // not really handled here.
1372 catch_sigabrt(SIGABRT
);
1375 log_write(_("clearing file cache"));
1377 send_status_all(STATUS_CACHE
, NULL
);
1392 static void catchsig(int sig
)
1394 log_write("Caught SIGSEGV. Exiting.");
1395 #ifdef HAVE_BACKTRACE
1396 BACKTRACE(__FUNCTION__
);
1401 static void *waiting_for_exit(void *arg
)
1403 #ifdef HAVE_PR_SET_NAME
1404 prctl(PR_SET_NAME
, "exiting");
1406 pthread_setspecific(thread_name_key
, g_strdup(__FUNCTION__
));
1407 log_write(_("waiting for all clients to disconnect"));
1408 MUTEX_LOCK(&quit_mutex
);
1409 pthread_cleanup_push(cleanup_mutex_cb
, &quit_mutex
);
1412 MUTEX_LOCK(&cn_mutex
);
1413 gint n
= g_slist_length(cn_thread_list
);
1414 MUTEX_UNLOCK(&cn_mutex
);
1418 log_write(_("%i clients remain"), n
);
1419 pthread_cond_wait(&quit_cond
, &quit_mutex
);
1422 pthread_cleanup_pop(1);
1423 kill(getpid(), SIGUSR2
);
1427 static gboolean
server_loop(gint sockfd
, gchar
**socketpath
)
1429 pthread_t accept_tid
;
1430 pthread_t cache_timeout_tid
;
1431 gboolean cancel_timeout_thread
= FALSE
, cancel_accept_thread
= FALSE
;
1434 gboolean segv
= FALSE
;
1438 sigemptyset(&sigset
);
1441 sigaddset(&sigset
, SIGTERM
);
1442 sigaddset(&sigset
, SIGINT
);
1444 /* Clears the file cache. */
1445 sigaddset(&sigset
, SIGUSR1
);
1447 /* Configuration file reloading. */
1448 sigaddset(&sigset
, SIGHUP
);
1450 /* For exiting cleanly. */
1451 sigaddset(&sigset
, SIGUSR2
);
1453 /* Clears the cache and exits when something bad happens. */
1454 signal(SIGABRT
, catch_sigabrt
);
1455 sigaddset(&sigset
, SIGABRT
);
1456 sigprocmask(SIG_BLOCK
, &sigset
, NULL
);
1458 /* Ignored everywhere. When a client disconnects abnormally this signal
1459 * gets raised. It isn't needed though because client_thread() will check
1460 * for rcs even after the client disconnects. */
1461 signal(SIGPIPE
, SIG_IGN
);
1463 /* Can show a backtrace of the stack in the log. */
1464 signal(SIGSEGV
, catchsig
);
1467 /* Needs to be done after the fork(). */
1468 if (!start_stop_tls(FALSE
)) {
1474 pthread_mutex_init(&quit_mutex
, NULL
);
1475 pthread_cond_init(&quit_cond
, NULL
);
1476 log_write(_("%s started for user %s"), PACKAGE_STRING
, g_get_user_name());
1477 #ifndef HAVE_DECL_SO_PEERCRED
1478 log_write(_("Peer credential checking is NOT supported on this OS."));
1481 if (get_key_file_boolean("global", "enable_tcp"))
1482 log_write(_("Listening on %s and TCP port %i"), *socketpath
,
1483 get_key_file_integer("global", "tcp_port"));
1485 log_write(_("Listening on %s"), *socketpath
);
1487 log_write(_("Listening on %s"), *socketpath
);
1490 rc
= create_thread(reload_rcfile_thread
, NULL
, &rcfile_tid
, FALSE
);
1492 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1497 rc
= create_thread(cache_timer_thread
, NULL
, &cache_timeout_tid
, TRUE
);
1499 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1504 cancel_timeout_thread
= TRUE
;
1505 rc
= create_thread(accept_thread
, &sockfd
, &accept_tid
, TRUE
);
1507 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1512 cancel_accept_thread
= TRUE
;
1513 sigdelset(&sigset
, SIGUSR2
);
1515 signal_loop(sigset
);
1521 * We're out of the main server loop. This happens when a signal was sent
1522 * to terminate the daemon. We'll wait for all clients to disconnect
1523 * before exiting but exit immediately if another termination signal is
1526 if (cancel_accept_thread
)
1527 pthread_cancel(accept_tid
);
1529 shutdown(sockfd
, SHUT_RDWR
);
1531 unlink(*socketpath
);
1532 g_free(*socketpath
);
1534 MUTEX_LOCK(&cn_mutex
);
1535 n
= g_slist_length(cn_thread_list
);
1536 MUTEX_UNLOCK(&cn_mutex
);
1541 rc
= create_thread(waiting_for_exit
, NULL
, &tid
, TRUE
);
1543 sigaddset(&sigset
, SIGUSR2
);
1544 if (signal_loop(sigset
)) {
1545 log_write(_("Received second termination request. Exiting."));
1546 pthread_cancel(tid
);
1550 log_write("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1554 if (cancel_timeout_thread
)
1555 pthread_cancel(cache_timeout_tid
);
1557 MUTEX_LOCK(&cn_mutex
);
1559 n
= g_slist_length(cn_thread_list
);
1561 for (i
= 0; i
< n
; i
++) {
1562 struct client_thread_s
*thd
= g_slist_nth_data(cn_thread_list
, i
);
1564 if (thd
->fd
!= -1) {
1571 MUTEX_UNLOCK(&cn_mutex
);
1573 start_stop_tls(TRUE
);
1577 pthread_cond_destroy(&quit_cond
);
1578 pthread_mutex_destroy(&quit_mutex
);
1579 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
1582 static void startup_failure()
1584 log_write(_("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
1588 /* This is called from cache.c:clear_once(). See
1589 * command.c:clearcache_command() for details about lock checking.
1591 static gpg_error_t
free_cache_data(file_cache_t
*cache
)
1593 gpg_error_t rc
= GPG_ERR_NO_DATA
;
1595 struct client_thread_s
*found
= NULL
;
1596 gboolean self
= FALSE
;
1602 MUTEX_LOCK(&cn_mutex
);
1603 pthread_cleanup_push(cleanup_mutex_cb
, &cn_mutex
);
1604 t
= g_slist_length(cn_thread_list
);
1606 for (i
= 0; i
< t
; i
++) {
1607 struct client_thread_s
*thd
= g_slist_nth_data(cn_thread_list
, i
);
1612 if (!memcmp(thd
->cl
->md5file
, cache
->filename
,
1613 sizeof(cache
->filename
))) {
1614 if (pthread_equal(pthread_self(), thd
->tid
)) {
1620 /* Continue trying to find a client who has the same file open and
1621 * also has a lock. */
1622 rc
= cache_lock_mutex(thd
->cl
->ctx
, thd
->cl
->md5file
, -1, FALSE
, -1);
1631 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
1632 rc
= cache_lock_mutex(found
->cl
->ctx
, found
->cl
->md5file
, -1, FALSE
, -1);
1634 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
) {
1635 free_cache_data_once(cache
->data
);
1637 cache
->defer_clear
= FALSE
;
1638 cache
->timeout
= -1;
1641 cache_unlock_mutex(found
->cl
->md5file
, FALSE
);
1647 cache
->defer_clear
= TRUE
;
1649 pthread_cleanup_pop(1);
1654 static gboolean
convert_v2_datafile(const gchar
*filename
, const gchar
*cipher
,
1655 const gchar
*keyfile
, const gchar
*keygrip
, const gchar
*sign_keygrip
,
1656 gboolean nopass
, const gchar
*outfile
, const gchar
*keyparam
,
1657 gulong s2k_count
, guint64 iterations
)
1660 gpointer data
= NULL
;
1662 struct crypto_s
*crypto
= NULL
;
1666 if (outfile
[0] == '-' && outfile
[1] == 0)
1669 log_write(_("Converting version 2 data file \"%s\" ..."), filename
);
1670 if (access(filename
, R_OK
) == -1) {
1671 log_write("%s: %s", filename
, pwmd_strerror(gpg_error_from_syserror()));
1676 log_write(_("Using passphrase file \"%s\" for decryption ..."),
1678 if (access(keyfile
, R_OK
) == -1) {
1679 log_write("%s: %s", keyfile
,
1680 pwmd_strerror(gpg_error_from_syserror()));
1685 rc
= read_v2_datafile(filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
1687 log_write("ERR %i: %s", rc
, pwmd_strerror(rc
));
1692 algo
= cipher_string_to_gcrypt(cipher
);
1694 rc
= GPG_ERR_CIPHER_ALGO
;
1700 xmlDocPtr doc
= parse_doc(data
, datalen
);
1703 rc
= GPG_ERR_BAD_DATA
;
1707 rc
= convert_pre_212_elements(doc
);
1711 xmlDocDumpFormatMemory(doc
, (xmlChar
**)&data
, (gint
*)&datalen
, 0);
1713 rc
= GPG_ERR_ENOMEM
;
1721 rc
= init_client_crypto(&crypto
);
1723 rc
= set_pinentry_options(crypto
->agent
);
1725 memcpy(&crypto
->save
.hdr
, &crypto
->hdr
,
1726 sizeof(file_header_t
));
1727 crypto
->save
.hdr
.flags
= set_cipher_flag(crypto
->save
.hdr
.flags
, algo
);
1728 crypto
->save
.s2k_count
= (gulong
)s2k_count
;
1729 crypto
->save
.hdr
.iterations
= iterations
;
1730 rc
= export_common(crypto
, keygrip
, sign_keygrip
, nopass
, data
,
1731 datalen
, outfile
, keyparam
,
1732 no_passphrase_file
? NULL
: keyfile
);
1734 log_write(_("Output written to \"%s\"."), outfile
);
1743 cleanup_crypto(&crypto
);
1746 log_write("ERR %i: %s", rc
, pwmd_strerror(rc
));
1747 return rc
? FALSE
: TRUE
;
1750 int main(int argc
, char *argv
[])
1753 struct sockaddr_un addr
;
1754 gchar buf
[PATH_MAX
];
1755 gchar
*socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
1756 gchar
*socketarg
= NULL
;
1757 gchar
*datadir
= NULL
;
1761 gchar
**cache_push
= NULL
;
1762 gchar
*import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
1763 gchar
*keyparam
= NULL
;
1764 gboolean rcfile_spec
= FALSE
;
1765 gint estatus
= EXIT_FAILURE
;
1767 gchar
*outfile
= NULL
;
1768 GMemVTable mtable
= { xmalloc
, xrealloc
, xfree
, xcalloc
, NULL
, NULL
};
1770 gboolean secure
= FALSE
;
1771 gint show_version
= 0;
1772 gboolean force
= FALSE
;
1773 gboolean no_passphrase
= FALSE
;
1775 gchar
*convertfile
= NULL
;
1776 gchar
*cipher
= NULL
;
1777 gchar
*keyfile
= NULL
;
1778 glong s2k_count
= -1;
1779 guint64 iterations
= 0;
1780 GError
*error
= NULL
;
1781 gchar
*debug_level_opt
= NULL
;
1782 GOptionContext
*context
;
1783 GOptionEntry options
[] =
1785 { "version", 0, 0, G_OPTION_ARG_NONE
, &show_version
,
1786 "version information", NULL
},
1787 { "no-fork", 'n', 0, G_OPTION_ARG_NONE
, &nofork
,
1788 "run as a foreground process", NULL
},
1789 { "disable-dump", 'D', 0, G_OPTION_ARG_NONE
, &secure
,
1790 "disable the LIST, XPATH and DUMP commands", NULL
},
1791 { "rcfile", 'f', 0, G_OPTION_ARG_FILENAME
, &rcfile
,
1792 "load the specified rcfile (~/.pwmd/config)", "filename" },
1793 { "ignore", 0, 0, G_OPTION_ARG_NONE
, &force
,
1794 "ignore cache failures on startup", NULL
},
1795 { "outfile", 'o', 0, G_OPTION_ARG_FILENAME
, &outfile
,
1796 "output file when importing (- for stdout)", "filename" },
1797 { "convert", 'C', 0, G_OPTION_ARG_FILENAME
, &convertfile
,
1798 "convert a version 2 data file to version 3", "filename" },
1799 { "passphrase-file", 'k', 0, G_OPTION_ARG_FILENAME
, &keyfile
,
1800 "for decryption when converting", "filename" },
1801 { "no-passphrase-file", 0, 0, G_OPTION_ARG_NONE
, &no_passphrase_file
,
1802 "no --passphrase-file after conversion", NULL
},
1803 { "import", 'I', 0, G_OPTION_ARG_FILENAME
, &import
,
1804 "import an XML file", "filename" },
1805 { "keygrip", 0, 0, G_OPTION_ARG_STRING
, &keygrip
,
1806 "the public keygrip to use for encryption", "hexstring"},
1807 { "sign-keygrip", 0, 0, G_OPTION_ARG_STRING
, &sign_keygrip
,
1808 "the keygrip to use for signing of the data", "hexstring"},
1809 { "keyparam", 0, 0, G_OPTION_ARG_STRING
, &keyparam
,
1810 "alternate key parameters to use (RSA-2048)", "s-exp"},
1811 { "no-passphrase", 0, 0, G_OPTION_ARG_NONE
, &no_passphrase
,
1812 "for the imported/converted keypair", NULL
},
1813 { "cipher", 0, 0, G_OPTION_ARG_STRING
, &cipher
,
1814 "encryption cipher, see man page (aes256)", "string" },
1815 { "s2k-count", 0, 0, G_OPTION_ARG_INT64
, &s2k_count
,
1816 "hash iteration count >65536 (calibrated)", "iterations" },
1817 { "cipher-iterations", 0, 0, G_OPTION_ARG_INT64
, &iterations
,
1818 "cipher iteration count (N+1)", "iterations" },
1819 { "debug-level", 0, 0, G_OPTION_ARG_STRING
, &debug_level_opt
,
1820 "protocol output, see man page", "keywords"},
1821 { "homedir", 'I', 0, G_OPTION_ARG_STRING
, &homedir
,
1822 "home directory for pwmd", "directory" },
1827 #ifdef HAVE_SETRLIMIT
1830 rl
.rlim_cur
= rl
.rlim_max
= 0;
1832 if (setrlimit(RLIMIT_CORE
, &rl
) != 0)
1833 err(EXIT_FAILURE
, "setrlimit()");
1838 setlocale(LC_ALL
, "");
1839 bindtextdomain("pwmd", LOCALEDIR
);
1846 g_mem_set_vtable(&mtable
);
1847 g_thread_init(NULL
);
1854 gnutls_global_set_mem_functions(g_malloc
, g_malloc
, secure_mem_check
,
1856 gnutls_global_init();
1857 gnutls_global_set_log_function(tls_log
);
1858 gnutls_global_set_log_level(1);
1862 xmlMemSetup(g_free
, g_malloc
, g_realloc
, g_strdup
);
1869 context
= g_option_context_new("- Password Manager Daemon");
1870 g_option_context_add_main_entries(context
, options
, NULL
);
1871 if (!g_option_context_parse(context
, &argc
, &argv
, &error
))
1873 g_print("Option parsing failed: %s\n", error
->message
);
1879 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
1881 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
1882 "Compile time features:\n%s"), PACKAGE_STRING
, PACKAGE_BUGREPORT
,
1913 homedir
= g_strdup_printf("%s/.pwmd", g_get_home_dir());
1915 if (mkdir(homedir
, 0700) == -1 && errno
!= EEXIST
)
1916 err(EXIT_FAILURE
, "%s", homedir
);
1918 g_snprintf(buf
, sizeof(buf
), "%s/data", homedir
);
1919 if (mkdir(buf
, 0700) == -1 && errno
!= EEXIST
)
1920 err(EXIT_FAILURE
, "%s", buf
);
1922 datadir
= g_strdup(buf
);
1923 pthread_mutexattr_t attr
;
1924 pthread_mutexattr_init(&attr
);
1925 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
1926 pthread_mutex_init(&rcfile_mutex
, &attr
);
1927 pthread_cond_init(&rcfile_cond
, NULL
);
1928 pthread_mutex_init(&cn_mutex
, &attr
);
1929 pthread_mutexattr_destroy(&attr
);
1930 pthread_key_create(&last_error_key
, free_key
);
1933 rcfile
= g_strdup_printf("%s/config", homedir
);
1937 if ((keyfileh
= parse_rcfile(rcfile_spec
, cmdline
)) == NULL
)
1940 if (debug_level_opt
)
1941 debug_level
= g_strsplit(debug_level_opt
, ",", 0);
1943 if (g_key_file_has_key(keyfileh
, "global", "syslog", NULL
) == TRUE
)
1944 log_syslog
= g_key_file_get_boolean(keyfileh
, "global", "syslog", NULL
);
1946 if (log_syslog
== TRUE
)
1947 openlog("pwmd", LOG_NDELAY
|LOG_PID
, LOG_DAEMON
);
1949 if (g_key_file_has_key(keyfileh
, "global", "priority", NULL
)) {
1950 x
= g_key_file_get_integer(keyfileh
, "global", "priority", NULL
);
1953 if (setpriority(PRIO_PROCESS
, 0, x
) == -1) {
1954 log_write("setpriority(): %s", pwmd_strerror(gpg_error_from_syserror()));
1959 #ifdef HAVE_MLOCKALL
1960 if (disable_mlock
== FALSE
&& mlockall(MCL_CURRENT
|MCL_FUTURE
) == -1) {
1961 log_write("mlockall(): %s", pwmd_strerror(gpg_error_from_syserror()));
1966 rc
= cache_init(free_cache_data
);
1968 log_write("pwmd: gpg-agent: ERR %i: %s", rc
,
1969 gpg_err_code(rc
) == GPG_ERR_UNKNOWN_VERSION
1970 ? _("incompatible version: 2.1.0 or later required")
1971 : pwmd_strerror(rc
));
1975 if (s2k_count
== -1)
1976 s2k_count
= get_key_file_ulong(NULL
, "s2k_count");
1980 gchar
*tmp
= g_option_context_get_help(context
, TRUE
, NULL
);
1981 fprintf(stderr
, "%s", tmp
);
1986 estatus
= convert_v2_datafile(convertfile
, cipher
, keyfile
, keygrip
,
1987 sign_keygrip
, no_passphrase
, outfile
, keyparam
,
1988 (gulong
)s2k_count
, iterations
);
1989 g_key_file_free(keyfileh
);
1996 gchar
*tmp
= g_option_context_get_help(context
, TRUE
, NULL
);
1997 fprintf(stderr
, "%s", tmp
);
2002 if (outfile
[0] == '-' && outfile
[1] == 0)
2005 estatus
= xml_import(import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2006 no_passphrase
, cipher
, keyparam
, (gulong
)s2k_count
, iterations
);
2007 g_key_file_free(keyfileh
);
2012 g_option_context_free(context
);
2013 p
= g_key_file_get_string(keyfileh
, "global", "socket_path", NULL
);
2015 p
= g_strdup_printf("%s/socket", homedir
);
2017 socketarg
= expand_homedir(p
);
2020 if (secure
== FALSE
&& g_key_file_has_key(keyfileh
, "global", "disable_list_and_dump", NULL
) == TRUE
) {
2021 n
= g_key_file_get_boolean(keyfileh
, "global", "disable_list_and_dump", NULL
);
2022 disable_list_and_dump
= n
;
2025 disable_list_and_dump
= secure
;
2027 setup_logging(keyfileh
);
2029 if (g_key_file_has_key(keyfileh
, "global", "cache_push", NULL
) == TRUE
)
2030 cache_push
= g_key_file_get_string_list(keyfileh
, "global", "cache_push", NULL
, NULL
);
2032 for (gint n
= 1; n
< argc
; n
++) {
2033 if (strv_printf(&cache_push
, "%s", argv
[n
]) == FALSE
)
2034 errx(EXIT_FAILURE
, "%s", pwmd_strerror(GPG_ERR_ENOMEM
));
2037 if (strchr(socketarg
, '/') == NULL
) {
2038 socketdir
= g_get_current_dir();
2039 socketname
= g_strdup(socketarg
);
2040 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
2043 socketname
= g_strdup(strrchr(socketarg
, '/'));
2045 socketarg
[strlen(socketarg
) - strlen(socketname
) -1] = 0;
2046 socketdir
= g_strdup(socketarg
);
2047 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
2050 if (chdir(datadir
)) {
2051 log_write("%s: %s", datadir
, pwmd_strerror(gpg_error_from_syserror()));
2057 * Set the cache entry for a file. Prompts for the password.
2060 struct crypto_s
*crypto
;
2061 gpg_error_t rc
= init_client_crypto(&crypto
);
2064 estatus
= EXIT_FAILURE
;
2068 rc
= set_pinentry_options(crypto
->agent
);
2070 estatus
= EXIT_FAILURE
;
2074 for (opt
= 0; cache_push
[opt
]; opt
++) {
2075 if (!do_cache_push(cache_push
[opt
], crypto
) && !force
) {
2076 g_strfreev(cache_push
);
2078 estatus
= EXIT_FAILURE
;
2079 cleanup_crypto(&crypto
);
2083 cleanup_crypto_stage1(crypto
);
2086 (void)kill_scd(crypto
->agent
);
2087 cleanup_crypto(&crypto
);
2088 g_strfreev(cache_push
);
2089 log_write(!nofork
? _("Done. Daemonizing...") : _("Done. Waiting for connections..."));
2092 clear_rcfile_keys();
2095 * bind() doesn't like the full pathname of the socket or any non alphanum
2096 * characters so change to the directory where the socket is wanted then
2097 * create it then change to datadir.
2099 if (chdir(socketdir
)) {
2100 log_write("%s: %s", socketdir
, pwmd_strerror(gpg_error_from_syserror()));
2106 if ((sockfd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) == -1) {
2107 log_write("socket(): %s", pwmd_strerror(gpg_error_from_syserror()));
2111 addr
.sun_family
= AF_UNIX
;
2112 g_snprintf(addr
.sun_path
, sizeof(addr
.sun_path
), "%s", socketname
);
2114 if (bind(sockfd
, (struct sockaddr
*)&addr
, sizeof(struct sockaddr
)) == -1) {
2115 log_write("bind(): %s", pwmd_strerror(gpg_error_from_syserror()));
2117 if (errno
== EADDRINUSE
)
2118 log_write(_("Either there is another pwmd running or '%s' is a \n"
2119 "stale socket. Please remove it manually."), socketpath
);
2125 if (g_key_file_has_key(keyfileh
, "global", "socket_perms", NULL
) == TRUE
) {
2126 gchar
*t
= g_key_file_get_string(keyfileh
, "global", "socket_perms", NULL
);
2127 mode_t mode
= strtol(t
, NULL
, 8);
2128 mode_t mask
= umask(0);
2132 if (chmod(socketname
, mode
) == -1) {
2133 log_write("%s: %s", socketname
, pwmd_strerror(gpg_error_from_syserror()));
2143 g_free(--socketname
);
2145 if (chdir(datadir
)) {
2146 log_write("%s: %s", datadir
, pwmd_strerror(gpg_error_from_syserror()));
2154 if (listen(sockfd
, 0) == -1) {
2155 log_write("listen(): %s", pwmd_strerror(gpg_error_from_syserror()));
2164 log_write("fork(): %s", pwmd_strerror(gpg_error_from_syserror()));
2173 _exit(EXIT_SUCCESS
);
2177 pthread_key_create(&thread_name_key
, free_key
);
2178 pthread_setspecific(thread_name_key
, g_strdup("main"));
2179 estatus
= server_loop(sockfd
, &socketpath
);
2182 if (socketpath
&& do_unlink
) {
2189 gnutls_global_deinit();
2191 pthread_cancel(rcfile_tid
);
2192 pthread_join(rcfile_tid
, NULL
);
2193 pthread_cond_destroy(&rcfile_cond
);
2194 pthread_mutex_destroy(&rcfile_mutex
);
2197 g_key_file_free(keyfileh
);
2201 xmlCleanupGlobals();
2203 if (estatus
== EXIT_SUCCESS
)
2204 log_write(_("pwmd exiting normally"));
2207 #if defined(DEBUG) && !defined(MEM_DEBUG)