diff --git a/src/assuan-pipe-connect.c b/src/assuan-pipe-connect.c index c116d1d..9669cb3 100644 --- a/src/assuan-pipe-connect.c +++ b/src/assuan-pipe-connect.c @@ -1,453 +1,490 @@ /* assuan-pipe-connect.c - Establish a pipe connection (client) * Copyright (C) 2001, 2002, 2003, 2005, 2006, 2007, 2009, 2010, * 2011 Free Software Foundation, Inc. * * This file is part of Assuan. * * Assuan is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Assuan is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1+ */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include /* On Windows systems signal.h is not needed and even not supported on WindowsCE. */ #ifndef HAVE_DOSISH_SYSTEM # include #endif #ifdef HAVE_UNISTD_H # include #endif #include #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_SYS_TYPES_H # include #endif #ifndef HAVE_W32_SYSTEM # include #else # ifdef HAVE_WINSOCK2_H # include # endif # include #endif #include "assuan-defs.h" #include "debug.h" /* Hacks for Slowaris. */ #ifndef PF_LOCAL # ifdef PF_UNIX # define PF_LOCAL PF_UNIX # else # define PF_LOCAL AF_UNIX # endif #endif #ifndef AF_LOCAL # define AF_LOCAL AF_UNIX #endif /* This should be called to make sure that SIGPIPE gets ignored. */ static void fix_signals (void) { #ifndef HAVE_DOSISH_SYSTEM /* No SIGPIPE for these systems. */ static int fixed_signals; if (!fixed_signals) { struct sigaction act; sigaction (SIGPIPE, NULL, &act); if (act.sa_handler == SIG_DFL) { act.sa_handler = SIG_IGN; sigemptyset (&act.sa_mask); act.sa_flags = 0; sigaction (SIGPIPE, &act, NULL); } fixed_signals = 1; /* FIXME: This is not MT safe */ } #endif /*HAVE_DOSISH_SYSTEM*/ } /* Helper for pipe_connect. */ static gpg_error_t initial_handshake (assuan_context_t ctx) { assuan_response_t response; int off; gpg_error_t err; err = _assuan_read_from_server (ctx, &response, &off, 0); if (err) TRACE1 (ctx, ASSUAN_LOG_SYSIO, "initial_handshake", ctx, "can't connect server: %s", gpg_strerror (err)); else if (response == ASSUAN_RESPONSE_OK) { #if defined(HAVE_W32_SYSTEM) const char *line = ctx->inbound.line + off; int process_id = -1; /* Parse the message: OK ..., process %i */ line = strchr (line, ','); if (line) { line = strchr (line + 1, ' '); if (line) { line = strchr (line + 1, ' '); if (line) process_id = atoi (line + 1); } } if (process_id != -1) ctx->process_id = process_id; #else ; #endif } else { TRACE1 (ctx, ASSUAN_LOG_SYSIO, "initial_handshake", ctx, "can't connect server: `%s'", ctx->inbound.line); err = _assuan_error (ctx, GPG_ERR_ASS_CONNECT_FAILED); } return err; } struct at_pipe_fork { void (*user_atfork) (void *opaque, int reserved); void *user_atforkvalue; pid_t parent_pid; }; static void at_pipe_fork_cb (void *opaque, int reserved) { struct at_pipe_fork *atp = opaque; if (atp->user_atfork) atp->user_atfork (atp->user_atforkvalue, reserved); #ifndef HAVE_W32_SYSTEM { char mypidstr[50]; /* We store our parents pid in the environment so that the execed assuan server is able to read the actual pid of the client. The server can't use getppid because it might have been double forked before the assuan server has been initialized. */ sprintf (mypidstr, "%lu", (unsigned long) atp->parent_pid); setenv ("_assuan_pipe_connect_pid", mypidstr, 1); /* Make sure that we never pass a connection fd variable when using a simple pipe. */ unsetenv ("_assuan_connection_fd"); } #endif } static gpg_error_t pipe_connect (assuan_context_t ctx, const char *name, const char **argv, assuan_fd_t *fd_child_list, void (*atfork) (void *opaque, int reserved), void *atforkvalue, unsigned int flags) { gpg_error_t rc; assuan_fd_t rp[2]; assuan_fd_t wp[2]; assuan_pid_t pid; int res; struct at_pipe_fork atp; unsigned int spawn_flags; atp.user_atfork = atfork; atp.user_atforkvalue = atforkvalue; atp.parent_pid = getpid (); if (!ctx || !name || !argv || !argv[0]) return _assuan_error (ctx, GPG_ERR_ASS_INV_VALUE); if (! ctx->flags.no_fixsignals) fix_signals (); if (_assuan_pipe (ctx, rp, 1) < 0) return _assuan_error (ctx, gpg_err_code_from_syserror ()); if (_assuan_pipe (ctx, wp, 0) < 0) { _assuan_close (ctx, rp[0]); _assuan_close_inheritable (ctx, rp[1]); return _assuan_error (ctx, gpg_err_code_from_syserror ()); } spawn_flags = 0; if (flags & ASSUAN_PIPE_CONNECT_DETACHED) spawn_flags |= ASSUAN_SPAWN_DETACHED; /* FIXME: Use atfork handler that closes child fds on Unix. */ res = _assuan_spawn (ctx, &pid, name, argv, wp[0], rp[1], fd_child_list, at_pipe_fork_cb, &atp, spawn_flags); if (res < 0) { rc = gpg_err_code_from_syserror (); _assuan_close (ctx, rp[0]); _assuan_close_inheritable (ctx, rp[1]); _assuan_close_inheritable (ctx, wp[0]); _assuan_close (ctx, wp[1]); return _assuan_error (ctx, rc); } /* Close the stdin/stdout child fds in the parent. */ _assuan_close_inheritable (ctx, rp[1]); _assuan_close_inheritable (ctx, wp[0]); ctx->engine.release = _assuan_client_release; ctx->engine.readfnc = _assuan_simple_read; ctx->engine.writefnc = _assuan_simple_write; #ifdef HAVE_W32_SYSTEM ctx->engine.sendfd = w32_fdpass_send; #else ctx->engine.sendfd = NULL; #endif ctx->engine.receivefd = NULL; ctx->finish_handler = _assuan_client_finish; ctx->max_accepts = 1; ctx->accept_handler = NULL; ctx->inbound.fd = rp[0]; /* Our inbound is read end of read pipe. */ ctx->outbound.fd = wp[1]; /* Our outbound is write end of write pipe. */ ctx->server_proc = pid; rc = initial_handshake (ctx); if (rc) _assuan_reset (ctx); return rc; } /* FIXME: For socketpair_connect, use spawn function and add atfork handler to do the right thing. Instead of stdin and stdout, we extend the fd_child_list by fds[1]. */ #ifndef HAVE_W32_SYSTEM struct at_socketpair_fork { assuan_fd_t peer_fd; void (*user_atfork) (void *opaque, int reserved); void *user_atforkvalue; pid_t parent_pid; }; static void at_socketpair_fork_cb (void *opaque, int reserved) { struct at_socketpair_fork *atp = opaque; if (atp->user_atfork) atp->user_atfork (atp->user_atforkvalue, reserved); #ifndef HAVE_W32_SYSTEM { char mypidstr[50]; /* We store our parents pid in the environment so that the execed assuan server is able to read the actual pid of the client. The server can't use getppid because it might have been double forked before the assuan server has been initialized. */ sprintf (mypidstr, "%lu", (unsigned long) atp->parent_pid); setenv ("_assuan_pipe_connect_pid", mypidstr, 1); /* Now set the environment variable used to convey the connection's file descriptor. */ sprintf (mypidstr, "%d", atp->peer_fd); if (setenv ("_assuan_connection_fd", mypidstr, 1)) _exit (4); } #endif } /* This function is similar to pipe_connect but uses a socketpair and sets the I/O up to use sendmsg/recvmsg. */ static gpg_error_t socketpair_connect (assuan_context_t ctx, const char *name, const char **argv, assuan_fd_t *fd_child_list, void (*atfork) (void *opaque, int reserved), void *atforkvalue) { gpg_error_t err; int idx; int fds[2]; char mypidstr[50]; pid_t pid; int *child_fds = NULL; int child_fds_cnt = 0; struct at_socketpair_fork atp; int rc; TRACE_BEG3 (ctx, ASSUAN_LOG_CTX, "socketpair_connect", ctx, "name=%s,atfork=%p,atforkvalue=%p", name ? name : "(null)", atfork, atforkvalue); atp.user_atfork = atfork; atp.user_atforkvalue = atforkvalue; atp.parent_pid = getpid (); if (!ctx || (name && (!argv || !argv[0])) || (!name && !argv)) return _assuan_error (ctx, GPG_ERR_ASS_INV_VALUE); if (! ctx->flags.no_fixsignals) fix_signals (); sprintf (mypidstr, "%lu", (unsigned long)getpid ()); if (fd_child_list) while (fd_child_list[child_fds_cnt] != ASSUAN_INVALID_FD) child_fds_cnt++; child_fds = _assuan_malloc (ctx, (child_fds_cnt + 2) * sizeof (int)); if (! child_fds) return TRACE_ERR (gpg_err_code_from_syserror ()); child_fds[1] = ASSUAN_INVALID_FD; if (fd_child_list) memcpy (&child_fds[1], fd_child_list, (child_fds_cnt + 1) * sizeof (int)); if (_assuan_socketpair (ctx, AF_LOCAL, SOCK_STREAM, 0, fds)) { TRACE_LOG1 ("socketpair failed: %s", strerror (errno)); _assuan_free (ctx, child_fds); return TRACE_ERR (GPG_ERR_ASS_GENERAL); } atp.peer_fd = fds[1]; child_fds[0] = fds[1]; rc = _assuan_spawn (ctx, &pid, name, argv, ASSUAN_INVALID_FD, ASSUAN_INVALID_FD, child_fds, at_socketpair_fork_cb, &atp, 0); if (rc < 0) { err = gpg_err_code_from_syserror (); _assuan_close (ctx, fds[0]); _assuan_close (ctx, fds[1]); _assuan_free (ctx, child_fds); return TRACE_ERR (err); } /* For W32, the user needs to know the server-local names of the inherited handles. Return them here. Note that the translation of the peer socketpair fd (fd_child_list[0]) must be done by the wrapper program based on the environment variable _assuan_connection_fd. */ if (fd_child_list) { for (idx = 0; fd_child_list[idx] != -1; idx++) /* We add 1 to skip over the socketpair end. */ fd_child_list[idx] = child_fds[idx + 1]; } _assuan_free (ctx, child_fds); /* If this is the server child process, exit early. */ if (! name && (*argv)[0] == 's') { _assuan_close (ctx, fds[0]); return 0; } _assuan_close (ctx, fds[1]); ctx->engine.release = _assuan_client_release; ctx->finish_handler = _assuan_client_finish; ctx->max_accepts = 1; ctx->inbound.fd = fds[0]; ctx->outbound.fd = fds[0]; _assuan_init_uds_io (ctx); err = initial_handshake (ctx); if (err) _assuan_reset (ctx); return err; } #endif /*!HAVE_W32_SYSTEM*/ /* Connect to a server over a full-duplex socket (i.e. created by socketpair), creating the assuan context and returning it in CTX. The server filename is NAME, the argument vector in ARGV. FD_CHILD_LIST is a -1 terminated list of file descriptors not to close in the child. ATFORK is called in the child right after the fork; ATFORKVALUE is passed as the first argument and 0 is passed as the second argument. The ATFORK function should only act if the second value is 0. FLAGS is a bit vector and controls how the function acts: Bit 0: If cleared a simple pipe based server is expected and the function behaves similar to `assuan_pipe_connect'. If set a server based on full-duplex pipes is expected. Such pipes are usually created using the `socketpair' function. It also enables features only available with such servers. Bit 7: If set and there is a need to start the server it will be started as a background process. This flag is useful under W32 systems, so that no new console is created and pops up a console window when starting the server If NAME is NULL, no exec is done but the same process is continued. However all file descriptors are closed and some special environment variables are set. To let the caller detect whether the child or the parent continues, the child returns "client" or "server" in *ARGV (but it is sufficient to check only the first character). This feature is only available on POSIX platforms. */ gpg_error_t assuan_pipe_connect (assuan_context_t ctx, const char *name, const char *argv[], assuan_fd_t *fd_child_list, void (*atfork) (void *opaque, int reserved), void *atforkvalue, unsigned int flags) { TRACE2 (ctx, ASSUAN_LOG_CTX, "assuan_pipe_connect", ctx, "name=%s, flags=0x%x", name ? name : "(null)", flags); #ifndef HAVE_W32_SYSTEM if (flags & ASSUAN_PIPE_CONNECT_FDPASSING) return socketpair_connect (ctx, name, argv, fd_child_list, atfork, atforkvalue); else #endif return pipe_connect (ctx, name, argv, fd_child_list, atfork, atforkvalue, flags); } +gpg_error_t +assuan_pipe_wait_server_termination (assuan_context_t ctx, int *status, + int no_hang) +{ + assuan_pid_t pid; + + if (ctx->server_proc == -1) + return _assuan_error (ctx, GPG_ERR_NO_SERVICE); + + pid = _assuan_waitpid (ctx, ctx->server_proc, 0, status, no_hang); + if (pid == -1) + return _assuan_error (ctx, gpg_err_code_from_syserror ()); + else if (pid == 0) + return _assuan_error (ctx, GPG_ERR_TIMEOUT); + + /* We did wait on the process already, so, not any more. */ + ctx->flags.no_waitpid = 1; + return 0; +} + +gpg_error_t +assuan_pipe_kill_server (assuan_context_t ctx) +{ + if (ctx->server_proc == -1) + ; /* No pid available can't send a kill. */ + else + { + _assuan_pre_syscall (); +#ifdef HAVE_W32_SYSTEM + TerminateProcess ((HANDLE)ctx->server_proc, 1); +#else + kill (ctx->server_proc, SIGINT); +#endif + _assuan_post_syscall (); + } + return 0; +} diff --git a/src/assuan.h.in b/src/assuan.h.in index 30a243c..99444b8 100644 --- a/src/assuan.h.in +++ b/src/assuan.h.in @@ -1,619 +1,623 @@ /* assuan.h - Definitions for the Assuan IPC library -*- c -*- * Copyright (C) 2001-2013 Free Software Foundation, Inc. * Copyright (C) 2001-2021 g10 Code GmbH * * This file is part of Assuan. * * Assuan is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Assuan is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later * * @configure_input@ */ /* Compile time configuration: * * #define _ASSUAN_NO_SOCKET_WRAPPER * * Do not include the definitions for the socket wrapper feature. */ #ifndef ASSUAN_H #define ASSUAN_H #include #include #include #include #ifndef _ASSUAN_NO_SOCKET_WRAPPER @include:includes@ #endif /*!_ASSUAN_NO_SOCKET_WRAPPER*/ @include:types@ #include #ifdef __cplusplus extern "C" { #if 0 } #endif #endif /* The version of this header should match the one of the library. Do * not use this symbol in your application; use assuan_check_version * instead. */ #define ASSUAN_VERSION @version@ /* The version number of this header. It may be used to handle minor * API incompatibilities. */ #define ASSUAN_VERSION_NUMBER @version-number@ /* Check for compiler features. */ #if __GNUC__ #define _ASSUAN_GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) #if _ASSUAN_GCC_VERSION > 30100 #define _ASSUAN_DEPRECATED __attribute__ ((__deprecated__)) #endif #endif #ifndef _ASSUAN_DEPRECATED #define _ASSUAN_DEPRECATED #endif #define ASSUAN_LINELENGTH 1002 /* 1000 + [CR,]LF */ struct assuan_context_s; typedef struct assuan_context_s *assuan_context_t; @include:fd-t@ assuan_fd_t assuan_fdopen (int fd); @include:sock-nonce@ /* * Global interface. */ struct assuan_malloc_hooks { void *(*malloc) (size_t cnt); void *(*realloc) (void *ptr, size_t cnt); void (*free) (void *ptr); }; typedef struct assuan_malloc_hooks *assuan_malloc_hooks_t; /* Categories for log messages. */ #define ASSUAN_LOG_INIT 1 #define ASSUAN_LOG_CTX 2 #define ASSUAN_LOG_ENGINE 3 #define ASSUAN_LOG_DATA 4 #define ASSUAN_LOG_SYSIO 5 #define ASSUAN_LOG_CONTROL 8 /* If MSG is NULL, return true/false depending on if this category is * logged. This is used to probe before expensive log message * generation (buffer dumps). */ typedef int (*assuan_log_cb_t) (assuan_context_t ctx, void *hook, unsigned int cat, const char *msg); /* Return or check the version number. */ const char *assuan_check_version (const char *req_version); /* Set the default gpg error source. */ void assuan_set_gpg_err_source (gpg_err_source_t errsource); /* Get the default gpg error source. */ gpg_err_source_t assuan_get_gpg_err_source (void); /* Set the default malloc hooks. */ void assuan_set_malloc_hooks (assuan_malloc_hooks_t malloc_hooks); /* Get the default malloc hooks. */ assuan_malloc_hooks_t assuan_get_malloc_hooks (void); /* Set the default log callback handler. */ void assuan_set_log_cb (assuan_log_cb_t log_cb, void *log_cb_data); /* Get the default log callback handler. */ void assuan_get_log_cb (assuan_log_cb_t *log_cb, void **log_cb_data); /* Create a new Assuan context. The initial parameters are all needed * in the creation of the context. */ gpg_error_t assuan_new_ext (assuan_context_t *ctx, gpg_err_source_t errsource, assuan_malloc_hooks_t malloc_hooks, assuan_log_cb_t log_cb, void *log_cb_data); /* Create a new context with default arguments. */ gpg_error_t assuan_new (assuan_context_t *ctx); /* Release all resources associated with the given context. */ void assuan_release (assuan_context_t ctx); /* Release the memory at PTR using the allocation handler of the * context CTX. This is a convenience function. */ void assuan_free (assuan_context_t ctx, void *ptr); /* Set user-data in a context. */ void assuan_set_pointer (assuan_context_t ctx, void *pointer); /* Get user-data in a context. */ void *assuan_get_pointer (assuan_context_t ctx); /* Definitions of flags for assuan_set_flag(). */ typedef unsigned int assuan_flag_t; /* When using a pipe server, by default Assuan will wait for the * forked process to die in assuan_release. In certain cases this * is not desirable. By setting this flag, the waitpid will be * skipped and the caller is responsible to cleanup a forked * process. */ #define ASSUAN_NO_WAITPID 1 /* This flag indicates whether Assuan logging is in confidential mode. You can use assuan_{begin,end}_condidential to change the mode. */ #define ASSUAN_CONFIDENTIAL 2 /* This flag suppresses fix up of signal handlers for pipes. */ #define ASSUAN_NO_FIXSIGNALS 3 /* This flag changes assuan_transact to return comment lines via the * status callback. The default is to skip comment lines. */ #define ASSUAN_CONVEY_COMMENTS 4 /* This flag disables logging for one context. */ #define ASSUAN_NO_LOGGING 5 /* This flag forces a connection close. */ #define ASSUAN_FORCE_CLOSE 6 /* For context CTX, set the flag FLAG to VALUE. Values for flags * are usually 1 or 0 but certain flags might allow for other values; * see the description of the type assuan_flag_t for details. */ void assuan_set_flag (assuan_context_t ctx, assuan_flag_t flag, int value); /* Return the VALUE of FLAG in context CTX. */ int assuan_get_flag (assuan_context_t ctx, assuan_flag_t flag); /* Same as assuan_set_flag (ctx, ASSUAN_CONFIDENTIAL, 1). */ void assuan_begin_confidential (assuan_context_t ctx); /* Same as assuan_set_flag (ctx, ASSUAN_CONFIDENTIAL, 0). */ void assuan_end_confidential (assuan_context_t ctx); /* Direction values for assuan_set_io_monitor. */ #define ASSUAN_IO_FROM_PEER 0 #define ASSUAN_IO_TO_PEER 1 /* Return flags of I/O monitor. */ #define ASSUAN_IO_MONITOR_NOLOG 1 #define ASSUAN_IO_MONITOR_IGNORE 2 /* The IO monitor gets to see all I/O on the context, and can return * ASSUAN_IO_MONITOR_* bits to control actions on it. */ typedef unsigned int (*assuan_io_monitor_t) (assuan_context_t ctx, void *hook, int inout, const char *line, size_t linelen); /* Set the IO monitor function. */ void assuan_set_io_monitor (assuan_context_t ctx, assuan_io_monitor_t io_monitor, void *hook_data); /* The system hooks. See assuan_set_system_hooks et al. */ #define ASSUAN_SYSTEM_HOOKS_VERSION 2 #define ASSUAN_SPAWN_DETACHED 128 struct assuan_system_hooks { /* Always set to ASSUAN_SYTEM_HOOKS_VERSION. */ int version; /* Sleep for the given number of microseconds. */ void (*usleep) (assuan_context_t ctx, unsigned int usec); /* Create a pipe with an inheritable end. */ int (*pipe) (assuan_context_t ctx, assuan_fd_t fd[2], int inherit_idx); /* Close the given file descriptor, created with _assuan_pipe or one of the socket functions. */ int (*close) (assuan_context_t ctx, assuan_fd_t fd); ssize_t (*read) (assuan_context_t ctx, assuan_fd_t fd, void *buffer, size_t size); ssize_t (*write) (assuan_context_t ctx, assuan_fd_t fd, const void *buffer, size_t size); int (*recvmsg) (assuan_context_t ctx, assuan_fd_t fd, assuan_msghdr_t msg, int flags); int (*sendmsg) (assuan_context_t ctx, assuan_fd_t fd, const assuan_msghdr_t msg, int flags); /* If NAME is NULL, don't exec, just fork. FD_CHILD_LIST is modified to reflect the value of the FD in the peer process (on Windows). */ int (*spawn) (assuan_context_t ctx, assuan_pid_t *r_pid, const char *name, const char **argv, assuan_fd_t fd_in, assuan_fd_t fd_out, assuan_fd_t *fd_child_list, void (*atfork) (void *opaque, int reserved), void *atforkvalue, unsigned int flags); /* If action is 0, like waitpid. If action is 1, just release the PID? */ assuan_pid_t (*waitpid) (assuan_context_t ctx, assuan_pid_t pid, int action, int *status, int options); int (*socketpair) (assuan_context_t ctx, int _namespace, int style, int protocol, assuan_fd_t filedes[2]); assuan_fd_t (*socket) (assuan_context_t ctx, int _namespace, int style, int protocol); int (*connect) (assuan_context_t ctx, assuan_fd_t sock, struct sockaddr *addr, socklen_t length); }; typedef struct assuan_system_hooks *assuan_system_hooks_t; /* * Configuration of the default log handler. */ /* Set the prefix to be used at the start of a line emitted by assuan * on the log stream. The default is the empty string. Note, that * this function is not thread-safe and should in general be used * right at startup. */ void assuan_set_assuan_log_prefix (const char *text); /* Return a prefix to be used at the start of a line emitted by assuan * on the log stream. The default implementation returns the empty * string, i.e. "". */ const char *assuan_get_assuan_log_prefix (void); /* Global default log stream. */ void assuan_set_assuan_log_stream (FILE *fp); /* Set the per context log stream for the default log handler. */ void assuan_set_log_stream (assuan_context_t ctx, FILE *fp); /* The type for assuan command handlers. */ typedef gpg_error_t (*assuan_handler_t) (assuan_context_t, char *); /*-- assuan-handler.c --*/ gpg_error_t assuan_register_command (assuan_context_t ctx, const char *cmd_string, assuan_handler_t handler, const char *help_string); gpg_error_t assuan_register_pre_cmd_notify (assuan_context_t ctx, gpg_error_t (*fnc)(assuan_context_t, const char *cmd)); gpg_error_t assuan_register_post_cmd_notify (assuan_context_t ctx, void (*fnc)(assuan_context_t, gpg_error_t)); gpg_error_t assuan_register_bye_notify (assuan_context_t ctx, assuan_handler_t handler); gpg_error_t assuan_register_reset_notify (assuan_context_t ctx, assuan_handler_t handler); gpg_error_t assuan_register_cancel_notify (assuan_context_t ctx, assuan_handler_t handler); gpg_error_t assuan_register_input_notify (assuan_context_t ctx, assuan_handler_t handler); gpg_error_t assuan_register_output_notify (assuan_context_t ctx, assuan_handler_t handler); gpg_error_t assuan_register_option_handler (assuan_context_t ctx, gpg_error_t (*fnc)(assuan_context_t, const char*, const char*)); gpg_error_t assuan_process (assuan_context_t ctx); gpg_error_t assuan_process_next (assuan_context_t ctx, int *done); gpg_error_t assuan_process_done (assuan_context_t ctx, gpg_error_t rc); int assuan_get_active_fds (assuan_context_t ctx, int what, assuan_fd_t *fdarray, int fdarraysize); const char *assuan_get_command_name (assuan_context_t ctx); FILE *assuan_get_data_fp (assuan_context_t ctx); gpg_error_t assuan_set_okay_line (assuan_context_t ctx, const char *line); gpg_error_t assuan_write_status (assuan_context_t ctx, const char *keyword, const char *text); /* Negotiate a file descriptor. If LINE contains "FD=N", returns N * assuming a local file descriptor. If LINE contains "FD" reads a * file descriptor via CTX and stores it in *RDF (the CTX must be * capable of passing file descriptors). Under Windows the returned * FD is a libc-type one. */ gpg_error_t assuan_command_parse_fd (assuan_context_t ctx, char *line, assuan_fd_t *rfd); /*-- assuan-listen.c --*/ gpg_error_t assuan_set_hello_line (assuan_context_t ctx, const char *line); gpg_error_t assuan_accept (assuan_context_t ctx); assuan_fd_t assuan_get_input_fd (assuan_context_t ctx); assuan_fd_t assuan_get_output_fd (assuan_context_t ctx); gpg_error_t assuan_close_input_fd (assuan_context_t ctx); gpg_error_t assuan_close_output_fd (assuan_context_t ctx); /*-- assuan-pipe-server.c --*/ gpg_error_t assuan_init_pipe_server (assuan_context_t ctx, assuan_fd_t filedes[2]); /*-- assuan-socket-server.c --*/ #define ASSUAN_SOCKET_SERVER_FDPASSING 1 #define ASSUAN_SOCKET_SERVER_ACCEPTED 2 gpg_error_t assuan_init_socket_server (assuan_context_t ctx, assuan_fd_t listen_fd, unsigned int flags); void assuan_set_sock_nonce (assuan_context_t ctx, assuan_sock_nonce_t *nonce); /*-- assuan-pipe-connect.c --*/ #define ASSUAN_PIPE_CONNECT_FDPASSING 1 #define ASSUAN_PIPE_CONNECT_DETACHED 128 gpg_error_t assuan_pipe_connect (assuan_context_t ctx, const char *name, const char *argv[], assuan_fd_t *fd_child_list, void (*atfork) (void *, int), void *atforkvalue, unsigned int flags); /*-- assuan-socket-connect.c --*/ #define ASSUAN_SOCKET_CONNECT_FDPASSING 1 gpg_error_t assuan_socket_connect (assuan_context_t ctx, const char *name, pid_t server_pid, unsigned int flags); /*-- assuan-socket-connect.c --*/ gpg_error_t assuan_socket_connect_fd (assuan_context_t ctx, assuan_fd_t fd, unsigned int flags); /*-- context.c --*/ pid_t assuan_get_pid (assuan_context_t ctx); struct _assuan_peercred { #ifdef _WIN32 /* Empty struct not allowed on some compilers, so, put this (not valid). */ pid_t pid; #else pid_t pid; uid_t uid; gid_t gid; #endif }; typedef struct _assuan_peercred *assuan_peercred_t; gpg_error_t assuan_get_peercred (assuan_context_t ctx, assuan_peercred_t *peercred); /* * Client interface. */ /* Client response codes. */ #define ASSUAN_RESPONSE_ERROR 0 #define ASSUAN_RESPONSE_OK 1 #define ASSUAN_RESPONSE_DATA 2 #define ASSUAN_RESPONSE_INQUIRE 3 #define ASSUAN_RESPONSE_STATUS 4 #define ASSUAN_RESPONSE_END 5 #define ASSUAN_RESPONSE_COMMENT 6 typedef int assuan_response_t; /* This already de-escapes data lines. */ gpg_error_t assuan_client_read_response (assuan_context_t ctx, char **line, int *linelen); gpg_error_t assuan_client_parse_response (assuan_context_t ctx, char *line, int linelen, assuan_response_t *response, int *off); /*-- assuan-client.c --*/ gpg_error_t assuan_transact (assuan_context_t ctx, const char *command, gpg_error_t (*data_cb)(void *, const void *, size_t), void *data_cb_arg, gpg_error_t (*inquire_cb)(void*, const char *), void *inquire_cb_arg, gpg_error_t (*status_cb)(void*, const char *), void *status_cb_arg); /*-- assuan-inquire.c --*/ gpg_error_t assuan_inquire (assuan_context_t ctx, const char *keyword, unsigned char **r_buffer, size_t *r_length, size_t maxlen); gpg_error_t assuan_inquire_ext (assuan_context_t ctx, const char *keyword, size_t maxlen, gpg_error_t (*cb) (void *cb_data, gpg_error_t rc, unsigned char *buf, size_t buf_len), void *cb_data); /*-- assuan-buffer.c --*/ gpg_error_t assuan_read_line (assuan_context_t ctx, char **line, size_t *linelen); int assuan_pending_line (assuan_context_t ctx); gpg_error_t assuan_write_line (assuan_context_t ctx, const char *line); gpg_error_t assuan_send_data (assuan_context_t ctx, const void *buffer, size_t length); /* The file descriptor must be pending before assuan_receivefd is * called. This means that assuan_sendfd should be called *before* the * trigger is sent (normally via assuan_write_line ("INPUT FD")). */ gpg_error_t assuan_sendfd (assuan_context_t ctx, assuan_fd_t fd); gpg_error_t assuan_receivefd (assuan_context_t ctx, assuan_fd_t *fd); /*-- assuan-util.c --*/ gpg_error_t assuan_set_error (assuan_context_t ctx, gpg_error_t err, const char *text); /*-- assuan-socket.c --*/ /* This flag is used with assuan_sock_connect_byname to * connect via SOCKS. */ #define ASSUAN_SOCK_SOCKS 1 /* This flag is used with assuan_sock_connect_byname to force a connection via Tor even if the socket subsystem has not been swicthed into Tor mode. This flags overrides ASSUAN_SOCK_SOCKS. */ #define ASSUAN_SOCK_TOR 2 /* These are socket wrapper functions to support an emulation of Unix * domain sockets on Windows. */ gpg_error_t assuan_sock_init (void); void assuan_sock_deinit (void); int assuan_sock_close (assuan_fd_t fd); assuan_fd_t assuan_sock_new (int domain, int type, int proto); int assuan_sock_set_flag (assuan_fd_t sockfd, const char *name, int value); int assuan_sock_get_flag (assuan_fd_t sockfd, const char *name, int *r_value); assuan_fd_t assuan_sock_accept (assuan_fd_t sockfd, struct sockaddr *addr, socklen_t *p_addrlen); int assuan_sock_connect (assuan_fd_t sockfd, struct sockaddr *addr, int addrlen); assuan_fd_t assuan_sock_connect_byname (const char *host, unsigned short port, int timeout, const char *credentials, unsigned int flags); int assuan_sock_bind (assuan_fd_t sockfd, struct sockaddr *addr, int addrlen); int assuan_sock_set_sockaddr_un (const char *fname, struct sockaddr *addr, int *r_redirected); int assuan_sock_get_nonce (struct sockaddr *addr, int addrlen, assuan_sock_nonce_t *nonce); int assuan_sock_check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce); void assuan_sock_set_system_hooks (assuan_system_hooks_t system_hooks); +gpg_error_t assuan_pipe_wait_server_termination (assuan_context_t ctx, + int *status, int no_hang); + +gpg_error_t assuan_pipe_kill_server (assuan_context_t ctx); /* Set the default system callbacks. This is irreversible. */ void assuan_set_system_hooks (assuan_system_hooks_t system_hooks); /* Set the per context system callbacks. This is irreversible. */ void assuan_ctx_set_system_hooks (assuan_context_t ctx, assuan_system_hooks_t system_hooks); /* Change the system hooks for the socket interface. * This is not thread-safe. */ void assuan_sock_set_system_hooks (assuan_system_hooks_t system_hooks); void __assuan_usleep (assuan_context_t ctx, unsigned int usec); int __assuan_pipe (assuan_context_t ctx, assuan_fd_t fd[2], int inherit_idx); int __assuan_close (assuan_context_t ctx, assuan_fd_t fd); int __assuan_spawn (assuan_context_t ctx, assuan_pid_t *r_pid, const char *name, const char **argv, assuan_fd_t fd_in, assuan_fd_t fd_out, assuan_fd_t *fd_child_list, void (*atfork) (void *opaque, int reserved), void *atforkvalue, unsigned int flags); int __assuan_socketpair (assuan_context_t ctx, int _namespace, int style, int protocol, assuan_fd_t filedes[2]); assuan_fd_t __assuan_socket (assuan_context_t ctx, int _namespace, int style, int protocol); int __assuan_connect (assuan_context_t ctx, assuan_fd_t sock, struct sockaddr *addr, socklen_t length); ssize_t __assuan_read (assuan_context_t ctx, assuan_fd_t fd, void *buffer, size_t size); ssize_t __assuan_write (assuan_context_t ctx, assuan_fd_t fd, const void *buffer, size_t size); int __assuan_recvmsg (assuan_context_t ctx, assuan_fd_t fd, assuan_msghdr_t msg, int flags); int __assuan_sendmsg (assuan_context_t ctx, assuan_fd_t fd, const assuan_msghdr_t msg, int flags); assuan_pid_t __assuan_waitpid (assuan_context_t ctx, assuan_pid_t pid, int nowait, int *status, int options); #if defined(LIBASSUAN_API_REQUESTED) && LIBASSUAN_API_REQUESTED >= 3 #defined ASSUAN_NO_GLOBAL_SYSTEM_HOOKS_ANY_MORE 1 #endif #if defined(ASSUAN_REALLY_REQUIRE_OLD_WAY_OF_SYSTEM_NPTH) \ || !defined(ASSUAN_NO_GLOBAL_SYSTEM_HOOKS_ANY_MORE) /* Standard system hooks for nPth. */ #define ASSUAN_SYSTEM_NPTH_IMPL \ static void _assuan_npth_usleep (assuan_context_t ctx, unsigned int usec) \ { npth_unprotect(); \ __assuan_usleep (ctx, usec); \ npth_protect(); } \ static ssize_t _assuan_npth_read (assuan_context_t ctx, assuan_fd_t fd, \ void *buffer, size_t size) \ { ssize_t res; (void) ctx; npth_unprotect(); \ res = __assuan_read (ctx, fd, buffer, size); \ npth_protect(); return res; } \ static ssize_t _assuan_npth_write (assuan_context_t ctx, assuan_fd_t fd, \ const void *buffer, size_t size) \ { ssize_t res; (void) ctx; npth_unprotect(); \ res = __assuan_write (ctx, fd, buffer, size); \ npth_protect(); return res; } \ static int _assuan_npth_recvmsg (assuan_context_t ctx, assuan_fd_t fd, \ assuan_msghdr_t msg, int flags) \ { int res; (void) ctx; npth_unprotect(); \ res = __assuan_recvmsg (ctx, fd, msg, flags); \ npth_protect(); return res; } \ static int _assuan_npth_sendmsg (assuan_context_t ctx, assuan_fd_t fd, \ const assuan_msghdr_t msg, int flags) \ { int res; (void) ctx; npth_unprotect(); \ res = __assuan_sendmsg (ctx, fd, msg, flags); \ npth_protect(); return res; } \ static assuan_pid_t _assuan_npth_waitpid (assuan_context_t ctx, \ assuan_pid_t pid, int nowait, \ int *status, int options) \ { assuan_pid_t res; (void) ctx; npth_unprotect(); \ res = __assuan_waitpid (ctx, pid, nowait, status, options); \ npth_protect(); return res; } \ static int _assuan_npth_connect (assuan_context_t ctx, assuan_fd_t sock, \ struct sockaddr *addr, socklen_t len)\ { int res; npth_unprotect(); \ res = __assuan_connect (ctx, sock, addr, len); \ npth_protect(); return res; } \ static int _assuan_npth_close (assuan_context_t ctx, assuan_fd_t fd) \ { int res; npth_unprotect(); \ res = __assuan_close (ctx, fd); \ npth_protect(); return res; } \ \ struct assuan_system_hooks _assuan_system_npth = \ { ASSUAN_SYSTEM_HOOKS_VERSION, _assuan_npth_usleep, __assuan_pipe, \ _assuan_npth_close, _assuan_npth_read, _assuan_npth_write, \ _assuan_npth_recvmsg, _assuan_npth_sendmsg, \ __assuan_spawn, _assuan_npth_waitpid, __assuan_socketpair, \ __assuan_socket, _assuan_npth_connect } extern struct assuan_system_hooks _assuan_system_npth; #define ASSUAN_SYSTEM_NPTH &_assuan_system_npth #else #define ASSUAN_SYSTEM_NPTH_IMPL /**/ #define ASSUAN_SYSTEM_NPTH NULL #endif #ifdef __cplusplus } #endif #endif /* ASSUAN_H */ diff --git a/src/libassuan.def b/src/libassuan.def index ed9ceaf..d1f0f76 100644 --- a/src/libassuan.def +++ b/src/libassuan.def @@ -1,121 +1,123 @@ ; assuan.def - List of symbols to export. ; Copyright (C) 2005, 2009 g10 Code GmbH ; ; This file is part of ASSUAN. ; ; ASSUAN is free software; you can redistribute it and/or modify ; it under the terms of the GNU Lesser general Public License as ; published by the Free Software Foundation; either version 2.1 of ; the License, or (at your option) any later version. ; ; ASSUAN is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU Lesser General Public License for more details. ; ; You should have received a copy of the GNU Lesser General Public ; License along with this program; if not, see . ; SPDX-License-Identifier: LGPL-2.1+ EXPORTS assuan_accept @1 assuan_begin_confidential @2 assuan_close_input_fd @3 assuan_close_output_fd @4 assuan_command_parse_fd @5 assuan_ctx_set_system_hooks @6 assuan_end_confidential @7 assuan_get_active_fds @8 assuan_get_assuan_log_prefix @9 assuan_get_command_name @10 assuan_get_data_fp @11 assuan_get_flag @12 assuan_get_gpg_err_source @13 assuan_get_input_fd @14 assuan_get_log_cb @15 assuan_get_malloc_hooks @16 assuan_get_output_fd @17 assuan_get_peercred @18 assuan_get_pid @19 assuan_get_pointer @20 assuan_init_pipe_server @21 assuan_init_socket_server @22 assuan_inquire @23 assuan_inquire_ext @24 assuan_new @25 assuan_new_ext @26 assuan_pending_line @27 assuan_pipe_connect @28 assuan_process @29 assuan_process_done @30 assuan_process_next @31 assuan_read_line @32 assuan_receivefd @33 assuan_register_bye_notify @34 assuan_register_cancel_notify @35 assuan_register_command @36 assuan_register_input_notify @37 assuan_register_option_handler @38 assuan_register_output_notify @39 assuan_register_post_cmd_notify @40 assuan_register_reset_notify @41 assuan_release @42 assuan_send_data @43 assuan_sendfd @44 assuan_set_assuan_log_prefix @45 assuan_set_assuan_log_stream @46 assuan_set_error @47 assuan_set_flag @48 assuan_set_gpg_err_source @49 assuan_set_hello_line @50 assuan_set_io_monitor @51 assuan_set_log_cb @52 assuan_set_log_stream @53 assuan_set_malloc_hooks @54 assuan_set_okay_line @55 assuan_set_pointer @56 assuan_set_system_hooks @57 assuan_sock_bind @58 assuan_sock_check_nonce @59 assuan_sock_close @60 assuan_sock_connect @61 assuan_sock_deinit @62 assuan_sock_get_nonce @63 assuan_sock_init @64 assuan_sock_new @65 assuan_socket_connect @66 assuan_transact @67 assuan_write_line @68 assuan_write_status @69 __assuan_close @70 __assuan_pipe @71 __assuan_socketpair @72 __assuan_spawn @73 __assuan_usleep @74 assuan_fdopen @75 assuan_client_read_response @76 assuan_client_parse_response @77 assuan_set_sock_nonce @78 _assuan_w32ce_create_pipe @79 assuan_free @80 _assuan_w32ce_prepare_pipe @81 _assuan_w32ce_finish_pipe @82 __assuan_socket @83 __assuan_connect @84 assuan_register_pre_cmd_notify @85 assuan_socket_connect_fd @86 __assuan_read @87 __assuan_write @88 __assuan_recvmsg @89 __assuan_sendmsg @90 __assuan_waitpid @91 assuan_check_version @92 assuan_sock_set_sockaddr_un @93 assuan_sock_set_flag @94 assuan_sock_get_flag @95 assuan_sock_connect_byname @96 assuan_sock_set_system_hooks @97 + assuan_pipe_wait_server_termination @98 + assuan_pipe_kill_server @99 ; END diff --git a/src/libassuan.vers b/src/libassuan.vers index 788bb92..1726dcc 100644 --- a/src/libassuan.vers +++ b/src/libassuan.vers @@ -1,125 +1,127 @@ # libassuan.vers - List of symbols to export. # Copyright (C) 2009 g10 Code GmbH # # This file is part of LIBASSUAN. # # LIBASSUAN is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser general Public License as # published by the Free Software Foundation; either version 2.1 of # the License, or (at your option) any later version. # # LIBASSUAN is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see . # SPDX-License-Identifier: LGPL-2.1+ #----------------------------------------------------------- # Please remember to add new functions also to libassuan.def #----------------------------------------------------------- LIBASSUAN_1.0 { global: assuan_accept; assuan_begin_confidential; assuan_client_read_response; assuan_client_parse_response; assuan_close_input_fd; assuan_close_output_fd; assuan_command_parse_fd; assuan_ctx_set_system_hooks; assuan_end_confidential; assuan_fdopen; assuan_get_active_fds; assuan_get_assuan_log_prefix; assuan_get_command_name; assuan_get_data_fp; assuan_get_flag; assuan_get_gpg_err_source; assuan_get_input_fd; assuan_get_log_cb; assuan_get_malloc_hooks; assuan_get_output_fd; assuan_get_peercred; assuan_get_pid; assuan_get_pointer; assuan_init_pipe_server; assuan_init_socket_server; assuan_inquire; assuan_inquire_ext; assuan_new; assuan_new_ext; assuan_pending_line; assuan_pipe_connect; assuan_process; assuan_process_done; assuan_process_next; assuan_read_line; assuan_receivefd; assuan_register_bye_notify; assuan_register_cancel_notify; assuan_register_command; assuan_register_input_notify; assuan_register_option_handler; assuan_register_output_notify; assuan_register_pre_cmd_notify; assuan_register_post_cmd_notify; assuan_register_reset_notify; assuan_release; assuan_send_data; assuan_sendfd; assuan_set_assuan_log_prefix; assuan_set_assuan_log_stream; assuan_set_error; assuan_set_flag; assuan_set_gpg_err_source; assuan_set_hello_line; assuan_set_io_monitor; assuan_set_log_cb; assuan_set_log_stream; assuan_set_malloc_hooks; assuan_set_okay_line; assuan_set_pointer; assuan_set_sock_nonce; assuan_set_system_hooks; assuan_sock_bind; assuan_sock_check_nonce; assuan_sock_close; assuan_sock_connect; assuan_sock_deinit; assuan_sock_get_nonce; assuan_sock_init; assuan_sock_new; assuan_socket_connect; assuan_transact; assuan_write_line; assuan_write_status; assuan_free; assuan_socket_connect_fd; assuan_check_version; assuan_sock_set_sockaddr_un; assuan_sock_set_flag; assuan_sock_get_flag; assuan_sock_connect_byname; assuan_sock_set_system_hooks; + assuan_pipe_wait_server_termination; + assuan_pipe_kill_server; __assuan_close; __assuan_pipe; __assuan_socketpair; __assuan_spawn; __assuan_usleep; __assuan_socket; __assuan_connect; __assuan_read; __assuan_write; __assuan_recvmsg; __assuan_sendmsg; __assuan_waitpid; local: *; }; diff --git a/src/system-posix.c b/src/system-posix.c index 5f3a7f2..7952907 100644 --- a/src/system-posix.c +++ b/src/system-posix.c @@ -1,451 +1,452 @@ /* system-posix.c - System support functions. * Copyright (C) 2009, 2010 Free Software Foundation, Inc. * * This file is part of Assuan. * * Assuan is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Assuan is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1+ */ #ifdef HAVE_CONFIG_H #include #endif #include #include #ifdef HAVE_STDINT_H # include #endif /* Solaris 8 needs sys/types.h before time.h. */ #include #include #include #include #ifdef HAVE_GETRLIMIT # include # include #endif /*HAVE_GETRLIMIT*/ #if __linux__ # include #endif /*__linux__ */ #include "assuan-defs.h" #include "debug.h" assuan_fd_t assuan_fdopen (int fd) { return dup (fd); } /* Sleep for the given number of microseconds. Default implementation. */ void __assuan_usleep (assuan_context_t ctx, unsigned int usec) { if (! usec) return; #ifdef HAVE_NANOSLEEP { struct timespec req; struct timespec rem; req.tv_sec = usec / 1000000; req.tv_nsec = (usec % 1000000) * 1000; while (nanosleep (&req, &rem) < 0 && errno == EINTR) req = rem; } #else { struct timeval tv; tv.tv_sec = usec / 1000000; tv.tv_usec = usec % 1000000; select (0, NULL, NULL, NULL, &tv); } #endif } /* Create a pipe with one inheritable end. Easy for Posix. */ int __assuan_pipe (assuan_context_t ctx, assuan_fd_t fd[2], int inherit_idx) { return pipe (fd); } /* Close the given file descriptor, created with _assuan_pipe or one of the socket functions. Easy for Posix. */ int __assuan_close (assuan_context_t ctx, assuan_fd_t fd) { return close (fd); } ssize_t __assuan_read (assuan_context_t ctx, assuan_fd_t fd, void *buffer, size_t size) { return read (fd, buffer, size); } ssize_t __assuan_write (assuan_context_t ctx, assuan_fd_t fd, const void *buffer, size_t size) { return write (fd, buffer, size); } int __assuan_recvmsg (assuan_context_t ctx, assuan_fd_t fd, assuan_msghdr_t msg, int flags) { int ret; do ret = recvmsg (fd, msg, flags); while (ret == -1 && errno == EINTR); return ret; } int __assuan_sendmsg (assuan_context_t ctx, assuan_fd_t fd, assuan_msghdr_t msg, int flags) { int ret; do ret = sendmsg (fd, msg, flags); while (ret == -1 && errno == EINTR); return ret; } static int writen (int fd, const char *buffer, size_t length) { while (length) { int nwritten = write (fd, buffer, length); if (nwritten < 0) { if (errno == EINTR) continue; return -1; /* write error */ } length -= nwritten; buffer += nwritten; } return 0; /* okay */ } /* Return the maximum number of currently allowed open file * descriptors. */ static int get_max_fds (void) { int max_fds = -1; #ifdef HAVE_GETRLIMIT struct rlimit rl; /* Under Linux we can figure out the highest used file descriptor by * reading /proc/PID/fd. This is in the common cases much faster * than for example doing 4096 close calls where almost all of them * will fail. We use the same code in GnuPG and measured this: On a * system with a limit of 4096 files and only 8 files open with the * highest number being 10, we speedup close_all_fds from 125ms to * 0.4ms including the readdir. * * Another option would be to close the file descriptors as returned * from reading that directory - however then we need to snapshot * that list before starting to close them. */ #ifdef __linux__ { DIR *dir = NULL; struct dirent *dir_entry; const char *s; int x; dir = opendir ("/proc/self/fd"); if (dir) { while ((dir_entry = readdir (dir))) { s = dir_entry->d_name; if ( *s < '0' || *s > '9') continue; x = atoi (s); if (x > max_fds) max_fds = x; } closedir (dir); } if (max_fds != -1) return max_fds + 1; } #endif /* __linux__ */ # ifdef RLIMIT_NOFILE if (!getrlimit (RLIMIT_NOFILE, &rl)) max_fds = rl.rlim_max; # endif # ifdef RLIMIT_OFILE if (max_fds == -1 && !getrlimit (RLIMIT_OFILE, &rl)) max_fds = rl.rlim_max; # endif #endif /*HAVE_GETRLIMIT*/ #ifdef _SC_OPEN_MAX if (max_fds == -1) { long int scres = sysconf (_SC_OPEN_MAX); if (scres >= 0) max_fds = scres; } #endif #ifdef _POSIX_OPEN_MAX if (max_fds == -1) max_fds = _POSIX_OPEN_MAX; #endif #ifdef OPEN_MAX if (max_fds == -1) max_fds = OPEN_MAX; #endif if (max_fds == -1) max_fds = 256; /* Arbitrary limit. */ /* AIX returns INT32_MAX instead of a proper value. We assume that this is always an error and use a more reasonable limit. */ #ifdef INT32_MAX if (max_fds == INT32_MAX) max_fds = 256; #endif return max_fds; } int __assuan_spawn (assuan_context_t ctx, assuan_pid_t *r_pid, const char *name, const char **argv, assuan_fd_t fd_in, assuan_fd_t fd_out, assuan_fd_t *fd_child_list, void (*atfork) (void *opaque, int reserved), void *atforkvalue, unsigned int flags) { int pid; pid = fork (); if (pid < 0) return -1; if (pid == 0) { /* Child process (server side). */ int i; int n; char errbuf[512]; int *fdp; int fdnul; if (atfork) atfork (atforkvalue, 0); fdnul = open ("/dev/null", O_WRONLY); if (fdnul == -1) { TRACE1 (ctx, ASSUAN_LOG_SYSIO, "__assuan_spawn", ctx, "can't open `/dev/null': %s", strerror (errno)); _exit (4); } /* Dup handles to stdin/stdout. */ if (fd_out != STDOUT_FILENO) { if (dup2 (fd_out == ASSUAN_INVALID_FD ? fdnul : fd_out, STDOUT_FILENO) == -1) { TRACE1 (ctx, ASSUAN_LOG_SYSIO, "__assuan_spawn", ctx, "dup2 failed in child: %s", strerror (errno)); _exit (4); } } if (fd_in != STDIN_FILENO) { if (dup2 (fd_in == ASSUAN_INVALID_FD ? fdnul : fd_in, STDIN_FILENO) == -1) { TRACE1 (ctx, ASSUAN_LOG_SYSIO, "__assuan_spawn", ctx, "dup2 failed in child: %s", strerror (errno)); _exit (4); } } /* Dup stderr to /dev/null unless it is in the list of FDs to be passed to the child. */ fdp = fd_child_list; if (fdp) { for (; *fdp != -1 && *fdp != STDERR_FILENO; fdp++) ; } if (!fdp || *fdp == -1) { if (dup2 (fdnul, STDERR_FILENO) == -1) { TRACE1 (ctx, ASSUAN_LOG_SYSIO, "pipe_connect_unix", ctx, "dup2(dev/null, 2) failed: %s", strerror (errno)); _exit (4); } } close (fdnul); /* Close all files which will not be duped and are not in the fd_child_list. */ n = get_max_fds (); for (i = 0; i < n; i++) { if (i == STDIN_FILENO || i == STDOUT_FILENO || i == STDERR_FILENO) continue; fdp = fd_child_list; if (fdp) { while (*fdp != -1 && *fdp != i) fdp++; } if (!(fdp && *fdp != -1)) close (i); } gpg_err_set_errno (0); if (! name) { /* No name and no args given, thus we don't do an exec but continue the forked process. */ *argv = "server"; /* FIXME: Cleanup. */ return 0; } execv (name, (char *const *) argv); /* oops - use the pipe to tell the parent about it */ snprintf (errbuf, sizeof(errbuf)-1, "ERR %d can't exec `%s': %.50s\n", _assuan_error (ctx, GPG_ERR_ASS_SERVER_START), name, strerror (errno)); errbuf[sizeof(errbuf)-1] = 0; writen (1, errbuf, strlen (errbuf)); _exit (4); } if (! name) *argv = "client"; *r_pid = pid; return 0; } /* FIXME: Add some sort of waitpid function that covers GPGME and gpg-agent's use of assuan. */ assuan_pid_t __assuan_waitpid (assuan_context_t ctx, assuan_pid_t pid, int nowait, int *status, int options) { + if (nowait) + return 0; + /* We can't just release the PID, a waitpid is mandatory. But NOWAIT in POSIX systems just means the caller already did the waitpid for this child. */ - if (! nowait) - return waitpid (pid, NULL, 0); - return 0; + return waitpid (pid, status, options ? WNOHANG : 0); } int __assuan_socketpair (assuan_context_t ctx, int namespace, int style, int protocol, assuan_fd_t filedes[2]) { return socketpair (namespace, style, protocol, filedes); } int __assuan_socket (assuan_context_t ctx, int namespace, int style, int protocol) { return socket (namespace, style, protocol); } int __assuan_connect (assuan_context_t ctx, int sock, struct sockaddr *addr, socklen_t length) { return connect (sock, addr, length); } /* The default system hooks for assuan contexts. */ struct assuan_system_hooks _assuan_system_hooks = { 0, __assuan_usleep, __assuan_pipe, __assuan_close, __assuan_read, __assuan_write, __assuan_recvmsg, __assuan_sendmsg, __assuan_spawn, __assuan_waitpid, __assuan_socketpair, __assuan_socket, __assuan_connect }; diff --git a/src/system-w32.c b/src/system-w32.c index 415cd63..a1ac42f 100644 --- a/src/system-w32.c +++ b/src/system-w32.c @@ -1,657 +1,679 @@ /* system-w32.c - System support functions for Windows. * Copyright (C) 2009, 2010 Free Software Foundation, Inc. * * This file is part of Assuan. * * Assuan is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Assuan is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1+ */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include "assuan-defs.h" #include "debug.h" assuan_fd_t assuan_fdopen (int fd) { assuan_fd_t ifd = (assuan_fd_t) _get_osfhandle (fd); assuan_fd_t ofd; if (! DuplicateHandle(GetCurrentProcess(), ifd, GetCurrentProcess(), &ofd, 0, TRUE, DUPLICATE_SAME_ACCESS)) { gpg_err_set_errno (EIO); return ASSUAN_INVALID_FD; } return ofd; } /* Sleep for the given number of microseconds. Default implementation. */ void __assuan_usleep (assuan_context_t ctx, unsigned int usec) { if (!usec) return; Sleep (usec / 1000); } /* Three simple wrappers, only used because thes function are named in the def file. */ HANDLE _assuan_w32ce_prepare_pipe (int *r_rvid, int write_end) { (void)r_rvid; (void)write_end; return INVALID_HANDLE_VALUE; } HANDLE _assuan_w32ce_finish_pipe (int rvid, int write_end) { (void)rvid; (void)write_end; return INVALID_HANDLE_VALUE; } DWORD _assuan_w32ce_create_pipe (HANDLE *read_hd, HANDLE *write_hd, LPSECURITY_ATTRIBUTES sec_attr, DWORD size) { return CreatePipe (read_hd, write_hd, sec_attr, size); } /* Create a pipe with one inheritable end. Default implementation. */ int __assuan_pipe (assuan_context_t ctx, assuan_fd_t fd[2], int inherit_idx) { HANDLE rh; HANDLE wh; HANDLE th; SECURITY_ATTRIBUTES sec_attr; memset (&sec_attr, 0, sizeof (sec_attr)); sec_attr.nLength = sizeof (sec_attr); sec_attr.bInheritHandle = FALSE; if (!CreatePipe (&rh, &wh, &sec_attr, 0)) { TRACE1 (ctx, ASSUAN_LOG_SYSIO, "__assuan_pipe", ctx, "CreatePipe failed: %s", _assuan_w32_strerror (ctx, -1)); gpg_err_set_errno (EIO); return -1; } if (! DuplicateHandle (GetCurrentProcess(), (inherit_idx == 0) ? rh : wh, GetCurrentProcess(), &th, 0, TRUE, DUPLICATE_SAME_ACCESS )) { TRACE1 (ctx, ASSUAN_LOG_SYSIO, "__assuan_pipe", ctx, "DuplicateHandle failed: %s", _assuan_w32_strerror (ctx, -1)); CloseHandle (rh); CloseHandle (wh); gpg_err_set_errno (EIO); return -1; } if (inherit_idx == 0) { CloseHandle (rh); rh = th; } else { CloseHandle (wh); wh = th; } fd[0] = rh; fd[1] = wh; return 0; } /* Close the given file descriptor, created with _assuan_pipe or one of the socket functions. Default implementation. */ int __assuan_close (assuan_context_t ctx, assuan_fd_t fd) { int rc; if (ctx->flags.is_socket) { rc = closesocket (HANDLE2SOCKET(fd)); if (rc) gpg_err_set_errno ( _assuan_sock_wsa2errno (WSAGetLastError ()) ); } else { rc = CloseHandle (fd); if (rc) /* FIXME. */ gpg_err_set_errno (EIO); } return rc; } /* Get a file HANDLE for other end to send, from MY_HANDLE. */ static gpg_error_t get_file_handle (assuan_fd_t my_handle, int process_id, HANDLE *r_handle) { HANDLE prochandle, newhandle; prochandle = OpenProcess (PROCESS_DUP_HANDLE, FALSE, process_id); if (!prochandle) return gpg_error (GPG_ERR_ASS_PARAMETER);/*FIXME: error*/ if (!DuplicateHandle (GetCurrentProcess (), my_handle, prochandle, &newhandle, 0, TRUE, DUPLICATE_SAME_ACCESS)) { CloseHandle (prochandle); return gpg_error (GPG_ERR_ASS_PARAMETER);/*FIXME: error*/ } CloseHandle (prochandle); *r_handle = newhandle; return 0; } /* Send an FD (which means Windows HANDLE) to the peer. */ gpg_error_t w32_fdpass_send (assuan_context_t ctx, assuan_fd_t fd) { char fdpass_msg[256]; int res; HANDLE file_handle; gpg_error_t err; err = get_file_handle (fd, ctx->process_id, &file_handle); if (err) return err; res = snprintf (fdpass_msg, sizeof (fdpass_msg), "SENDFD %p", file_handle); if (res < 0) { CloseHandle (file_handle); return gpg_error (GPG_ERR_ASS_PARAMETER);/*FIXME: error*/ } err = assuan_transact (ctx, fdpass_msg, NULL, NULL, NULL, NULL, NULL, NULL); return err; } /* Receive a HANDLE from the peer and turn it into an FD. */ gpg_error_t w32_fdpass_recv (assuan_context_t ctx, assuan_fd_t *fd) { int i; if (!ctx->uds.pendingfdscount) { TRACE0 (ctx, ASSUAN_LOG_SYSIO, "w32_receivefd", ctx, "no pending file descriptors"); return _assuan_error (ctx, GPG_ERR_ASS_GENERAL); } *fd = ctx->uds.pendingfds[0]; for (i=1; i < ctx->uds.pendingfdscount; i++) ctx->uds.pendingfds[i-1] = ctx->uds.pendingfds[i]; ctx->uds.pendingfdscount--; TRACE1 (ctx, ASSUAN_LOG_SYSIO, "w32_fdpass_recv", ctx, "received fd: %p", ctx->uds.pendingfds[0]); return 0; } ssize_t __assuan_read (assuan_context_t ctx, assuan_fd_t fd, void *buffer, size_t size) { int res; int ec = 0; if (ctx->flags.is_socket) { int tries = 3; again: ec = 0; res = recv (HANDLE2SOCKET (fd), buffer, size, 0); if (res == -1) ec = WSAGetLastError (); if (ec == WSAEWOULDBLOCK && tries--) { /* EAGAIN: Use select to wait for resources and try again. We do this 3 times and then give up. The higher level layer then needs to take care of EAGAIN. No need to specify a timeout - the socket is not expected to be in blocking mode. */ fd_set fds; FD_ZERO (&fds); FD_SET (HANDLE2SOCKET (fd), &fds); select (0, &fds, NULL, NULL, NULL); goto again; } } else { DWORD nread = 0; if (!ReadFile (fd, buffer, size, &nread, NULL)) { res = -1; ec = GetLastError (); } else res = nread; } if (res == -1) { switch (ec) { case WSAENOTSOCK: gpg_err_set_errno (EBADF); break; case WSAEWOULDBLOCK: gpg_err_set_errno (EAGAIN); break; case WSAECONNRESET: /* Due to the use of recv. */ case ERROR_BROKEN_PIPE: gpg_err_set_errno (EPIPE); break; default: gpg_err_set_errno (EIO); break; } } return res; } ssize_t __assuan_write (assuan_context_t ctx, assuan_fd_t fd, const void *buffer, size_t size) { int res; int ec = 0; if (ctx->flags.is_socket) { int tries = 3; again: ec = 0; res = send (HANDLE2SOCKET (fd), buffer, size, 0); if (res == -1) ec = WSAGetLastError (); if (ec == WSAEWOULDBLOCK && tries--) { /* EAGAIN: Use select to wait for resources and try again. We do this 3 times and then give up. The higher level layer then needs to take care of EAGAIN. No need to specify a timeout - the socket is not expected to be in blocking mode. */ fd_set fds; FD_ZERO (&fds); FD_SET (HANDLE2SOCKET (fd), &fds); select (0, NULL, &fds, NULL, NULL); goto again; } } else { DWORD nwrite; if (!WriteFile (fd, buffer, size, &nwrite, NULL)) { res = -1; ec = GetLastError (); } else res = (int)nwrite; } if (res == -1) { switch (ec) { case WSAENOTSOCK: gpg_err_set_errno (EBADF); break; case WSAEWOULDBLOCK: gpg_err_set_errno (EAGAIN); break; case ERROR_BROKEN_PIPE: case ERROR_NO_DATA: gpg_err_set_errno (EPIPE); break; default: gpg_err_set_errno (EIO); break; } } return res; } int __assuan_recvmsg (assuan_context_t ctx, assuan_fd_t fd, assuan_msghdr_t msg, int flags) { gpg_err_set_errno (ENOSYS); return -1; } int __assuan_sendmsg (assuan_context_t ctx, assuan_fd_t fd, assuan_msghdr_t msg, int flags) { gpg_err_set_errno (ENOSYS); return -1; } /* Build a command line for use with W32's CreateProcess. On success CMDLINE gets the address of a newly allocated string. */ static int build_w32_commandline (assuan_context_t ctx, const char * const *argv, char **cmdline) { int i, n; const char *s; char *buf, *p; *cmdline = NULL; n = 0; for (i=0; (s = argv[i]); i++) { n += strlen (s) + 1 + 2; /* (1 space, 2 quoting */ for (; *s; s++) if (*s == '\"') n++; /* Need to double inner quotes. */ } n++; buf = p = _assuan_malloc (ctx, n); if (! buf) return -1; for (i = 0; argv[i]; i++) { if (i) p = stpcpy (p, " "); if (! *argv[i]) /* Empty string. */ p = stpcpy (p, "\"\""); else if (strpbrk (argv[i], " \t\n\v\f\"")) { p = stpcpy (p, "\""); for (s = argv[i]; *s; s++) { *p++ = *s; if (*s == '\"') *p++ = *s; } *p++ = '\"'; *p = 0; } else p = stpcpy (p, argv[i]); } *cmdline= buf; return 0; } int __assuan_spawn (assuan_context_t ctx, assuan_pid_t *r_pid, const char *name, const char **argv, assuan_fd_t fd_in, assuan_fd_t fd_out, assuan_fd_t *fd_child_list, void (*atfork) (void *opaque, int reserved), void *atforkvalue, unsigned int flags) { SECURITY_ATTRIBUTES sec_attr; PROCESS_INFORMATION pi = { NULL, /* Returns process handle. */ 0, /* Returns primary thread handle. */ 0, /* Returns pid. */ 0 /* Returns tid. */ }; STARTUPINFOW si; assuan_fd_t fd; assuan_fd_t *fdp; char *cmdline; wchar_t *wcmdline = NULL; wchar_t *wname = NULL; HANDLE nullfd = INVALID_HANDLE_VALUE; int rc; /* fixme: Actually we should set the "_assuan_pipe_connect_pid" env variable. However this requires us to write a full environment handler, because the strings are expected in sorted order. The suggestion given in the MS Reference Library, to save the old value, change it, create process and restore it, is not thread safe. */ /* Build the command line. */ if (build_w32_commandline (ctx, argv, &cmdline)) return -1; /* Start the process. */ memset (&sec_attr, 0, sizeof sec_attr); sec_attr.nLength = sizeof sec_attr; sec_attr.bInheritHandle = FALSE; memset (&si, 0, sizeof si); si.cb = sizeof (si); si.dwFlags = STARTF_USESTDHANDLES; /* FIXME: Dup to nul if ASSUAN_INVALID_FD. */ si.hStdInput = fd_in; si.hStdOutput = fd_out; /* Dup stderr to /dev/null unless it is in the list of FDs to be passed to the child. */ fd = assuan_fd_from_posix_fd (fileno (stderr)); fdp = fd_child_list; if (fdp) { for (; *fdp != ASSUAN_INVALID_FD && *fdp != fd; fdp++) ; } if (!fdp || *fdp == ASSUAN_INVALID_FD) { nullfd = CreateFileW (L"nul", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (nullfd == INVALID_HANDLE_VALUE) { TRACE1 (ctx, ASSUAN_LOG_SYSIO, "__assuan_spawn", ctx, "can't open `nul': %s", _assuan_w32_strerror (ctx, -1)); _assuan_free (ctx, cmdline); gpg_err_set_errno (EIO); return -1; } si.hStdError = nullfd; } else si.hStdError = fd; /* Note: We inherit all handles flagged as inheritable. This seems to be a security flaw but there seems to be no way of selecting handles to inherit. A fix for this would be to use a helper process like we have in gpgme. Take care: CreateProcessW may modify wpgmname */ /* _assuan_log_printf ("CreateProcess, path=`%s' cmdline=`%s'\n", */ /* name, cmdline); */ if (name && !(wname = _assuan_utf8_to_wchar (name))) rc = 0; else if (!(wcmdline = _assuan_utf8_to_wchar (cmdline))) rc = 0; else rc = CreateProcessW (wname, /* Program to start. */ wcmdline, /* Command line arguments. */ &sec_attr, /* Process security attributes. */ &sec_attr, /* Thread security attributes. */ TRUE, /* Inherit handles. */ (CREATE_DEFAULT_ERROR_MODE | ((flags & 128)? DETACHED_PROCESS : 0) | GetPriorityClass (GetCurrentProcess ()) | CREATE_SUSPENDED), /* Creation flags. */ NULL, /* Environment. */ NULL, /* Use current drive/directory. */ &si, /* Startup information. */ &pi /* Returns process information. */ ); if (!rc) { TRACE1 (ctx, ASSUAN_LOG_SYSIO, "pipe_connect_w32", ctx, "CreateProcess failed%s: %s", _assuan_w32_strerror (ctx, -1)); free (wname); free (wcmdline); _assuan_free (ctx, cmdline); if (nullfd != INVALID_HANDLE_VALUE) CloseHandle (nullfd); gpg_err_set_errno (EIO); return -1; } free (wname); free (wcmdline); _assuan_free (ctx, cmdline); if (nullfd != INVALID_HANDLE_VALUE) CloseHandle (nullfd); ResumeThread (pi.hThread); CloseHandle (pi.hThread); /* _assuan_log_printf ("CreateProcess ready: hProcess=%p hThread=%p" */ /* " dwProcessID=%d dwThreadId=%d\n", */ /* pi.hProcess, pi.hThread, */ /* (int) pi.dwProcessId, (int) pi.dwThreadId); */ *r_pid = (assuan_pid_t) pi.hProcess; /* No need to modify peer process, as we don't change the handle names. However this also means we are not safe, as we inherit too many handles. Should use approach similar to gpgme and glib using a helper process. */ return 0; } /* FIXME: Add some sort of waitpid function that covers GPGME and gpg-agent's use of assuan. */ assuan_pid_t __assuan_waitpid (assuan_context_t ctx, assuan_pid_t pid, int nowait, int *status, int options) { - CloseHandle ((HANDLE) pid); - return 0; + int code; + DWORD exit_code; + + (void)ctx; + + if (nowait) + return 0; + + code = WaitForSingleObject ((HANDLE)pid, options? 0: INFINITE); + + if (code == WAIT_OBJECT_0) + { + if (status) + { + GetExitCodeProcess ((HANDLE)pid, &exit_code); + *status = (int)exit_code; + } + CloseHandle ((HANDLE)pid); + return pid; + } + else if (code == WAIT_TIMEOUT) + return 0; + else + return -1; } int __assuan_socketpair (assuan_context_t ctx, int namespace, int style, int protocol, assuan_fd_t filedes[2]) { gpg_err_set_errno (ENOSYS); return -1; } assuan_fd_t __assuan_socket (assuan_context_t ctx, int domain, int type, int proto) { assuan_fd_t res; res = SOCKET2HANDLE (socket (domain, type, proto)); if (res == SOCKET2HANDLE (INVALID_SOCKET)) gpg_err_set_errno (_assuan_sock_wsa2errno (WSAGetLastError ())); return res; } int __assuan_connect (assuan_context_t ctx, assuan_fd_t sock, struct sockaddr *addr, socklen_t length) { int res; res = connect (HANDLE2SOCKET (sock), addr, length); if (res < 0) gpg_err_set_errno (_assuan_sock_wsa2errno (WSAGetLastError ())); return res; } /* The default system hooks for assuan contexts. */ struct assuan_system_hooks _assuan_system_hooks = { 0, __assuan_usleep, __assuan_pipe, __assuan_close, __assuan_read, __assuan_write, __assuan_recvmsg, __assuan_sendmsg, __assuan_spawn, __assuan_waitpid, __assuan_socketpair, __assuan_socket, __assuan_connect };