LS: Sort files.
[pwmd.git] / src / pwmd.c
blob5eb2d37520d1d3bc037e3aa21fcafc23232d3a92
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016, 2017
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/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <sys/socket.h>
32 #include <sys/un.h>
33 #include <signal.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <sys/wait.h>
37 #include <fcntl.h>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <pthread.h>
41 #include <sys/mman.h>
42 #include <termios.h>
43 #include <assert.h>
44 #include <syslog.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 #include <sys/time.h>
49 #include <sys/resource.h>
50 #include <setjmp.h>
51 #include <errno.h>
52 #include <poll.h>
54 #ifdef TM_IN_SYS_TIME
55 #include <sys/time.h>
56 #else
57 #include <time.h>
58 #endif
60 #ifdef HAVE_LIMITS_H
61 #include <limits.h>
62 #endif
64 #ifdef HAVE_GETOPT_LONG
65 #ifdef HAVE_GETOPT_H
66 #include <getopt.h>
67 #endif
68 #else
69 #include "getopt_long.h"
70 #endif
72 #ifdef HAVE_PR_SET_NAME
73 #include <sys/prctl.h>
74 #endif
76 #include "pwmd-error.h"
77 #include <gcrypt.h>
79 #include "util-misc.h"
80 #include "mem.h"
81 #include "xml.h"
82 #include "common.h"
83 #include "commands.h"
84 #include "cache.h"
85 #include "util-string.h"
86 #include "mutex.h"
87 #include "rcfile.h"
88 #include "crypto.h"
89 #include "acl.h"
91 static int quit;
92 static int cmdline;
93 static jmp_buf jmp;
94 static int nofork;
95 static int log_fd;
96 static unsigned assuan_level;
98 #ifndef HAVE_PTHREAD_CANCEL
99 #define INIT_SIGNAL(s, cb) do { \
100 int *n = xmalloc (sizeof (int)); \
101 *n = 0; \
102 pthread_setspecific (signal_thread_key, n); \
103 struct sigaction act; \
104 sigset_t sigset; \
105 sigemptyset (&sigset); \
106 sigaddset (&sigset, s); \
107 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
108 memset (&act, 0, sizeof(act)); \
109 act.sa_flags = SA_SIGINFO; \
110 act.sa_mask = sigset; \
111 act.sa_sigaction = cb; \
112 sigaction (s, &act, NULL); \
113 } while (0)
115 static void
116 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
118 int *n = (int *) pthread_getspecific (signal_thread_key);
120 *n = 1;
122 #endif
124 static void
125 setup_logging ()
127 int n = config_get_boolean ("global", "enable_logging");
129 if (n)
131 char *p = config_get_string ("global", "log_path");
133 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
135 if (log_fd != -1)
136 close (log_fd);
138 log_fd = -1;
141 xfree (logfile);
142 logfile = NULL;
143 if (p)
144 logfile = expand_homedir (p);
145 xfree (p);
147 else
149 xfree (logfile);
150 logfile = NULL;
151 if (log_fd != -1)
152 close(log_fd);
154 log_fd = -1;
155 closelog ();
158 log_syslog = config_get_boolean ("global", "syslog");
159 if (log_syslog == 1)
160 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
163 static void *
164 reload_rcfile_thread (void *arg)
166 #ifndef HAVE_PTHREAD_CANCEL
167 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
168 #endif
170 #ifdef HAVE_PR_SET_NAME
171 prctl (PR_SET_NAME, "reload rcfile");
172 #endif
173 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
174 MUTEX_LOCK (&rcfile_mutex);
176 (void)arg;
178 for (;;)
180 struct slist_s *keep = NULL;
181 struct slist_s *config;
182 int b = disable_list_and_dump;
183 #ifdef WITH_GNUTLS
184 char *prio;
185 char *prio2 = NULL;
186 #endif
188 pthread_cleanup_push (release_mutex_cb, &rcfile_mutex);
189 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
190 TEST_CANCEL ();
191 keep = config_keep_save ();
192 log_write (_("reloading configuration file '%s'"), rcfile);
194 #ifdef WITH_GNUTLS
195 prio = config_get_string ("global", "tls_cipher_suite");
196 #endif
197 config = config_parse (rcfile, 1);
198 if (config)
200 config_free (global_config);
201 global_config = config;
202 setup_logging ();
205 config_keep_restore (keep);
206 disable_list_and_dump = !disable_list_and_dump ? b : 1;
208 #ifdef WITH_GNUTLS
209 /* Restart listening sockets since they may have changed. */
210 tls_start_stop (1);
211 tls_start_stop (0);
213 prio2 = config_get_string ("global", "tls_cipher_suite");
214 if ((prio2 && (!prio || strcmp (prio, prio2))) || (prio && !prio2))
215 tls_rehandshake ();
217 xfree (prio2);
218 xfree (prio);
219 #endif
220 crypto_set_keepalive ();
221 pthread_cleanup_pop (0);
224 MUTEX_UNLOCK (&rcfile_mutex);
225 return NULL;
228 gpg_error_t
229 send_error (assuan_context_t ctx, gpg_error_t e)
231 struct client_s *client = assuan_get_pointer (ctx);
233 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
234 e = gpg_error (e);
236 if (client)
237 client->last_rc = e;
239 if (!e)
240 return assuan_process_done (ctx, 0);
242 if (!ctx)
244 log_write ("ERR %i: %s", e, pwmd_strerror (e));
245 return e;
248 if (client && client->xml_error)
250 log_write ("%s", client->xml_error->message);
251 xfree (client->last_error);
252 client->last_error = NULL;
253 if (client->xml_error->message)
254 client->last_error = str_dup (client->xml_error->message);
256 e = assuan_process_done (ctx,
257 assuan_set_error (ctx, e,
258 client->xml_error->message ? client->xml_error->message : NULL));
259 xmlResetLastError ();
260 xmlResetError (client->xml_error);
261 xfree (client->xml_error);
262 client->xml_error = NULL;
263 return e;
266 return assuan_process_done (ctx,
267 assuan_set_error (ctx, e, pwmd_strerror (e)));
270 void
271 log_write (const char *fmt, ...)
273 char *args;
274 va_list ap;
275 time_t now;
276 char buf[255];
277 pthread_t tid = pthread_self ();
278 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
280 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
281 return;
283 MUTEX_LOCK (&m);
284 pthread_cleanup_push (release_mutex_cb, &m);
286 if (!cmdline && logfile && log_fd == -1)
288 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
289 if (log_fd == -1)
290 warn ("%s", logfile);
293 va_start (ap, fmt);
295 if (str_vasprintf (&args, fmt, ap) != -1)
297 pthread_cleanup_push (xfree, args);
298 if (cmdline)
300 fprintf (stderr, "pwmd: %s\n", args);
301 fflush (stderr);
303 else
305 char *name = pthread_getspecific (thread_name_key);
306 char *line;
308 if (name)
310 if (*name == '!')
311 snprintf (buf, sizeof (buf), "%s: ", name+1);
312 else
313 snprintf (buf, sizeof (buf), "%s(%p): ", name,
314 (pthread_t *)tid);
316 else
317 snprintf (buf, sizeof (buf), "%p: ", (pthread_t *)tid);
319 name = buf;
320 if (!cmdline && log_syslog && !nofork)
321 syslog (LOG_INFO, "%s%s", name, args);
323 time (&now);
324 struct tm *tm = localtime (&now);
325 char tbuf[21];
326 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
327 tbuf[sizeof (tbuf) - 1] = 0;
329 if (args[strlen (args) - 1] == '\n')
330 args[strlen (args) - 1] = 0;
332 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name, args);
333 if (line)
335 pthread_cleanup_push (xfree, line);
336 if (logfile && log_fd != -1)
338 ssize_t ret = write (log_fd, line, strlen (line));
339 (void)ret;
340 fsync (log_fd);
343 if (nofork)
345 fprintf (stdout, "%s", line);
346 fflush (stdout);
349 pthread_cleanup_pop (1);
352 pthread_cleanup_pop (1);
355 va_end (ap);
357 if (log_fd != -1 && log_keepopen <= 0)
359 close(log_fd);
360 log_fd = -1;
363 pthread_cleanup_pop (1);
366 static gpg_error_t
367 setup_crypto ()
369 gpg_error_t rc;
371 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
373 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
374 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
375 gpgrt_check_version (NULL));
376 return GPG_ERR_UNKNOWN_VERSION;
379 gpgrt_init ();
380 //gpgrt_set_alloc_func (xrealloc_gpgrt);
382 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
384 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
385 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
386 assuan_check_version (NULL));
387 return GPG_ERR_UNKNOWN_VERSION;
390 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
392 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
393 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
394 gcry_check_version (NULL));
395 return GPG_ERR_UNKNOWN_VERSION;
398 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
400 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
402 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
403 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
404 gpgme_check_version (NULL));
405 return GPG_ERR_UNKNOWN_VERSION;
408 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
409 if (rc)
411 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
412 return GPG_ERR_UNKNOWN_VERSION;
415 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
416 #ifdef ENABLE_NLS
417 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
418 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
419 #endif
421 #ifdef WITH_GNUTLS
422 if (gnutls_global_init ())
424 fprintf(stderr, _("gnutls_global_init() failed.\n"));
425 return GPG_ERR_UNKNOWN_VERSION;
428 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION))
430 fprintf (stderr, _("gnutls_check_version(): Incompatible libgnutls. "
431 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION,
432 gnutls_check_version (NULL));
433 return GPG_ERR_UNKNOWN_VERSION;
436 gnutls_global_set_log_function (tls_log);
437 gnutls_global_set_audit_log_function (tls_audit_log);
438 #endif
439 return 0;
442 static void
443 xml_error_cb (void *data, xmlErrorPtr e)
445 struct client_s *client = data;
448 * Keep the first reported error as the one to show in the error
449 * description. Reset in send_error().
451 if (client->xml_error)
452 return;
454 client->xml_error = xcalloc (1, sizeof(xmlError));
455 xmlCopyError (e, client->xml_error);
458 static pid_t
459 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
460 int *status, int options)
462 (void)ctx;
463 (void)action;
464 return waitpid (pid, status, options);
467 static ssize_t
468 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
470 TEST_CANCEL ();
471 #ifdef WITH_GNUTLS
472 struct client_s *client = assuan_get_pointer (ctx);
474 if (client->thd->remote)
475 return tls_read_hook (ctx, (int) fd, data, len);
476 #else
477 (void)ctx;
478 #endif
480 return read ((int) fd, data, len);
483 static ssize_t
484 hook_write (assuan_context_t ctx, assuan_fd_t fd,
485 const void *data, size_t len)
487 TEST_CANCEL ();
488 #ifdef WITH_GNUTLS
489 struct client_s *client = assuan_get_pointer (ctx);
491 if (client->thd->remote)
492 return tls_write_hook (ctx, (int) fd, data, len);
493 #else
494 (void)ctx;
495 #endif
497 return write ((int) fd, data, len);
501 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
502 const char *msg)
504 struct client_s *client = data;
505 const char *str = NULL;
507 (void)client;
508 (void)ctx;
510 if (!(assuan_level & cat))
511 return 0;
513 if (!msg)
514 return 1;
516 switch (cat)
518 case ASSUAN_LOG_INIT:
519 str = "ASSUAN[INIT]";
520 break;
521 case ASSUAN_LOG_CTX:
522 str = "ASSUAN[CTX]";
523 break;
524 case ASSUAN_LOG_ENGINE:
525 str = "ASSUAN[ENGINE]";
526 break;
527 case ASSUAN_LOG_DATA:
528 str = "ASSUAN[DATA]";
529 break;
530 case ASSUAN_LOG_SYSIO:
531 str = "ASSUAN[SYSIO]";
532 break;
533 case ASSUAN_LOG_CONTROL:
534 str = "ASSUAN[CONTROL]";
535 break;
536 default:
537 str = "ASSUAN[UNKNOWN]";
538 break;
541 log_write ("%s: %s", str, msg);
542 return 1;
545 static int
546 new_connection (struct client_s *cl)
548 gpg_error_t rc;
549 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
550 static struct assuan_system_hooks shooks = {
551 ASSUAN_SYSTEM_HOOKS_VERSION,
552 __assuan_usleep,
553 __assuan_pipe,
554 __assuan_close,
555 hook_read,
556 hook_write,
557 //FIXME
558 NULL, //recvmsg
559 NULL, //sendmsg both are used for FD passing
560 __assuan_spawn,
561 hook_waitpid,
562 __assuan_socketpair,
563 __assuan_socket,
564 __assuan_connect
567 #ifdef WITH_GNUTLS
568 if (cl->thd->remote)
570 char *prio = config_get_string ("global", "tls_cipher_suite");
572 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
573 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
574 return 0;
576 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
577 xfree (prio);
578 if (!cl->thd->tls)
579 return 0;
581 #endif
583 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
584 assuan_log_cb, cl);
585 if (rc)
586 goto fail;
588 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
589 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
590 if (rc)
591 goto fail;
593 assuan_set_pointer (cl->ctx, cl);
594 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
595 rc = register_commands (cl->ctx);
596 if (rc)
597 goto fail;
599 rc = assuan_accept (cl->ctx);
600 if (rc)
601 goto fail;
603 rc = validate_peer (cl);
604 /* May not be implemented on all platforms. */
605 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
606 goto fail;
608 MUTEX_LOCK (&cn_mutex);
609 cl->thd->state = CLIENT_STATE_INIT;
610 MUTEX_UNLOCK (&cn_mutex);
611 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
612 xmlSetStructuredErrorFunc (cl, xml_error_cb);
613 return 1;
615 fail:
616 log_write ("%s", pwmd_strerror (rc));
617 return 0;
621 * This is called after a client is cancelled or disconnects. Set with
622 * pthread_cleanup_push().
624 static void
625 free_client_cb (void *arg)
627 struct client_thread_s *cn = arg;
628 struct client_s *cl = cn->cl;
629 char *tmp = NULL;
631 #ifndef HAVE_PTHREAD_CANCEL
632 tmp = pthread_getspecific (signal_thread_key);
633 xfree (tmp);
634 pthread_setspecific (signal_thread_key, NULL);
635 #endif
637 MUTEX_LOCK (&cn_mutex);
638 cn_thread_list = slist_remove (cn_thread_list, cn);
639 MUTEX_UNLOCK (&cn_mutex);
641 if (cl)
643 unlock_flock (&cl->flock_fd);
644 reset_client (cl);
645 if (cl->xml_error)
646 xmlResetError (cl->xml_error);
648 xfree (cl->xml_error);
650 #ifdef WITH_GNUTLS
651 if (cn->tls)
653 gnutls_deinit (cn->tls->ses);
654 xfree (cn->tls->fp);
655 xfree (cn->tls);
657 #endif
659 if (cl->ctx)
660 assuan_release (cl->ctx);
661 else if (cl->thd && cl->thd->fd != -1)
662 close (cl->thd->fd);
664 if (cl->crypto)
665 crypto_free (cl->crypto);
667 cl->crypto = NULL;
668 xfree (cl);
670 else
672 if (cn->fd != -1)
673 close (cn->fd);
676 while (cn->msg_queue)
678 struct status_msg_s *msg = cn->msg_queue;
680 cn->msg_queue = msg->next;
681 xfree (msg->line);
682 xfree (msg);
685 if (cn->status_msg_pipe[0] != -1)
686 close (cn->status_msg_pipe[0]);
688 if (cn->status_msg_pipe[1] != -1)
689 close (cn->status_msg_pipe[1]);
691 pthread_mutex_destroy (&cn->status_mutex);
692 log_write (_("exiting, fd=%i"), cn->fd);
693 send_status_all (STATUS_CLIENTS, NULL);
695 xfree (cn->name);
696 #ifdef WITH_GNUTLS
697 xfree (cn->peeraddr);
698 #endif
700 if (cn->eof) // Not pthread_exit()
702 tmp = pthread_getspecific (thread_name_key);
703 xfree (tmp);
704 pthread_setspecific (thread_name_key, NULL);
707 xfree (cn);
710 static void
711 free_all_clients ()
713 MUTEX_LOCK (&cn_mutex);
714 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
716 while (slist_length (cn_thread_list))
718 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
720 free_client_cb (thd);
721 thd->eof = 1;
724 pthread_cleanup_pop (1);
727 static gpg_error_t
728 send_msg_queue (struct client_thread_s *thd)
730 MUTEX_LOCK (&thd->status_mutex);
731 gpg_error_t rc = 0;
732 char c;
733 ssize_t ret;
735 ret = read (thd->status_msg_pipe[0], &c, 1);
736 rc = gpg_error_from_syserror ();
737 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
738 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
739 else
740 rc = 0;
742 thd->wrote_status = 0;
744 while (thd->msg_queue)
746 struct status_msg_s *msg = thd->msg_queue;
748 thd->msg_queue = thd->msg_queue->next;
749 MUTEX_UNLOCK (&thd->status_mutex);
750 pthread_cleanup_push (xfree, msg);
751 pthread_cleanup_push (xfree, msg->line);
752 rc = send_status (thd->cl->ctx, msg->s, msg->line);
753 pthread_cleanup_pop (1);
754 pthread_cleanup_pop (1);
755 MUTEX_LOCK (&thd->status_mutex);
756 if (rc)
757 break;
760 MUTEX_UNLOCK (&thd->status_mutex);
761 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
762 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
764 return rc;
767 static void *
768 client_thread (void *data)
770 struct client_thread_s *thd = data;
771 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
772 struct slist_s *list;
773 gpg_error_t rc = 0;
774 #ifndef HAVE_PTHREAD_CANCEL
775 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
776 #endif
778 #ifdef HAVE_PR_SET_NAME
779 prctl (PR_SET_NAME, "client");
780 #endif
781 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
783 if (!cl)
785 log_write ("%s(%i): %s", __FILE__, __LINE__,
786 pwmd_strerror (GPG_ERR_ENOMEM));
787 return NULL;
790 MUTEX_LOCK (&cn_mutex);
791 pthread_cleanup_push (free_client_cb, thd);
792 thd->cl = cl;
793 cl->thd = thd;
794 cl->flock_fd = -1;
796 list = slist_append (cn_thread_list, thd);
797 if (list)
798 cn_thread_list = list;
799 else
801 log_write ("%s(%i): %s", __FILE__, __LINE__,
802 pwmd_strerror (GPG_ERR_ENOMEM));
803 MUTEX_UNLOCK (&cn_mutex);
804 return NULL;
807 if (fcntl (thd->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
808 rc = gpg_error_from_errno (errno);
810 if (!rc)
811 if (fcntl (thd->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
812 rc = gpg_error_from_errno (errno);
814 MUTEX_UNLOCK (&cn_mutex);
816 if (rc)
818 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
819 return NULL;
822 if (new_connection (cl))
824 int finished = 0;
825 struct pollfd fds[2];
827 fds[0].fd = thd->fd;
828 fds[0].events = POLLIN;
829 fds[1].fd = thd->status_msg_pipe[0];
830 fds[1].events = POLLIN;
832 send_status_all (STATUS_CLIENTS, NULL);
833 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
834 if (rc)
836 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
837 finished = 1;
840 while (!finished)
842 int n;
843 int eof;
845 n = poll (fds, 2, 100);
846 if (n == -1)
848 log_write ("%s", strerror (errno));
849 break;
852 #ifdef WITH_GNUTLS
853 if (thd->remote && thd->tls && thd->tls->rehandshake)
855 char *prio;
856 int ret;
857 const char *e;
859 if (thd->tls->rehandshake == 1)
861 prio = config_get_string ("global", "tls_cipher_suite");
862 if (!prio)
864 thd->tls->rehandshake = 0;
865 continue;
868 ret = gnutls_priority_set_direct (thd->tls->ses, prio, &e);
869 if (ret == GNUTLS_E_SUCCESS)
871 rc = send_status (cl->ctx, STATUS_REHANDSHAKE, NULL);
872 if (!rc)
874 rc = assuan_send_data (cl->ctx, NULL, 0);
875 if (!rc)
877 ret = gnutls_rehandshake (thd->tls->ses);
878 if (ret)
880 log_write ("%s", gnutls_strerror (ret));
881 thd->tls->rehandshake = 0;
883 else
884 thd->tls->rehandshake = 2;
888 if (rc)
889 log_write ("%s", pwmd_strerror (rc));
891 else
892 log_write ("%s: %s", gnutls_strerror (ret), e);
894 xfree (prio);
895 continue;
898 #endif
900 if (!n)
901 continue;
903 if (fds[1].revents & POLLIN)
905 #ifdef WITH_GNUTLS
906 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
907 #endif
909 rc = send_msg_queue (thd);
910 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
911 break;
915 #ifdef HAVE_PTHREAD_CANCEL
916 if (!(fds[0].revents & POLLIN))
917 #else
918 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
919 #endif
920 continue;
922 rc = assuan_process_next (cl->ctx, &eof);
923 if (rc || eof)
925 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
926 break;
928 log_write ("assuan_process_next(): rc=%u %s", rc,
929 pwmd_strerror (rc));
930 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
931 break;
933 rc = send_error (cl->ctx, rc);
934 if (rc)
936 log_write ("assuan_process_done(): rc=%u %s", rc,
937 pwmd_strerror (rc));
938 break;
942 /* Since the msg queue pipe fd's are non-blocking, check for
943 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
944 * client has already disconnected and will be converted to
945 * GPG_ERR_EOF during assuan_process_next().
947 #ifdef WITH_GNUTLS
948 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
949 #endif
951 rc = send_msg_queue (thd);
952 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
953 break;
958 /* Don't do pthread_exit() here because any set pthread_cleanup_push
959 * functions would be called after a command failed but then the client
960 * exited normally which may lead to a double free. */
961 thd->eof = 1;
962 pthread_cleanup_pop (1);
963 return NULL;
966 static gpg_error_t
967 xml_import (const char *filename, const char *outfile, char **keyid,
968 char *sign_keyid, char *keyfile, const char *userid,
969 const char *algo, long expire, int no_passphrase, int symmetric)
971 xmlDocPtr doc;
972 int fd;
973 struct stat st;
974 int len;
975 xmlChar *xmlbuf = NULL;
976 gpg_error_t rc = 0;
977 struct crypto_s *crypto = NULL;
979 if (strcmp (filename, "-"))
981 rc = open_check_file (filename, &fd, &st, 0);
982 if (rc)
983 return rc;
985 xmlbuf = xmalloc (st.st_size + 1);
986 if (!xmlbuf)
988 close (fd);
989 return GPG_ERR_ENOMEM;
992 if (read (fd, xmlbuf, st.st_size) == -1)
994 rc = gpg_error_from_errno (errno);
995 close (fd);
996 xfree (xmlbuf);
997 return rc;
1000 xmlbuf[st.st_size] = 0;
1001 close (fd);
1003 else
1005 #define BUFSIZE 8196
1006 size_t size = 0, xlen = 0;
1008 for (;;)
1010 size_t ret;
1011 xmlChar *tmp;
1013 tmp = xrealloc (xmlbuf, size+BUFSIZE+1);
1014 if (!tmp)
1016 xfree (xmlbuf);
1017 return GPG_ERR_ENOMEM;
1020 xmlbuf = tmp;
1021 size += BUFSIZE;
1022 ret = read (STDIN_FILENO, &xmlbuf[xlen], BUFSIZE);
1023 if (ret == -1)
1025 rc = gpg_error_from_syserror ();
1026 xfree (xmlbuf);
1027 return rc;
1030 xlen += ret;
1031 if (!ret || ret < BUFSIZE)
1032 break;
1035 xmlbuf[xlen] = 0;
1038 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1039 xfree (xmlbuf);
1040 if (!doc)
1041 return GPG_ERR_BAD_DATA;
1043 xmlNodePtr n = xmlDocGetRootElement (doc);
1044 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1045 rc = GPG_ERR_BAD_DATA;
1047 if (!rc)
1049 rc = xml_validate_import (NULL, n ? n->children : n);
1050 if (!rc)
1052 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1053 if (!rc)
1055 if (keyfile)
1057 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1058 crypto->keyfile = str_dup (keyfile);
1061 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1062 if (len > 0)
1063 crypto->plaintext_size = len;
1064 else
1065 rc = GPG_ERR_ENOMEM;
1070 if (!rc)
1072 if (!symmetric && !keyid)
1074 crypto->save.userid = str_dup (userid);
1075 crypto->save.algo = algo ? str_dup (algo) : NULL;
1076 crypto->save.expire = expire;
1077 if (no_passphrase)
1078 crypto->save.flags |= GPGME_CREATE_NOPASSWD;
1080 rc = crypto_genkey (NULL, crypto);
1082 else
1084 if (keyid)
1085 crypto->save.pubkey = strv_dup (keyid);
1087 if (sign_keyid)
1088 crypto->save.sigkey = str_dup (sign_keyid);
1091 if (!rc)
1093 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1094 rc = crypto_encrypt (NULL, crypto);
1098 if (!rc)
1100 if (!strcmp (outfile, "-"))
1101 outfile = NULL;
1103 xfree (crypto->plaintext);
1104 crypto->plaintext = NULL;
1105 xfree (crypto->filename);
1106 crypto->filename = outfile ? str_dup (outfile) : NULL;
1107 rc = crypto_write_file (crypto, NULL, NULL);
1110 xmlFreeDoc (doc);
1111 crypto_free (crypto);
1112 return rc;
1115 static gpg_error_t
1116 do_cache_push (struct crypto_s *crypto)
1118 gpg_error_t rc;
1119 xmlDocPtr doc;
1120 struct cache_data_s *cdata;
1121 unsigned char *crc;
1122 size_t len;
1123 int fd = -1;
1125 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1126 crypto->filename);
1128 if (valid_filename (crypto->filename) == 0)
1130 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1131 return GPG_ERR_INV_VALUE;
1134 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1135 if (!rc)
1136 rc = crypto_decrypt (NULL, crypto);
1137 if (rc)
1139 unlock_flock (&fd);
1140 return rc;
1143 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1144 if (rc)
1146 unlock_flock (&fd);
1147 log_write ("%s", pwmd_strerror (rc));
1148 return rc;
1151 cdata = xcalloc (1, sizeof (struct cache_data_s));
1152 if (!cdata)
1154 unlock_flock (&fd);
1155 xmlFreeDoc (doc);
1156 return GPG_ERR_ENOMEM;
1159 rc = get_checksum (crypto->filename, &crc, &len);
1160 unlock_flock (&fd);
1161 if (rc)
1163 xmlFreeDoc (doc);
1164 cache_free_data_once (cdata);
1165 return rc;
1168 cdata->crc = crc;
1169 rc = cache_encrypt (crypto);
1170 if (!rc)
1172 cdata->doc = crypto->plaintext;
1173 cdata->size = crypto->plaintext_size;
1174 crypto->plaintext = NULL;
1175 cdata->pubkey = crypto->pubkey;
1176 cdata->sigkey = crypto->sigkey;
1177 crypto->pubkey = NULL;
1178 crypto->sigkey = NULL;
1180 else
1182 xmlFreeDoc (doc);
1183 cache_free_data_once (cdata);
1184 return rc;
1187 long timeout = config_get_long (crypto->filename, "cache_timeout");
1188 rc = cache_add_file (crypto->filename, cdata, timeout);
1189 return rc;
1192 static gpg_error_t
1193 init_client (int fd, const char *addr)
1195 gpg_error_t rc = 0;
1196 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1198 if (!new)
1200 close (fd);
1201 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1202 return GPG_ERR_ENOMEM;
1205 MUTEX_LOCK (&cn_mutex);
1206 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1207 new->conntime = time (NULL);
1209 if (pipe (new->status_msg_pipe) == -1)
1210 rc = gpg_error_from_errno (errno);
1211 else
1212 pthread_mutex_init (&new->status_mutex, NULL);
1214 if (!rc)
1216 #ifdef WITH_GNUTLS
1217 new->remote = addr ? 1 : 0;
1218 if (addr)
1219 new->peeraddr = str_dup (addr);
1220 #endif
1221 new->fd = fd;
1222 rc = create_thread (client_thread, new, &new->tid, 1);
1223 if (rc)
1225 close (new->status_msg_pipe[0]);
1226 close (new->status_msg_pipe[1]);
1227 pthread_mutex_destroy (&new->status_mutex);
1231 if (!rc)
1233 if (addr)
1234 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1235 (pthread_t *) new->tid, fd, addr);
1236 else
1237 log_write (_("new connection: tid=%p, fd=%i"),
1238 (pthread_t *) new->tid, fd);
1241 pthread_cleanup_pop (1);
1243 if (rc)
1245 xfree (new);
1246 close (fd);
1247 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1249 return rc;
1252 #ifdef WITH_GNUTLS
1253 static gpg_error_t
1254 do_tls_accept (struct pollfd *fds)
1256 struct sockaddr_storage raddr;
1257 socklen_t slen = sizeof (raddr);
1258 int fd;
1259 char s[INET6_ADDRSTRLEN];
1261 if (!(fds->revents & POLLIN))
1262 return 0;
1264 memset (&raddr, 0, sizeof (raddr));
1265 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1266 if (fd == -1)
1268 int e = errno;
1270 if (errno != EAGAIN && !quit)
1271 log_write ("%s: %s", __FUNCTION__,
1272 pwmd_strerror (gpg_error_from_syserror()));
1274 return gpg_error_from_errno (e);
1277 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1278 sizeof s);
1279 (void) init_client (fd, s);
1280 return 0;
1282 #endif
1284 static void *
1285 accept_thread (void *arg)
1287 int sockfd = *(int *) arg;
1288 #ifndef HAVE_PTHREAD_CANCEL
1289 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1290 #endif
1292 #ifdef HAVE_PR_SET_NAME
1293 prctl (PR_SET_NAME, "accept");
1294 #endif
1295 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1297 for (;;)
1299 socklen_t slen = sizeof (struct sockaddr_un);
1300 struct sockaddr_un raddr;
1301 int fd, s = 0;
1302 struct pollfd fds[3];
1304 TEST_CANCEL ();
1305 memset (fds, 0, sizeof (fds));
1306 fds[s].fd = sockfd;
1307 fds[s++].events = POLLIN;
1309 #ifdef WITH_GNUTLS
1310 if (tls_fd != -1)
1312 fds[s].fd = tls_fd;
1313 fds[s++].events = POLLIN;
1315 else
1316 fds[s].fd = tls_fd;
1318 if (tls6_fd != -1)
1320 fds[s].fd = tls6_fd;
1321 fds[s++].events = POLLIN;
1323 else
1324 fds[s].fd = tls6_fd;
1325 #endif
1327 s = poll (fds, s, 500);
1328 if (s == -1)
1330 if (errno != EINTR)
1331 log_write ("%s", strerror (errno));
1332 break;
1334 else if (s == 0)
1335 continue;
1337 if (fds[0].revents & POLLIN)
1339 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1340 if (fd == -1)
1342 if (errno == EMFILE || errno == ENFILE)
1343 log_write ("%s: %s", __FUNCTION__,
1344 pwmd_strerror (gpg_error_from_errno (errno)));
1345 else if (errno != EAGAIN && errno != EINTR)
1347 if (!quit) // probably EBADF
1348 log_write ("%s: %s", __FUNCTION__,
1349 pwmd_strerror (gpg_error_from_errno (errno)));
1351 break;
1354 continue;
1357 (void) init_client (fd, NULL);
1360 #ifdef WITH_GNUTLS
1361 if (tls_fd != -1 && fds[1].fd == tls_fd)
1362 (void)do_tls_accept (&fds[1]);
1364 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1365 (void)do_tls_accept (&fds[1]);
1367 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1368 (void)do_tls_accept (&fds[2]);
1369 #endif
1372 /* Just in case accept() failed for some reason other than EBADF */
1373 quit = 1;
1374 return NULL;
1377 static void *
1378 cache_timer_thread (void *arg)
1380 unsigned k = 0;
1381 #ifndef HAVE_PTHREAD_CANCEL
1382 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1383 #endif
1385 (void)arg;
1387 #ifdef HAVE_PR_SET_NAME
1388 prctl (PR_SET_NAME, "timer");
1389 #endif
1390 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1392 for (;;)
1394 struct timeval tv = { 1, 0 };
1395 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1397 TEST_CANCEL ();
1398 select (0, NULL, NULL, NULL, &tv);
1399 cache_adjust_timeout ();
1401 if (keepalive && ++k >= keepalive)
1403 send_status_all (STATUS_KEEPALIVE, NULL);
1404 k = 0;
1408 return NULL;
1411 static int
1412 signal_loop (sigset_t sigset)
1414 int done = 0;
1418 int sig;
1420 sigwait (&sigset, &sig);
1421 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1423 switch (sig)
1425 case SIGHUP:
1426 pthread_cond_signal (&rcfile_cond);
1427 break;
1428 case SIGUSR1:
1429 log_write (_("clearing file cache"));
1430 cache_clear (NULL, NULL, 1, 0);
1431 send_status_all (STATUS_CACHE, NULL);
1432 break;
1433 default:
1434 done = 1;
1435 break;
1438 while (!done);
1440 return done;
1443 static void
1444 catchsig (int sig)
1446 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1447 #ifdef HAVE_BACKTRACE
1448 BACKTRACE (__FUNCTION__);
1449 #endif
1450 longjmp (jmp, 1);
1453 static void
1454 cancel_all_clients ()
1456 unsigned i, t;
1458 MUTEX_LOCK (&cn_mutex);
1459 t = slist_length (cn_thread_list);
1460 for (i = 0; i < t; i++)
1462 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
1464 #ifdef HAVE_PTHREAD_CANCEL
1465 pthread_cancel (thd->tid);
1466 #else
1467 pthread_kill (thd->tid, SIGUSR2);
1468 #endif
1471 while (slist_length (cn_thread_list))
1473 MUTEX_UNLOCK (&cn_mutex);
1474 usleep (50000);
1475 MUTEX_LOCK (&cn_mutex);
1478 MUTEX_UNLOCK (&cn_mutex);
1481 static int
1482 server_loop (int sockfd, char **socketpath)
1484 pthread_t cache_timeout_tid;
1485 pthread_t accept_tid;
1486 int cancel_timeout_thread = 0;
1487 int cancel_accept_thread = 0;
1488 int cancel_rcfile_thread = 0;
1489 sigset_t sigset;
1490 int n;
1491 int segv = 0;
1492 gpg_error_t rc;
1494 init_commands ();
1495 sigemptyset (&sigset);
1497 /* Termination */
1498 sigaddset (&sigset, SIGTERM);
1499 sigaddset (&sigset, SIGINT);
1501 /* Clears the file cache. */
1502 sigaddset (&sigset, SIGUSR1);
1504 /* Configuration file reloading. */
1505 sigaddset (&sigset, SIGHUP);
1507 #ifndef HAVE_PTHREAD_CANCEL
1509 The socket, cache and rcfile threads use this signal when
1510 pthread_cancel() is unavailable. Prevent the main thread from
1511 catching this signal from another process.
1513 sigaddset (&sigset, SIGUSR2);
1514 #endif
1516 /* An assertion failure. */
1517 signal (SIGABRT, catchsig);
1518 sigaddset (&sigset, SIGABRT);
1519 sigprocmask (SIG_BLOCK, &sigset, NULL);
1521 #ifndef HAVE_PTHREAD_CANCEL
1522 /* Remove this signal from the watched signals in signal_loop(). */
1523 sigdelset (&sigset, SIGUSR2);
1524 #endif
1526 /* Can show a backtrace of the stack in the log. */
1527 signal (SIGSEGV, catchsig);
1529 char *p = get_username (getuid());
1530 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
1531 xfree (p);
1533 #ifdef WITH_GNUTLS
1534 if (config_get_boolean ("global", "enable_tcp"))
1535 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1536 config_get_integer ("global", "tcp_port"));
1537 else
1538 log_write (_("Listening on %s"), *socketpath);
1539 #else
1540 log_write (_("Listening on %s"), *socketpath);
1541 #endif
1543 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1544 if (rc)
1546 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1547 pwmd_strerror (rc));
1548 goto done;
1551 cancel_rcfile_thread = 1;
1552 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1553 if (rc)
1555 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1556 pwmd_strerror (rc));
1557 goto done;
1560 cancel_timeout_thread = 1;
1561 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
1562 if (rc)
1564 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1565 pwmd_strerror (rc));
1566 goto done;
1569 cancel_accept_thread = 1;
1570 if (!setjmp (jmp))
1571 signal_loop (sigset);
1572 else
1573 segv = 1;
1575 done:
1577 * We're out of the main server loop. This happens when a signal was sent
1578 * to terminate the daemon. Cancel all clients and exit.
1580 if (cancel_accept_thread)
1582 #ifdef HAVE_PTHREAD_CANCEL
1583 n = pthread_cancel (accept_tid);
1584 #else
1585 n = pthread_kill (accept_tid, SIGUSR2);
1586 #endif
1587 if (!n)
1588 pthread_join (accept_tid, NULL);
1591 if (cancel_timeout_thread)
1593 #ifdef HAVE_PTHREAD_CANCEL
1594 n = pthread_cancel (cache_timeout_tid);
1595 #else
1596 n = pthread_kill (cache_timeout_tid, SIGUSR2);
1597 #endif
1598 if (!n)
1599 pthread_join (cache_timeout_tid, NULL);
1602 #ifdef WITH_GNUTLS
1603 tls_start_stop (1);
1604 #endif
1605 shutdown (sockfd, SHUT_RDWR);
1606 close (sockfd);
1607 unlink (*socketpath);
1608 xfree (*socketpath);
1609 *socketpath = NULL;
1610 MUTEX_LOCK (&cn_mutex);
1611 n = slist_length (cn_thread_list);
1612 MUTEX_UNLOCK (&cn_mutex);
1614 if (n && !segv)
1615 cancel_all_clients ();
1616 else
1617 free_all_clients ();
1619 if (cancel_rcfile_thread)
1621 #ifdef HAVE_PTHREAD_CANCEL
1622 pthread_cancel (rcfile_tid);
1623 #else
1624 pthread_kill (rcfile_tid, SIGUSR2);
1625 pthread_cond_signal (&rcfile_cond);
1626 #endif
1627 pthread_join (rcfile_tid, NULL);
1630 cache_deinit ();
1631 deinit_commands ();
1632 return segv ? EXIT_FAILURE : EXIT_SUCCESS;
1635 static void
1636 usage (const char *pn, int status)
1638 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
1640 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
1641 " --homedir alternate pwmd home directory (~/.pwmd)\n"
1642 " -f, --rcfile=filename load the specfied configuration file\n"
1643 " (~/.pwmd/config)\n"
1644 " --kill terminate an existing instance of pwmd\n"
1645 " -n, --no-fork run as a foreground process\n"
1646 " --disable-dump disable the LIST, XPATH and DUMP commands\n"
1647 " --ignore, --force ignore cache pushing errors during startup\n"
1648 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
1649 " -k, --passphrase-file=file for use when importing\n"
1650 " -o, --outfile=filename output file when importing\n"
1651 " --keyid=fpr[,..] public key to use when encrypting\n"
1652 " --sign-keyid=fpr fingerprint of the signing key to use\n"
1653 " -s, --symmetric use conventional encryption with optional signer\n"
1654 " --userid=string name and email address to use when importing\n"
1655 " --algo=string algorithm to use when importing (engine default)\n"
1656 " --expire=seconds key expiry time when importing (3 years)\n"
1657 " --no-passphrase don't require a passphrase when importing\n"
1658 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
1659 " --help this help text\n"
1660 " --version show version and compile time features\n"),
1661 pn);
1662 exit (status);
1665 static void
1666 unlink_stale_socket (const char *sock, const char *pidfile)
1668 log_write (_ ("removing stale socket %s"), sock);
1669 unlink (sock);
1670 unlink (pidfile);
1673 static int
1674 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
1675 char **pidfile, int create, mode_t mode, int terminate)
1677 pid_t pid;
1678 int fd;
1679 size_t len;
1681 if (!create)
1683 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
1684 *pidfile = str_dup (buf);
1685 fd = open (buf, O_RDONLY);
1687 else
1688 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
1690 if (fd == -1)
1692 if (!create && errno != ENOENT)
1694 log_write ("%s: %s", buf, pwmd_strerror (errno));
1695 xfree (*pidfile);
1696 *pidfile = NULL;
1697 return -1;
1699 else if (!create && !terminate)
1700 return 0;
1702 log_write ("%s: %s", *pidfile, strerror (errno));
1703 return -1;
1706 if (create)
1708 snprintf (buf, buflen, "%i", getpid ());
1709 ssize_t ret = write (fd, buf, strlen (buf));
1710 if (ret == -1)
1711 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
1712 pwmd_strerror (gpg_error_from_syserror ()));
1713 close (fd);
1714 return 0;
1717 len = read (fd, buf, buflen);
1718 close (fd);
1719 if (len == 0)
1721 unlink_stale_socket (path, *pidfile);
1722 return 0;
1725 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
1727 if (!terminate)
1729 unlink_stale_socket (path, *pidfile);
1730 return 0;
1734 if (kill (pid, 0) == -1)
1736 unlink_stale_socket (path, *pidfile);
1737 return 0;
1740 if (terminate)
1742 if (kill (pid, SIGTERM) == -1)
1743 log_write ("%s: %s", path, pwmd_strerror (errno));
1745 else
1746 log_write (_ ("an instance for socket %s is already running"), path);
1748 xfree (*pidfile);
1749 *pidfile = NULL;
1750 return 1;
1753 static unsigned
1754 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
1756 const char *p;
1757 unsigned level = 0;
1758 int gl = 0, tl = 0;
1760 for (p = str; p && *p; p++)
1762 if (*p == 'a') // assuan debug flags
1764 if (*++p != ':')
1765 return 1;
1767 while (*++p)
1769 switch (*p)
1771 case 'i':
1772 level |= ASSUAN_LOG_INIT;
1773 break;
1774 case 'x':
1775 level |= ASSUAN_LOG_CTX;
1776 break;
1777 case 'e':
1778 level |= ASSUAN_LOG_ENGINE;
1779 break;
1780 case 'd':
1781 level |= ASSUAN_LOG_DATA;
1782 break;
1783 case 's':
1784 level |= ASSUAN_LOG_SYSIO;
1785 break;
1786 case 'c':
1787 level |= ASSUAN_LOG_CONTROL;
1788 break;
1789 case ',':
1790 break;
1791 default:
1792 return 1;
1795 if (*p == ',')
1796 break;
1799 if (!*p)
1800 break;
1802 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
1804 int t = *p == 't';
1805 int n;
1807 if (*++p != ':')
1808 return 1;
1810 if (!isdigit (*++p))
1811 return 1;
1813 n = atoi (p);
1814 if (t)
1815 tl = n;
1816 else
1817 gl = n;
1819 if (tl < 0 || gl < 0 || gl > 9)
1820 return 1;
1822 while (isdigit (*p))
1823 p++;
1825 p--;
1826 if (*(p+1) && *(p+1) != ',')
1827 return 1;
1828 else if (*(p+1))
1829 p++;
1831 else
1832 return 1;
1835 if (tl)
1836 *tls = tl;
1838 if (gl)
1839 *gpgme = gl;
1841 *debug = level;
1842 return 0;
1846 main (int argc, char *argv[])
1848 int opt;
1849 struct sockaddr_un addr;
1850 char buf[PATH_MAX];
1851 char *socketpath = NULL, *socketdir, *socketname = NULL;
1852 char *socketarg = NULL;
1853 char *datadir = NULL;
1854 char *pidfile = NULL;
1855 mode_t mode = 0600;
1856 int x;
1857 char *p;
1858 char **cache_push = NULL;
1859 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
1860 char *userid = NULL;
1861 char *algo = NULL;
1862 long expire = 0;
1863 int no_passphrase = 0;
1864 int estatus = EXIT_FAILURE;
1865 int sockfd;
1866 char *outfile = NULL;
1867 int do_unlink = 0;
1868 int secure = 0;
1869 int show_version = 0;
1870 int force = 0;
1871 gpg_error_t rc;
1872 char *keyfile = NULL;
1873 int exists;
1874 int optindex;
1875 int terminate = 0;
1876 int sym = 0;
1877 int gpgme_level = -1;
1878 int tls_level = -1;
1879 int backlog = 0;
1880 /* Must maintain the same order as longopts[] */
1881 enum
1883 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
1884 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
1885 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_USERID, OPT_ALGO, OPT_EXPIRE,
1886 OPT_NOPASSPHRASE, OPT_KILL, OPT_DEBUG
1888 const char *optstring = "nf:C:k:I:o:s";
1889 const struct option longopts[] = {
1890 {"version", no_argument, 0, 0},
1891 {"help", no_argument, 0, 0},
1892 {"homedir", required_argument, 0, 0},
1893 {"no-fork", no_argument, 0, 'n'},
1894 {"disable_dump", no_argument, 0, 0},
1895 {"force", no_argument, 0, 0},
1896 {"rcfile", required_argument, 0, 'f'},
1897 {"passphrase-file", required_argument, 0, 'k'},
1898 {"import", required_argument, 0, 'I'},
1899 {"outfile", required_argument, 0, 'o'},
1900 {"keyid", required_argument, 0, 0},
1901 {"sign-keyid", required_argument, 0, 0},
1902 {"symmetric", no_argument, 0, 's'},
1903 {"userid", required_argument, 0, 0},
1904 {"algo", required_argument, 0, 0},
1905 {"expire", required_argument, 0, 0},
1906 {"no-passphrase", no_argument, 0, 0},
1907 {"kill", no_argument, 0, 0},
1908 {"debug", required_argument, 0, 0},
1909 {0, 0, 0, 0}
1912 log_fd = -1;
1913 cmdline = 1;
1914 expire = time (NULL) + DEFAULT_EXPIRE;
1916 #ifndef DEBUG
1917 #ifdef HAVE_SETRLIMIT
1918 struct rlimit rl;
1920 rl.rlim_cur = rl.rlim_max = 0;
1922 if (setrlimit (RLIMIT_CORE, &rl) != 0)
1923 err (EXIT_FAILURE, "setrlimit()");
1924 #endif
1926 #ifdef HAVE_PR_SET_DUMPABLE
1927 prctl (PR_SET_DUMPABLE, 0);
1928 #endif
1929 #endif
1931 #ifdef ENABLE_NLS
1932 setlocale (LC_ALL, "");
1933 bindtextdomain ("pwmd", LOCALEDIR);
1934 textdomain ("pwmd");
1935 #endif
1937 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
1938 != -1)
1940 switch (opt)
1942 case 'I':
1943 import = optarg;
1944 break;
1945 case 'k':
1946 keyfile = optarg;
1947 break;
1948 case 'o':
1949 outfile = optarg;
1950 break;
1951 case 'n':
1952 nofork = 1;
1953 break;
1954 case 'f':
1955 rcfile = str_dup (optarg);
1956 break;
1957 case 's':
1958 sym = 1;
1959 break;
1960 default:
1961 usage (argv[0], EXIT_FAILURE);
1962 break;
1963 case 0:
1964 switch (optindex)
1966 case OPT_DEBUG:
1967 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
1968 &tls_level))
1969 usage (argv[0], EXIT_FAILURE);
1970 break;
1971 case OPT_SYMMETRIC:
1972 sym = 1;
1973 break;
1974 case OPT_VERSION:
1975 show_version = 1;
1976 break;
1977 case OPT_HELP:
1978 usage (argv[0], EXIT_SUCCESS);
1979 break;
1980 case OPT_HOMEDIR:
1981 homedir = str_dup (optarg);
1982 break;
1983 case OPT_NO_FORK:
1984 nofork = 1;
1985 break;
1986 case OPT_DISABLE_DUMP:
1987 secure = 1;
1988 break;
1989 case OPT_FORCE:
1990 force = 1;
1991 break;
1992 case OPT_RCFILE:
1993 rcfile = str_dup (optarg);
1994 break;
1995 case OPT_PASSPHRASE_FILE:
1996 keyfile = optarg;
1997 break;
1998 case OPT_IMPORT:
1999 import = optarg;
2000 break;
2001 case OPT_OUTFILE:
2002 outfile = optarg;
2003 break;
2004 case OPT_KEYID:
2005 keyid = optarg;
2006 break;
2007 case OPT_SIGN_KEYID:
2008 sign_keyid = optarg;
2009 break;
2010 case OPT_USERID:
2011 userid = optarg;
2012 break;
2013 case OPT_ALGO:
2014 algo = optarg;
2015 break;
2016 case OPT_EXPIRE:
2017 errno = rc = 0;
2018 expire = strtoul (optarg, &p, 10);
2020 if (!errno && p && *p)
2021 rc = GPG_ERR_INV_VALUE;
2022 else if (expire == ULONG_MAX)
2023 rc = GPG_ERR_INV_VALUE;
2024 else if (errno)
2025 rc = gpg_error_from_syserror ();
2027 if (rc)
2028 usage (argv[0], EXIT_FAILURE);
2029 break;
2030 case OPT_NOPASSPHRASE:
2031 no_passphrase = 1;
2032 break;
2033 case OPT_KILL:
2034 terminate = 1;
2035 break;
2036 default:
2037 usage (argv[0], EXIT_FAILURE);
2042 if (show_version)
2044 printf (_("%s\n\n"
2045 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017\n"
2046 "%s\n"
2047 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2048 "Compile time features:\n%s"), PACKAGE_STRING,
2049 PACKAGE_BUGREPORT,
2050 #ifdef PWMD_HOMEDIR
2051 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2052 #endif
2053 #ifdef WITH_GNUTLS
2054 "+WITH_GNUTLS\n"
2055 #else
2056 "-WITH_GNUTLS\n"
2057 #endif
2058 #ifdef WITH_LIBACL
2059 "+WITH_LIBACL\n"
2060 #else
2061 "-WITH_LIBACL\n"
2062 #endif
2063 #ifdef DEBUG
2064 "+DEBUG\n"
2065 #else
2066 "-DEBUG\n"
2067 #endif
2068 #ifdef MEM_DEBUG
2069 "+MEM_DEBUG\n"
2070 #else
2071 "-MEM_DEBUG\n"
2072 #endif
2073 #ifdef MUTEX_DEBUG
2074 "+MUTEX_DEBUG\n"
2075 #else
2076 "-MUTEX_DEBUG\n"
2077 #endif
2079 exit (EXIT_SUCCESS);
2082 if (gpgme_level != -1)
2084 char s[2] = { gpgme_level + '0', 0 };
2086 if (getenv ("GPGME_DEBUG"))
2087 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2088 gpgme_level);
2090 gpgme_set_global_flag ("debug", s);
2093 if (setup_crypto ())
2094 exit (EXIT_FAILURE);
2096 #ifdef WITH_GNUTLS
2097 tls_level = tls_level == -1 ? 1 : tls_level;
2098 gnutls_global_set_log_level (tls_level);
2099 tls_fd = -1;
2100 tls6_fd = -1;
2101 #endif
2102 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2103 xmlInitMemory ();
2104 xmlInitGlobals ();
2105 xmlInitParser ();
2106 xmlXPathInit ();
2108 if (!homedir)
2109 #ifdef PWMD_HOMEDIR
2110 homedir = str_dup(PWMD_HOMEDIR);
2111 #else
2112 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2113 #endif
2115 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2116 err (EXIT_FAILURE, "%s", homedir);
2118 if (!rcfile)
2119 rcfile = str_asprintf ("%s/config", homedir);
2121 pthread_key_create (&last_error_key, free_key);
2122 #ifndef HAVE_PTHREAD_CANCEL
2123 pthread_key_create (&signal_thread_key, free_key);
2124 #endif
2126 pthread_mutexattr_t attr;
2127 pthread_mutexattr_init (&attr);
2128 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2129 pthread_mutex_init (&rcfile_mutex, &attr);
2130 global_config = config_parse (rcfile, 0);
2131 if (!global_config)
2133 pthread_mutexattr_destroy (&attr);
2134 pthread_mutex_destroy (&rcfile_mutex);
2135 exit (EXIT_FAILURE);
2138 p = config_get_string ("global", "gpg_homedir");
2139 if (!p)
2140 datadir = str_asprintf ("%s/.gnupg", homedir);
2141 else
2142 datadir = expand_homedir (p);
2144 xfree (p);
2145 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2146 err (EXIT_FAILURE, "%s", datadir);
2148 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2149 if (rc)
2150 errx (EXIT_FAILURE, "%s: %s", datadir, pwmd_strerror (rc));
2151 xfree (datadir);
2153 snprintf (buf, sizeof (buf), "%s/data", homedir);
2154 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2155 err (EXIT_FAILURE, "%s", buf);
2157 datadir = str_dup (buf);
2158 pthread_cond_init (&rcfile_cond, NULL);
2159 pthread_mutex_init (&cn_mutex, &attr);
2160 pthread_mutexattr_destroy (&attr);
2162 setup_logging ();
2164 x = config_get_int_param (global_config, "global", "priority", &exists);
2165 if (exists && x != atoi(INVALID_PRIORITY))
2167 errno = 0;
2168 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2170 log_write ("setpriority(): %s",
2171 pwmd_strerror (gpg_error_from_errno (errno)));
2172 goto do_exit;
2175 #ifdef HAVE_MLOCKALL
2176 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2178 log_write ("mlockall(): %s",
2179 pwmd_strerror (gpg_error_from_errno (errno)));
2180 goto do_exit;
2182 #endif
2184 rc = cache_init ();
2185 if (rc)
2187 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2188 exit (EXIT_FAILURE);
2191 if (import)
2193 char **keyids = NULL;
2195 if (!outfile || !*outfile || argc != optind)
2196 usage (argv[0], EXIT_FAILURE);
2198 if (keyid)
2199 keyids = str_split (keyid, ",", 0);
2200 else if (!userid && !sym)
2201 usage (argv[0], EXIT_FAILURE);
2203 rc = xml_import (import, outfile, keyids, sign_keyid, keyfile, userid,
2204 algo, expire, no_passphrase, sym);
2205 strv_free (keyids);
2206 if (rc)
2208 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2209 rc = gpg_error (rc);
2211 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2214 config_free (global_config);
2215 xfree (rcfile);
2216 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2219 p = config_get_string ("global", "socket_path");
2220 if (!p)
2221 p = str_asprintf ("%s/socket", homedir);
2223 socketarg = expand_homedir (p);
2224 xfree (p);
2226 if (!secure)
2227 disable_list_and_dump = config_get_boolean ("global",
2228 "disable_list_and_dump");
2229 else
2230 disable_list_and_dump = secure;
2232 cache_push = config_get_list ("global", "cache_push");
2234 while (optind < argc)
2236 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2237 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2240 if (!strchr (socketarg, '/'))
2242 socketdir = getcwd (buf, sizeof (buf));
2243 socketname = str_dup (socketarg);
2244 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2246 else
2248 socketname = str_dup (strrchr (socketarg, '/')+1);
2249 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2250 socketdir = str_dup (socketarg);
2251 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2254 if (chdir (datadir))
2256 log_write ("%s: %s", datadir,
2257 pwmd_strerror (gpg_error_from_errno (errno)));
2258 unlink (socketpath);
2259 goto do_exit;
2262 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2263 mode, terminate);
2264 if (!terminate && x)
2265 goto do_exit;
2266 else if (terminate)
2268 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2269 goto do_exit;
2273 * bind() doesn't like the full pathname of the socket or any non alphanum
2274 * characters so change to the directory where the socket is wanted then
2275 * create it then change to datadir.
2277 if (chdir (socketdir))
2279 log_write ("%s: %s", socketdir,
2280 pwmd_strerror (gpg_error_from_errno (errno)));
2281 goto do_exit;
2284 xfree (socketdir);
2286 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2288 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2289 goto do_exit;
2292 addr.sun_family = AF_UNIX;
2293 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2294 do_unlink = 1;
2295 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2298 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2300 if (errno == EADDRINUSE)
2302 do_unlink = 0;
2303 log_write (_("Either there is another pwmd running or '%s' is a \n"
2304 "stale socket. Please remove it manually."), socketpath);
2307 goto do_exit;
2311 char *t = config_get_string ("global", "socket_perms");
2312 mode_t mask;
2314 if (t)
2316 mode = strtol (t, NULL, 8);
2317 mask = umask (0);
2318 xfree (t);
2320 if (chmod (socketname, mode) == -1)
2322 log_write ("%s: %s", socketname,
2323 pwmd_strerror (gpg_error_from_errno (errno)));
2324 close (sockfd);
2325 umask (mask);
2326 goto do_exit;
2329 umask (mask);
2333 if (chdir (datadir))
2335 log_write ("%s: %s", datadir,
2336 pwmd_strerror (gpg_error_from_errno (errno)));
2337 close (sockfd);
2338 goto do_exit;
2341 xfree (datadir);
2342 #ifdef WITH_GNUTLS
2343 if (config_get_boolean ("global", "enable_tcp"))
2345 if (!tls_start_stop (0))
2347 close (sockfd);
2348 goto do_exit;
2351 #endif
2354 * Set the cache entry for a file. Prompts for the password.
2356 if (cache_push)
2358 for (opt = 0; cache_push[opt]; opt++)
2360 struct crypto_s *crypto = NULL;
2361 char *pw_file = config_get_string (cache_push[opt],
2362 "passphrase_file");
2363 rc = crypto_init (&crypto, NULL, cache_push[opt], pw_file != NULL,
2364 pw_file);
2366 if (!rc)
2368 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2369 crypto->keyfile = pw_file;
2371 else
2372 xfree (pw_file);
2374 if (rc)
2376 estatus = EXIT_FAILURE;
2377 goto do_exit;
2380 rc = do_cache_push (crypto);
2381 if (rc && !force)
2383 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2384 strv_free (cache_push);
2385 log_write (_ ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2386 cache_clear (NULL, NULL, 1, 0);
2387 estatus = EXIT_FAILURE;
2388 crypto_free (crypto);
2389 goto do_exit;
2391 else if (rc)
2392 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2393 else
2394 log_write (_("Successfully added '%s' to the cache."),
2395 crypto->filename);
2397 crypto_free (crypto);
2400 strv_free (cache_push);
2401 log_write (!nofork ? _("Done. Daemonizing...") :
2402 _("Done. Waiting for connections..."));
2405 backlog = config_get_integer ("global", "backlog");
2406 if (listen (sockfd, backlog) == -1)
2408 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2409 goto do_exit;
2412 if (!nofork)
2414 switch (fork ())
2416 case -1:
2417 log_write ("fork(): %s",
2418 pwmd_strerror (gpg_error_from_errno (errno)));
2419 goto do_exit;
2420 case 0:
2421 close (0);
2422 close (1);
2423 close (2);
2424 setsid ();
2425 break;
2426 default:
2427 _exit (EXIT_SUCCESS);
2431 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2432 mode, 0);
2433 xfree (socketname);
2434 cmdline = 0;
2435 pthread_key_create (&thread_name_key, free_key);
2436 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
2437 estatus = server_loop (sockfd, &socketpath);
2439 do_exit:
2440 if (socketpath && do_unlink)
2442 unlink (socketpath);
2443 xfree (socketpath);
2446 xfree (socketarg);
2447 #ifdef WITH_GNUTLS
2448 gnutls_global_deinit ();
2449 tls_deinit_params ();
2450 #endif
2451 pthread_cond_destroy (&rcfile_cond);
2452 pthread_mutex_destroy (&rcfile_mutex);
2453 pthread_key_delete (last_error_key);
2454 #ifndef HAVE_PTHREAD_CANCEL
2455 pthread_key_delete (signal_thread_key);
2456 #endif
2458 if (global_config)
2459 config_free (global_config);
2461 free_invoking_users (invoking_users);
2462 xfree (rcfile);
2463 xfree (home_directory);
2464 xfree (homedir);
2465 xmlCleanupParser ();
2466 xmlCleanupGlobals ();
2468 if (pidfile)
2469 unlink (pidfile);
2470 xfree (pidfile);
2472 if (estatus == EXIT_SUCCESS && !terminate)
2473 log_write (_("pwmd exiting normally"));
2475 pthread_key_delete (thread_name_key);
2476 closelog ();
2478 if (log_fd != -1)
2479 close (log_fd);
2481 exit (estatus);
2484 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2485 int type, int *fd)
2487 gpg_error_t rc = 0;
2489 #ifdef HAVE_FLOCK
2490 rc = open_check_file (filename, fd, NULL, 1);
2491 if (rc)
2492 return rc;
2494 TRY_FLOCK (ctx, *fd, type, rc);
2495 if (rc)
2497 close (*fd);
2498 *fd = -1;
2500 #endif
2502 return rc;
2505 void unlock_flock (int *fd)
2507 #ifdef HAVE_FLOCK
2508 if (*fd != -1)
2509 close (*fd);
2511 *fd = -1;
2512 #endif