diff options
Diffstat (limited to 'winsup/cygserver')
-rw-r--r-- | winsup/cygserver/client.cc | 570 | ||||
-rw-r--r-- | winsup/cygserver/cygserver.cc | 933 | ||||
-rw-r--r-- | winsup/cygserver/ipc.h | 84 | ||||
-rw-r--r-- | winsup/cygserver/process.cc | 658 | ||||
-rw-r--r-- | winsup/cygserver/shm.cc | 1379 | ||||
-rwxr-xr-x | winsup/cygserver/shm.h | 191 | ||||
-rw-r--r-- | winsup/cygserver/threaded_queue.cc | 500 | ||||
-rw-r--r-- | winsup/cygserver/transport.cc | 93 | ||||
-rw-r--r-- | winsup/cygserver/transport_pipes.cc | 387 | ||||
-rw-r--r-- | winsup/cygserver/transport_sockets.cc | 412 | ||||
-rw-r--r-- | winsup/cygserver/woutsup.h | 110 |
11 files changed, 3457 insertions, 1860 deletions
diff --git a/winsup/cygserver/client.cc b/winsup/cygserver/client.cc index 1df23ad9f..138c9ddc0 100644 --- a/winsup/cygserver/client.cc +++ b/winsup/cygserver/client.cc @@ -4,204 +4,526 @@ Written by Egor Duda <deo@logos-m.ru> - This file is part of Cygwin. +This file is part of Cygwin. - This software is a copyrighted work licensed under the terms of the - Cygwin license. Please consult the file "CYGWIN_LICENSE" for - details. */ +This software is a copyrighted work licensed under the terms of the +Cygwin license. Please consult the file "CYGWIN_LICENSE" for +details. */ +/* to allow this to link into cygwin and the .dll, a little magic is needed. */ #ifdef __OUTSIDE_CYGWIN__ -#undef __INSIDE_CYGWIN__ +#include "woutsup.h" #else #include "winsup.h" #endif -#ifndef __INSIDE_CYGWIN__ -#define debug_printf printf -#define api_fatal printf -#include <stdio.h> -#include <windows.h> -#endif -#include <sys/socket.h> +#include <assert.h> #include <errno.h> +#include <stdio.h> #include <unistd.h> -//#include "security.h" -#include "cygwin/cygserver_transport.h" -#include "cygwin/cygserver_transport_pipes.h" -#include "cygwin/cygserver_transport_sockets.h" + +#include "cygerrno.h" +#include "cygserver_shm.h" +#include "safe_memory.h" + #include "cygwin/cygserver.h" +#include "cygwin/cygserver_transport.h" + +int cygserver_running = CYGSERVER_UNKNOWN; // Nb: inherited by children. -/* 0 = untested, 1 = running, 2 = dead */ -int cygserver_running=CYGSERVER_UNKNOWN; -/* on by default during development. For release, we probably want off by default */ -int allow_daemon = TRUE; +/* On by default during development. For release, we probably want off + * by default. + */ +bool allow_daemon = true; // Nb: inherited by children. -client_request_get_version::client_request_get_version () : client_request (CYGSERVER_REQUEST_GET_VERSION, sizeof (version)) +client_request_get_version::client_request_get_version () + : client_request (CYGSERVER_REQUEST_GET_VERSION, &version, sizeof (version)) { - buffer = (char *)&version; + msglen (0); // No parameters for request. + + // verbose: syscall_printf ("created"); } -client_request_attach_tty::client_request_attach_tty () : client_request (CYGSERVER_REQUEST_ATTACH_TTY, sizeof (req)) +/* + * client_request_get_version::check_version () + * + * The major version and API version numbers must match exactly. An + * older than expected minor version number is accepted (as long as + * the first numbers match, that is). + */ + +bool +client_request_get_version::check_version () const { - buffer = (char *)&req; - req.pid = 0; - req.master_pid = 0; - req.from_master = NULL; - req.to_master = NULL; + const bool ok = (version.major == CYGWIN_SERVER_VERSION_MAJOR + && version.api == CYGWIN_SERVER_VERSION_API + && version.minor <= CYGWIN_SERVER_VERSION_MINOR); + + if (!ok) + syscall_printf (("incompatible version of cygwin server: " + "client version %d.%d.%d.%d, " + "server version %ld.%ld.%ld.%ld"), + CYGWIN_SERVER_VERSION_MAJOR, + CYGWIN_SERVER_VERSION_API, + CYGWIN_SERVER_VERSION_MINOR, + CYGWIN_SERVER_VERSION_PATCH, + version.major, + version.api, + version.minor, + version.patch); + + return ok; } -client_request_attach_tty::client_request_attach_tty (DWORD npid, DWORD nmaster_pid, HANDLE nfrom_master, HANDLE nto_master) : client_request (CYGSERVER_REQUEST_ATTACH_TTY, sizeof (req)) +#ifdef __INSIDE_CYGWIN__ + +client_request_attach_tty::client_request_attach_tty (DWORD nmaster_pid, + HANDLE nfrom_master, + HANDLE nto_master) + : client_request (CYGSERVER_REQUEST_ATTACH_TTY, &req, sizeof (req)) { - buffer = (char *)&req; - req.pid = npid; + req.pid = GetCurrentProcessId (); req.master_pid = nmaster_pid; req.from_master = nfrom_master; req.to_master = nto_master; -} -client_request_shutdown::client_request_shutdown () : client_request (CYGSERVER_REQUEST_SHUTDOWN, 0) -{ - buffer = NULL; + syscall_printf (("created: pid = %lu, master_pid = %lu, " + "from_master = %lu, to_master = %lu"), + req.pid, req.master_pid, req.from_master, req.to_master); } -client_request::client_request (cygserver_request_code id, ssize_t buffer_size) : header (id, buffer_size) +#else /* !__INSIDE_CYGWIN__ */ + +client_request_attach_tty::client_request_attach_tty () + : client_request (CYGSERVER_REQUEST_ATTACH_TTY, &req, sizeof (req)) { + // verbose: syscall_printf ("created"); } -client_request::~client_request () +#endif /* __INSIDE_CYGWIN__ */ + +/* + * client_request_attach_tty::send () + * + * Wraps the base method to provide error handling support. If the + * reply contains a body but is flagged as an error, close any handles + * that have been returned by cygserver and then discard the message + * body, i.e. the client either sees a successful result with handles + * or an unsuccessful result with no handles. + */ + +void +client_request_attach_tty::send (transport_layer_base * const conn) { + client_request::send (conn); + + if (msglen () && error_code ()) + { + if (from_master ()) + CloseHandle (from_master ()); + if (to_master ()) + CloseHandle (to_master ()); + msglen (0); + } } -client_request::operator class request_header () +client_request::header_t::header_t (const request_code_t request_code, + const size_t msglen) + : msglen (msglen), + request_code (request_code) { - return header; + assert (request_code >= 0 && request_code < CYGSERVER_REQUEST_LAST); } +// FIXME: also check write and read result for -1. + void -client_request::send (transport_layer_base *conn) +client_request::send (transport_layer_base * const conn) { - if (!conn) - return; - debug_printf("this=%p, conn=%p\n",this, conn); - ssize_t bytes_written, bytes_read; - debug_printf("header.cb = %ld\n",header.cb); - if ((bytes_written = conn->write ((char *)&header, sizeof (header))) - != sizeof(header) || (header.cb && - (bytes_written = conn->write (buffer, header.cb)) != header.cb)) + assert (conn); + assert (!(msglen () && !_buf)); // i.e., msglen () implies _buf + assert (msglen () <= _buflen); + + { + const ssize_t count = conn->write (&_header, sizeof (_header)); + + if (count != sizeof (_header)) + { + assert (errno); + error_code (errno); + syscall_printf (("request header write failure: " + "only %ld bytes sent of %ld, " + "error = %d(%lu)"), + count, sizeof (_header), + errno, GetLastError ()); + return; + } + } + + if (msglen ()) { - header.error_code = -1; - debug_printf ("bytes written != request size\n"); + const ssize_t count = conn->write (_buf, msglen ()); + + if (count == -1 || (size_t) count != msglen ()) + { + assert (errno); + error_code (errno); + syscall_printf (("request body write failure: " + "only %ld bytes sent of %ld, " + "error = %d(%lu)"), + count, msglen (), + errno, GetLastError ()); + return; + } + } + + // verbose: syscall_printf ("request sent (%ld + %ld bytes)", + // sizeof (_header), msglen ()); + + { + const ssize_t count = conn->read (&_header, sizeof (_header)); + + if (count != sizeof (_header)) + { + assert (errno); + error_code (errno); + syscall_printf (("reply header read failure: " + "only %ld bytes received of %ld, " + "error = %d(%lu)"), + count, sizeof (_header), + errno, GetLastError ()); + return; + } + } + + if (msglen () && !_buf) + { + system_printf ("no client buffer for reply body: %ld bytes needed", + msglen ()); + error_code (EINVAL); + return; + } + + if (msglen () > _buflen) + { + system_printf (("client buffer too small for reply body: " + "have %ld bytes and need %ld"), + _buflen, msglen ()); + error_code (EINVAL); return; } - debug_printf("Sent request, size (%ld)\n",bytes_written); + if (msglen ()) + { + const ssize_t count = conn->read (_buf, msglen ()); + + if (count == -1 || (size_t) count != msglen ()) + { + assert (errno); + error_code (errno); + syscall_printf (("reply body read failure: " + "only %ld bytes received of %ld, " + "error = %d(%lu)"), + count, msglen (), + errno, GetLastError ()); + return; + } + } + + // verbose: syscall_printf ("reply received (%ld + %ld bytes)", + // sizeof (_header), msglen ()); +} + +#ifndef __INSIDE_CYGWIN__ + +/* + * client_request::handle_request () + * + * A server-side method. + * + * This is a factory method for the client_request subclasses. It + * reads the incoming request header and, based on its request code, + * creates an instance of the appropriate class. + * + * FIXME: If the incoming packet is malformed, the server drops it on + * the floor. Should it try and generate some sort of reply for the + * client? As it is, the client will simply get a broken connection. + * + * FIXME: also check write and read result for -1. + */ + +/* static */ void +client_request::handle_request (transport_layer_base *const conn, + process_cache *const cache) +{ + // verbose: debug_printf ("about to read"); + + header_t header; + + { + const ssize_t count = conn->read (&header, sizeof (header)); + + if (count != sizeof (header)) + { + syscall_printf (("request header read failure: " + "only %ld bytes received of %ld, " + "error = %d(%lu)"), + count, sizeof (header), + errno, GetLastError ()); + return; + } + + // verbose: debug_printf ("got header (%ld)", count); + } - if ((bytes_read = conn->read ((char *)&header, sizeof (header))) - != sizeof (header) || (header.cb && - (bytes_read = conn->read (buffer, header.cb)) != header.cb)) + client_request *req = NULL; + + switch (header.request_code) { - header.error_code = -1; - debug_printf("failed reading response \n"); + case CYGSERVER_REQUEST_GET_VERSION: + req = safe_new0 (client_request_get_version); + break; + case CYGSERVER_REQUEST_SHUTDOWN: + req = safe_new0 (client_request_shutdown); + break; + case CYGSERVER_REQUEST_ATTACH_TTY: + req = safe_new0 (client_request_attach_tty); + break; + case CYGSERVER_REQUEST_SHM: + req = safe_new0 (client_request_shm); + break; + default: + syscall_printf ("unknown request code %d received: request ignored", + header.request_code); return; } - debug_printf ("completed ok\n"); + + assert (req); + + req->msglen (header.msglen); + req->handle (conn, cache); + + safe_delete (req); + +#ifndef DEBUGGING + printf ("."); // A little noise when we're being quiet. +#endif } -/* Oh, BTW: Fix the procedural basis and make this more intuitive. */ +#endif /* !__INSIDE_CYGWIN__ */ -int -cygserver_request (client_request * req) +client_request::client_request (request_code_t const id, + void * const buf, + size_t const buflen) + : _header (id, buflen), + _buf (buf), + _buflen (buflen) { - class transport_layer_base *transport; + assert ((!_buf && !_buflen) || (_buf && _buflen)); +} - if (!req || allow_daemon != TRUE) - return -1; +client_request::~client_request () +{} - /* dont' retry every request if the server's not there */ - if (cygserver_running==CYGSERVER_DEAD && req->header.req_id != CYGSERVER_REQUEST_GET_VERSION) - return -1; +int +client_request::make_request () +{ + assert (cygserver_running == CYGSERVER_UNKNOWN \ + || cygserver_running == CYGSERVER_OK \ + || cygserver_running == CYGSERVER_UNAVAIL); - transport = create_server_transport (); + if (cygserver_running == CYGSERVER_UNKNOWN) + cygserver_init (); - /* FIXME: have at most one connection per thread. use TLS to store the details */ - /* logic is: - * if not tlskey->conn, new conn, - * then; transport=conn; - */ - if (!transport->connect ()) + assert (cygserver_running == CYGSERVER_OK \ + || cygserver_running == CYGSERVER_UNAVAIL); + + /* Don't retry every request if the server's not there */ + if (cygserver_running == CYGSERVER_UNAVAIL) { - delete transport; + syscall_printf ("cygserver un-available"); + error_code (ENOSYS); return -1; } - debug_printf ("connected to server %p\n", transport); + transport_layer_base *const transport = create_server_transport (); + + assert (transport); + + if (transport->connect () == -1) + { + if (errno) + error_code (errno); + else + error_code (ENOSYS); + safe_delete (transport); + return -1; + } - req->send(transport); + // verbose: debug_printf ("connected to server %p", transport); - transport->close (); + send (transport); - delete transport; + safe_delete (transport); return 0; } -#if 0 -BOOL +#ifndef __INSIDE_CYGWIN__ + +/* + * client_request::handle () + * + * A server-side method. + * + * At this point, the header of an incoming request has been read and + * an appropriate client_request object constructed. This method has + * to read the request body into its buffer, if there is such a body, + * then perform the request and send back the results to the client. + * + * FIXME: If the incoming packet is malformed, the server drops it on + * the floor. Should it try and generate some sort of reply for the + * client? As it is, the client will simply get a broken connection. + * + * FIXME: also check write and read result for -1. + */ + +void +client_request::handle (transport_layer_base *const conn, + process_cache *const cache) +{ + if (msglen () && !_buf) + { + system_printf ("no buffer for request body: %ld bytes needed", + msglen ()); + error_code (EINVAL); + return; + } + + if (msglen () > _buflen) + { + system_printf (("buffer too small for request body: " + "have %ld bytes and need %ld"), + _buflen, msglen ()); + error_code (EINVAL); + return; + } + + if (msglen ()) + { + const ssize_t count = conn->read (_buf, msglen ()); + + if (count == -1 || (size_t) count != msglen ()) + { + assert (errno); + error_code (errno); + syscall_printf (("request body read failure: " + "only %ld bytes received of %ld, " + "error = %d(%lu)"), + count, msglen (), + errno, GetLastError ()); + return; + } + } + + // verbose: syscall_printf ("request received (%ld + %ld bytes)", + // sizeof (_header), msglen ()); + + error_code (0); // Overwrites the _header.request_code field. + + /* + * This is not allowed to fail. We must return ENOSYS at a minimum + * to the client. + */ + serve (conn, cache); + + { + const ssize_t count = conn->write (&_header, sizeof (_header)); + + if (count != sizeof (_header)) + { + assert (errno); + error_code (errno); + syscall_printf (("reply header write failure: " + "only %ld bytes sent of %ld, " + "error = %d(%lu)"), + count, sizeof (_header), + errno, GetLastError ()); + return; + } + } + + if (msglen ()) + { + const ssize_t count = conn->write (_buf, msglen ()); + + if (count == -1 || (size_t) count != msglen ()) + { + assert (errno); + error_code (errno); + syscall_printf (("reply body write failure: " + "only %ld bytes sent of %ld, " + "error = %d(%lu)"), + count, msglen (), + errno, GetLastError ()); + return; + } + } + + // verbose: syscall_printf ("reply sent (%ld + %ld bytes)", + // sizeof (_header), msglen ()); +} + +#endif /* !__INSIDE_CYGWIN__ */ + +bool check_cygserver_available () { - BOOL ret_val = FALSE; - HANDLE pipe = CreateFile (pipe_name, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - &sec_all_nih, - OPEN_EXISTING, - 0, - NULL); - if (pipe != INVALID_HANDLE_VALUE || GetLastError () != ERROR_PIPE_BUSY) - ret_val = TRUE; - - if (pipe && pipe != INVALID_HANDLE_VALUE) - CloseHandle (pipe); - - return (ret_val); + assert (cygserver_running == CYGSERVER_UNKNOWN \ + || cygserver_running == CYGSERVER_UNAVAIL); + + cygserver_running = CYGSERVER_OK; // For make_request (). + + client_request_get_version req; + + /* This indicates that we failed to connect to cygserver at all but + * that's fine as cygwin doesn't need it to be running. + */ + if (req.make_request () == -1) + return false; + + /* We connected to the server but something went wrong after that + * (in sending the message, in cygserver itself, or in receiving the + * reply). + */ + if (req.error_code ()) + { + syscall_printf ("failure in cygserver version request: %d", + req.error_code ()); + syscall_printf ("process will continue without cygserver support"); + return false; + } + + return req.check_version (); } -#endif void cygserver_init () { - int rc; - if (allow_daemon != TRUE) + if (!allow_daemon) { - cygserver_running = CYGSERVER_DEAD; + syscall_printf ("cygserver use disabled in client"); + cygserver_running = CYGSERVER_UNAVAIL; return; } - if (cygserver_running==CYGSERVER_OK) + assert (cygserver_running == CYGSERVER_UNKNOWN \ + || cygserver_running == CYGSERVER_OK \ + || cygserver_running == CYGSERVER_UNAVAIL); + + if (cygserver_running == CYGSERVER_OK) return; - client_request_get_version *req = - new client_request_get_version (); - - rc = cygserver_request (req); - delete req; - if (rc < 0) - cygserver_running = CYGSERVER_DEAD; - else if (rc > 0) - api_fatal ("error connecting to cygwin server. error: %d", rc); - else if (req->version.major != CYGWIN_SERVER_VERSION_MAJOR || - req->version.api != CYGWIN_SERVER_VERSION_API || - req->version.minor > CYGWIN_SERVER_VERSION_MINOR) - api_fatal ("incompatible version of cygwin server.\n\ - client version %d.%d.%d.%d, server version%ld.%ld.%ld.%ld", - CYGWIN_SERVER_VERSION_MAJOR, - CYGWIN_SERVER_VERSION_API, - CYGWIN_SERVER_VERSION_MINOR, - CYGWIN_SERVER_VERSION_PATCH, - req->version.major, - req->version.api, - req->version.minor, - req->version.patch); - else - cygserver_running = CYGSERVER_OK; + if (!check_cygserver_available ()) + cygserver_running = CYGSERVER_UNAVAIL; } diff --git a/winsup/cygserver/cygserver.cc b/winsup/cygserver/cygserver.cc index af9cee93e..0c0740379 100644 --- a/winsup/cygserver/cygserver.cc +++ b/winsup/cygserver/cygserver.cc @@ -4,61 +4,141 @@ Written by Egor Duda <deo@logos-m.ru> - This file is part of Cygwin. +This file is part of Cygwin. - This software is a copyrighted work licensed under the terms of the - Cygwin license. Please consult the file "CYGWIN_LICENSE" for - details. */ +This software is a copyrighted work licensed under the terms of the +Cygwin license. Please consult the file "CYGWIN_LICENSE" for +details. */ + +#include "woutsup.h" -#include <errno.h> -#include <stdio.h> -#include <unistd.h> -#include <windows.h> #include <sys/types.h> -#include <sys/socket.h> -#include <netdb.h> + +#include <assert.h> +#include <ctype.h> +#include <errno.h> +#include <getopt.h> #include <signal.h> +#include <stdio.h> #include <stdlib.h> -#include "wincap.h" -#include "cygwin_version.h" +#include <string.h> +#include <unistd.h> -#include "getopt.h" +#include "cygerrno.h" +#include "cygwin_version.h" -#include "cygwin/cygserver_transport.h" -#include "cygwin/cygserver_transport_pipes.h" -#include "cygwin/cygserver_transport_sockets.h" -#include "threaded_queue.h" -#include "cygwin/cygserver_process.h" #include "cygwin/cygserver.h" -#include "cygserver_shm.h" +#include "cygwin/cygserver_process.h" +#include "cygwin/cygserver_transport.h" -/* for quieter operation, set to 0 */ -#define DEBUG 0 -#define debug_printf if (DEBUG) printf +// Version string. +static const char version[] = "$Revision$"; -GENERIC_MAPPING access_mapping; -static class transport_layer_base *transport; +/* + * Support function for the XXX_printf () macros in "woutsup.h". + * Copied verbatim from "strace.cc". + */ +static int +getfunc (char *in_dst, const char *func) +{ + const char *p; + const char *pe; + char *dst = in_dst; + for (p = func; (pe = strchr (p, '(')); p = pe + 1) + if (isalnum ((int)pe[-1]) || pe[-1] == '_') + break; + else if (isspace ((int)pe[-1])) + { + pe--; + break; + } + if (!pe) + pe = strchr (func, '\0'); + for (p = pe; p > func; p--) + if (p != pe && *p == ' ') + { + p++; + break; + } + if (*p == '*') + p++; + while (p < pe) + *dst++ = *p++; + + *dst++ = ':'; + *dst++ = ' '; + *dst = '\0'; + + return dst - in_dst; +} + +/* + * Support function for the XXX_printf () macros in "woutsup.h". + */ +extern "C" void +__cygserver__printf (const char *const function, const char *const fmt, ...) +{ + const DWORD lasterror = GetLastError (); + const int lasterrno = errno; + + va_list ap; + + char *const buf = (char *) alloca (BUFSIZ); + + assert (buf); -DWORD request_count = 0; + int len = 0; -BOOL + if (function) + len += getfunc (buf, function); + + va_start (ap, fmt); + len += vsnprintf (buf + len, BUFSIZ - len, fmt, ap); + va_end (ap); + + len += snprintf (buf + len, BUFSIZ - len, "\n"); + + const int actual = (len > BUFSIZ ? BUFSIZ : len); + + write (2, buf, actual); + + errno = lasterrno; + SetLastError (lasterror); + + return; +} + +#ifdef DEBUGGING + +int __stdcall +__set_errno (const char *func, int ln, int val) +{ + debug_printf ("%s:%d val %d", func, ln, val); + return _impure_ptr->_errno = val; +} + +#endif /* DEBUGGING */ + +GENERIC_MAPPING access_mapping; + +static BOOL setup_privileges () { BOOL rc, ret_val; HANDLE hToken = NULL; TOKEN_PRIVILEGES sPrivileges; - rc = OpenProcessToken (GetCurrentProcess() , TOKEN_ALL_ACCESS , &hToken) ; + rc = OpenProcessToken (GetCurrentProcess () , TOKEN_ALL_ACCESS , &hToken) ; if (!rc) { - printf ("error opening process token (%lu)\n", GetLastError ()); + system_printf ("error opening process token (%lu)", GetLastError ()); ret_val = FALSE; goto out; } rc = LookupPrivilegeValue (NULL, SE_DEBUG_NAME, &sPrivileges.Privileges[0].Luid); if (!rc) { - printf ("error getting prigilege luid (%lu)\n", GetLastError ()); + system_printf ("error getting privilege luid (%lu)", GetLastError ()); ret_val = FALSE; goto out; } @@ -67,7 +147,8 @@ setup_privileges () rc = AdjustTokenPrivileges (hToken, FALSE, &sPrivileges, 0, NULL, NULL) ; if (!rc) { - printf ("error adjusting prigilege level. (%lu)\n", GetLastError ()); + system_printf ("error adjusting privilege level. (%lu)", + GetLastError ()); ret_val = FALSE; goto out; } @@ -89,179 +170,223 @@ check_and_dup_handle (HANDLE from_process, HANDLE to_process, HANDLE from_process_token, DWORD access, HANDLE from_handle, - HANDLE* to_handle_ptr, BOOL bInheritHandle = FALSE) + HANDLE *to_handle_ptr, BOOL bInheritHandle = FALSE) { HANDLE local_handle = NULL; int ret_val = EACCES; - char sd_buf [1024]; - PSECURITY_DESCRIPTOR sd = (PSECURITY_DESCRIPTOR) &sd_buf; - DWORD bytes_needed; - PRIVILEGE_SET ps; - DWORD ps_len = sizeof (ps); - BOOL status; if (from_process != GetCurrentProcess ()) { + if (!DuplicateHandle (from_process, from_handle, + GetCurrentProcess (), &local_handle, + 0, bInheritHandle, + DUPLICATE_SAME_ACCESS)) + { + system_printf ("error getting handle(%u) to server (%lu)", + (unsigned int)from_handle, GetLastError ()); + goto out; + } + } else + local_handle = from_handle; - if (!DuplicateHandle (from_process, from_handle, - GetCurrentProcess (), &local_handle, - 0, bInheritHandle, - DUPLICATE_SAME_ACCESS)) - { - printf ("error getting handle(%u) to server (%lu)\n", (unsigned int)from_handle, GetLastError ()); - goto out; - } -} else - local_handle = from_handle; - - if (!GetKernelObjectSecurity (local_handle, - OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, - sd, sizeof (sd_buf), &bytes_needed)) + if (!wincap.has_security ()) + assert (!from_process_token); + else { - printf ("error getting handle SD (%lu)\n", GetLastError ()); - goto out; - } + char sd_buf [1024]; + PSECURITY_DESCRIPTOR sd = (PSECURITY_DESCRIPTOR) &sd_buf; + DWORD bytes_needed; + PRIVILEGE_SET ps; + DWORD ps_len = sizeof (ps); + BOOL status; + + if (!GetKernelObjectSecurity (local_handle, + (OWNER_SECURITY_INFORMATION + | GROUP_SECURITY_INFORMATION + | DACL_SECURITY_INFORMATION), + sd, sizeof (sd_buf), &bytes_needed)) + { + system_printf ("error getting handle SD (%lu)", GetLastError ()); + goto out; + } - MapGenericMask (&access, &access_mapping); + MapGenericMask (&access, &access_mapping); - if (!AccessCheck (sd, from_process_token, access, &access_mapping, - &ps, &ps_len, &access, &status)) - { - printf ("error checking access rights (%lu)\n", GetLastError ()); - goto out; - } + if (!AccessCheck (sd, from_process_token, access, &access_mapping, + &ps, &ps_len, &access, &status)) + { + system_printf ("error checking access rights (%lu)", + GetLastError ()); + goto out; + } - if (!status) - { - printf ("access to object denied\n"); - goto out; + if (!status) + { + system_printf ("access to object denied"); + goto out; + } } if (!DuplicateHandle (from_process, from_handle, to_process, to_handle_ptr, access, bInheritHandle, 0)) { - printf ("error getting handle to client (%lu)\n", GetLastError ()); + system_printf ("error getting handle to client (%lu)", GetLastError ()); goto out; } - debug_printf ("Duplicated %p to %p\n", from_handle, *to_handle_ptr); + + // verbose: debug_printf ("Duplicated %p to %p", from_handle, *to_handle_ptr); ret_val = 0; -out: + out: if (local_handle && from_process != GetCurrentProcess ()) CloseHandle (local_handle); return (ret_val); } -void -client_request::serve (transport_layer_base *conn, class process_cache *cache) -{ - printf ("*****************************************\n" - "A call to the base client_request class has occured\n" - "This indicates a mismatch in a virtual function definition somewhere\n"); - exit (1); -} +/* + * client_request_attach_tty::serve () + */ void -client_request_attach_tty::serve(transport_layer_base *conn, class process_cache *cache) +client_request_attach_tty::serve (transport_layer_base *const conn, + process_cache *) { - HANDLE from_process_handle = NULL; - HANDLE to_process_handle = NULL; - HANDLE token_handle = NULL; - DWORD rc; + assert (conn); + + assert (!error_code ()); - if (header.cb != sizeof (req)) + if (!wincap.has_security ()) { - header.error_code = EINVAL; + syscall_printf ("operation only supported on systems with security"); + error_code (EINVAL); + msglen (0); return; } - debug_printf ("pid %ld:(%p,%p) -> pid %ld\n", req.master_pid, - req.from_master, req.to_master, - req.pid); - - debug_printf ("opening process %ld\n", req.master_pid); - from_process_handle = OpenProcess (PROCESS_DUP_HANDLE, FALSE, req.master_pid); - debug_printf ("opening process %ld\n", req.pid); - to_process_handle = OpenProcess (PROCESS_DUP_HANDLE, FALSE, req.pid); - if (!from_process_handle || !to_process_handle) + if (msglen () != sizeof (req)) { - printf ("error opening process (%lu)\n", GetLastError ()); - header.error_code = EACCES; - goto out; + syscall_printf ("bad request body length: expecting %lu bytes, got %lu", + sizeof (req), msglen ()); + error_code (EINVAL); + msglen (0); + return; } - debug_printf ("Impersonating client\n"); - conn->impersonate_client (); + msglen (0); // Until we fill in some fields. - debug_printf ("about to open thread token\n"); - rc = OpenThreadToken (GetCurrentThread (), - TOKEN_QUERY, - TRUE, - &token_handle); + // verbose: debug_printf ("pid %ld:(%p,%p) -> pid %ld", + // req.master_pid, req.from_master, req.to_master, + // req.pid); - debug_printf ("opened thread token, rc=%lu\n", rc); - conn->revert_to_self (); + // verbose: debug_printf ("opening process %ld", req.master_pid); - if (!rc) + const HANDLE from_process_handle = + OpenProcess (PROCESS_DUP_HANDLE, FALSE, req.master_pid); + + if (!from_process_handle) { - printf ("error opening thread token (%lu)\n", GetLastError ()); - header.error_code = EACCES; - goto out; + system_printf ("error opening `from' process, error = %lu", + GetLastError ()); + error_code (EACCES); + return; } - if (check_and_dup_handle (from_process_handle, to_process_handle, - token_handle, - GENERIC_READ, - req.from_master, - &req.from_master, TRUE) != 0) + // verbose: debug_printf ("opening process %ld", req.pid); + + const HANDLE to_process_handle = + OpenProcess (PROCESS_DUP_HANDLE, FALSE, req.pid); + + if (!to_process_handle) { - printf ("error duplicating from_master handle (%lu)\n", GetLastError ()); - header.error_code = EACCES; - goto out; + system_printf ("error opening `to' process, error = %lu", + GetLastError ()); + CloseHandle (from_process_handle); + error_code (EACCES); + return; } - if (req.to_master) + // verbose: debug_printf ("Impersonating client"); + conn->impersonate_client (); + + HANDLE token_handle = NULL; + + // verbose: debug_printf ("about to open thread token"); + const DWORD rc = OpenThreadToken (GetCurrentThread (), + TOKEN_QUERY, + TRUE, + &token_handle); + + // verbose: debug_printf ("opened thread token, rc=%lu", rc); + conn->revert_to_self (); + + if (!rc) { - if (check_and_dup_handle (from_process_handle, to_process_handle, - token_handle, - GENERIC_WRITE, - req.to_master, - &req.to_master, TRUE) != 0) - { - printf ("error duplicating to_master handle (%lu)\n", GetLastError ()); - header.error_code = EACCES; - goto out; - } + system_printf ("error opening thread token, error = %lu", + GetLastError ()); + CloseHandle (from_process_handle); + CloseHandle (to_process_handle); + error_code (EACCES); + return; } -#if DEBUG - printf ("%ld -> %ld(%p,%p)\n", req.master_pid, req.pid, - req.from_master, req.to_master); -#endif + // From this point on, a reply body is returned to the client. - header.error_code = 0; + const HANDLE from_master = req.from_master; + const HANDLE to_master = req.to_master; -out: - if (from_process_handle) - CloseHandle (from_process_handle); - if (to_process_handle) - CloseHandle (to_process_handle); - if (token_handle) - CloseHandle (token_handle); + req.from_master = NULL; + req.to_master = NULL; + + msglen (sizeof (req)); + + if (from_master) + if (check_and_dup_handle (from_process_handle, to_process_handle, + token_handle, + GENERIC_READ, + from_master, + &req.from_master, TRUE) != 0) + { + system_printf ("error duplicating from_master handle, error = %lu", + GetLastError ()); + error_code (EACCES); + } + + if (to_master) + if (check_and_dup_handle (from_process_handle, to_process_handle, + token_handle, + GENERIC_WRITE, + to_master, + &req.to_master, TRUE) != 0) + { + system_printf ("error duplicating to_master handle, error = %lu", + GetLastError ()); + error_code (EACCES); + } + + CloseHandle (from_process_handle); + CloseHandle (to_process_handle); + CloseHandle (token_handle); + + debug_printf ("%lu(%lu, %lu) -> %lu(%lu,%lu)", + req.master_pid, from_master, to_master, + req.pid, req.from_master, req.to_master); + + return; } void -client_request_get_version::serve(transport_layer_base *conn, class process_cache *cache) +client_request_get_version::serve (transport_layer_base *, process_cache *) { - if (header.cb != sizeof (version)) - { - header.error_code = EINVAL; - return; - } - header.error_code = 0; + assert (!error_code ()); + + if (msglen ()) + syscall_printf ("unexpected request body ignored: %lu bytes", msglen ()); + + msglen (sizeof (version)); + version.major = CYGWIN_SERVER_VERSION_MAJOR; version.api = CYGWIN_SERVER_VERSION_API; version.minor = CYGWIN_SERVER_VERSION_MINOR; @@ -270,280 +395,380 @@ client_request_get_version::serve(transport_layer_base *conn, class process_cach class server_request : public queue_request { - public: - server_request (transport_layer_base *newconn, class process_cache *newcache); - virtual void process (); - private: - char request_buffer [MAX_REQUEST_SIZE]; - transport_layer_base *conn; - class process_cache *cache; -}; +public: + server_request (transport_layer_base *const conn, process_cache *const cache) + : _conn (conn), _cache (cache) + {} -class server_process_param : public queue_process_param -{ - public: - transport_layer_base *transport; - server_process_param () : queue_process_param (false) {}; -}; + virtual ~server_request () + { + safe_delete (_conn); + } -class server_request_queue : public threaded_queue -{ - public: - class process_cache *cache; - void process_requests (transport_layer_base *transport); - virtual void add (transport_layer_base *conn); + virtual void process () + { + client_request::handle_request (_conn, _cache); + } + +private: + transport_layer_base *const _conn; + process_cache *const _cache; }; -class server_request_queue request_queue; -static DWORD WINAPI -request_loop (LPVOID LpParam) +class server_submission_loop : public queue_submission_loop { - class server_process_param *params = (server_process_param *) LpParam; - class server_request_queue *queue = (server_request_queue *) params->queue; - class transport_layer_base * transport = params->transport; - while (queue->active) +public: + server_submission_loop (threaded_queue *const queue, + transport_layer_base *const transport, + process_cache *const cache) + : queue_submission_loop (queue, false), + _transport (transport), + _cache (cache) { - transport_layer_base * new_conn = transport->accept (); - /* FIXME: this is a little ugly. What we really want is to wait on two objects: - * one for the pipe/socket, and one for being told to shutdown. Otherwise - * this will stay a problem (we won't actually shutdown until the request - * _AFTER_ the shutdown request. And sending ourselves a request is ugly - */ - if (new_conn && queue->active) - queue->add (new_conn); + assert (_transport); + assert (_cache); } - return 0; -} -/* TODO: check we are not being asked to service a already serviced transport */ +private: + transport_layer_base *const _transport; + process_cache *const _cache; + + virtual void request_loop (); +}; + +/* FIXME: this is a little ugly. What we really want is to wait on + * two objects: one for the pipe/socket, and one for being told to + * shutdown. Otherwise this will stay a problem (we won't actually + * shutdown until the request _AFTER_ the shutdown request. And + * sending ourselves a request is ugly + */ void -server_request_queue::process_requests (transport_layer_base *transport) +server_submission_loop::request_loop () { - class server_process_param *params = new server_process_param; - params->transport = transport; - threaded_queue::process_requests (params, request_loop); + /* I'd like the accepting thread's priority to be above any "normal" + * thread in the system to avoid overflowing the listen queue (for + * sockets; similar issues exist for named pipes); but, for example, + * a normal priority thread in a foregrounded process is boosted to + * THREAD_PRIORITY_HIGHEST (AFAICT). Thus try to set the current + * thread's priority to a level one above that. This fails on + * win9x/ME so assume any failure in that call is due to that and + * simply call again at one priority level lower. + */ + if (!SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST + 1)) + if (!SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST)) + debug_printf ("failed to raise accept thread priority, error = %lu", + GetLastError ()); + + while (_running) + { + bool recoverable = false; + transport_layer_base *const conn = _transport->accept (&recoverable); + if (!conn && !recoverable) + { + system_printf ("fatal error on IPC transport: closing down"); + return; + } + // EINTR probably implies a shutdown request; so back off for a + // moment to let the main thread take control, otherwise the + // server spins here receiving EINTR repeatedly since the signal + // handler in the main thread doesn't get a chance to be called. + if (!conn && errno == EINTR) + { + if (!SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_NORMAL)) + debug_printf ("failed to reset thread priority, error = %lu", + GetLastError ()); + + Sleep (0); + if (!SetThreadPriority (GetCurrentThread (), + THREAD_PRIORITY_HIGHEST + 1)) + if (!SetThreadPriority (GetCurrentThread (), + THREAD_PRIORITY_HIGHEST)) + debug_printf ("failed to raise thread priority, error = %lu", + GetLastError ()); + } + if (conn) + _queue->add (safe_new (server_request, conn, _cache)); + } +} + +client_request_shutdown::client_request_shutdown () + : client_request (CYGSERVER_REQUEST_SHUTDOWN) +{ + // verbose: syscall_printf ("created"); } void -client_request_shutdown::serve (transport_layer_base *conn, class process_cache *cache) +client_request_shutdown::serve (transport_layer_base *, process_cache *) { + assert (!error_code ()); + + if (msglen ()) + syscall_printf ("unexpected request body ignored: %lu bytes", msglen ()); + /* FIXME: link upwards, and then this becomes a trivial method call to * only shutdown _this queue_ */ - /* tell the main thread to shutdown */ - request_queue.active=false; + + kill (getpid (), SIGINT); + + msglen (0); } -server_request::server_request (transport_layer_base *newconn, class process_cache *newcache) +static sig_atomic_t shutdown_server = false; + +static void +handle_signal (const int signum) { - conn = newconn; - cache = newcache; + /* any signal makes us die :} */ + + shutdown_server = true; } -void -server_request::process () +/* + * print_usage () + */ + +static void +print_usage (const char *const pgm) { - ssize_t bytes_read, bytes_written; - struct request_header* req_ptr = (struct request_header*) &request_buffer; - client_request *req = NULL; - debug_printf ("about to read\n"); + printf ("Usage: %s [OPTIONS]\n", pgm); + printf (" -c, --cleanup-threads number of cleanup threads to use\n"); + printf (" -h, --help output usage information and exit\n"); + printf (" -r, --request-threads number of request threads to use\n"); + printf (" -s, --shutdown shutdown the daemon\n"); + printf (" -v, --version output version information and exit\n"); +} - bytes_read = conn->read (request_buffer, sizeof (struct request_header)); - if (bytes_read != sizeof (struct request_header)) - { - printf ("error reading from connection (%lu)\n", GetLastError ()); - goto out; - } - debug_printf ("got header (%ld)\n", bytes_read); +/* + * print_version () + */ - switch (req_ptr->req_id) - { - case CYGSERVER_REQUEST_GET_VERSION: - req = new client_request_get_version (); break; - case CYGSERVER_REQUEST_ATTACH_TTY: - req = new client_request_attach_tty (); break; - case CYGSERVER_REQUEST_SHUTDOWN: - req = new client_request_shutdown (); break; - case CYGSERVER_REQUEST_SHM_GET: - req = new client_request_shm (); break; - default: - req = new client_request (CYGSERVER_REQUEST_INVALID, 0); - req->header.error_code = ENOSYS; - debug_printf ("Bad client request - returning ENOSYS\n"); - } +static void +print_version (const char *const pgm) +{ + char *vn = NULL; - if (req->header.cb != req_ptr->cb) - { - debug_printf ("Mismatch in request buffer sizes\n"); - goto out; - } + const char *const colon = strchr (version, ':'); - if (req->header.cb) + if (!colon) { - - bytes_read = conn->read (req->buffer, req->header.cb); - if (bytes_read != req->header.cb) - { - debug_printf ("error reading from connection (%lu)\n", GetLastError ()); - goto out; - } - debug_printf ("got body (%ld)\n",bytes_read); + vn = strdup ("?"); } + else + { + vn = strdup (colon + 2); // Skip ": " - /* this is not allowed to fail. We must return ENOSYS at a minimum to the client */ - req->serve (conn, cache); + char *const spc = strchr (vn, ' '); - if ((bytes_written = conn->write ((char *)&req->header, sizeof (req->header))) - != sizeof(req->header) || (req->header.cb && - (bytes_written = conn->write (req->buffer, req->header.cb)) != req->header.cb)) - { - req->header.error_code = -1; - printf ("error writing to connection (%lu)\n", GetLastError ()); - goto out; + if (spc) + *spc = '\0'; } - debug_printf("Sent reply, size (%ld)\n",bytes_written); - printf ("."); - -out: - conn->close (); - delete conn; - if (req) - delete (req); + char buf[200]; + snprintf (buf, sizeof (buf), "%d.%d.%d(%d.%d/%d/%d)-(%d.%d.%d.%d) %s", + cygwin_version.dll_major / 1000, + cygwin_version.dll_major % 1000, + cygwin_version.dll_minor, + cygwin_version.api_major, + cygwin_version.api_minor, + cygwin_version.shared_data, + CYGWIN_SERVER_VERSION_MAJOR, + CYGWIN_SERVER_VERSION_API, + CYGWIN_SERVER_VERSION_MINOR, + CYGWIN_SERVER_VERSION_PATCH, + cygwin_version.mount_registry, + cygwin_version.dll_build_date); + + printf ("%s (cygwin) %s\n", pgm, vn); + printf ("API version %s\n", buf); + printf ("Copyright 2001, 2002 Red Hat, Inc.\n"); + printf ("Compiled on %s\n", __DATE__); + + free (vn); } -void -server_request_queue::add (transport_layer_base *conn) -{ - /* safe to not "Try" because workers don't hog this, they wait on the event - */ - /* every derived ::add must enter the section! */ - EnterCriticalSection (&queuelock); - if (!running) - { - conn->close (); - delete conn; - LeaveCriticalSection (&queuelock); - return; - } - queue_request * listrequest = new server_request (conn, cache); - threaded_queue::add (listrequest); - LeaveCriticalSection (&queuelock); -} +/* + * main () + */ -void -handle_signal (int signal) +int +main (const int argc, char *argv[]) { - /* any signal makes us die :} */ - /* FIXME: link upwards, and then this becomes a trivial method call to - * only shutdown _this queue_ - */ - /* tell the main thread to shutdown */ - request_queue.active=false; -} + const struct option longopts[] = { + {"cleanup-threads", required_argument, NULL, 'c'}, + {"help", no_argument, NULL, 'h'}, + {"request-threads", required_argument, NULL, 'r'}, + {"shutdown", no_argument, NULL, 's'}, + {"version", no_argument, NULL, 'v'}, + {0, no_argument, NULL, 0} + }; -struct option longopts[] = { - {"shutdown", no_argument, NULL, 's'}, - {0, no_argument, NULL, 0} -}; + const char opts[] = "c:hr:sv"; -char opts[] = "s"; + int cleanup_threads = 2; + int request_threads = 10; + bool shutdown = false; -int -main (int argc, char **argv) -{ - int shutdown=0; - char i; + const char *pgm = NULL; + + if (!(pgm = strrchr (*argv, '\\')) && !(pgm = strrchr (*argv, '/'))) + pgm = *argv; + else + pgm++; - while ((i = getopt_long (argc, argv, opts, longopts, NULL)) != EOF) - switch (i) + wincap.init (); + if (wincap.has_security ()) + setup_privileges (); + + int opt; + + while ((opt = getopt_long (argc, argv, opts, longopts, NULL)) != EOF) + switch (opt) { - case 's': - shutdown = 1; + case 'c': + cleanup_threads = atoi (optarg); + if (cleanup_threads <= 0) + { + fprintf (stderr, + "%s: number of cleanup threads must be positive\n", + pgm); + exit (1); + } + break; + + case 'h': + print_usage (pgm); + return 0; + + case 'r': + request_threads = atoi (optarg); + if (request_threads <= 0) + { + fprintf (stderr, + "%s: number of request threads must be positive\n", + pgm); + exit (1); + } break; - default: + + case 's': + shutdown = true; break; - /*NOTREACHED*/ + + case 'v': + print_version (pgm); + return 0; + + case '?': + fprintf (stderr, "Try `%s --help' for more information.\n", pgm); + exit (1); } - wincap.init(); - if (wincap.has_security ()) - setup_privileges (); - transport = create_server_transport (); + if (optind != argc) + { + fprintf (stderr, "%s: too many arguments\n", pgm); + exit (1); + } if (shutdown) { - if (!transport->connect()) + /* Setting `cygserver_running' stops the request code making a + * version request, which is not much to the point. + */ + cygserver_running = CYGSERVER_OK; + + client_request_shutdown req; + + if (req.make_request () == -1 || req.error_code ()) { - printf ("couldn't establish connection with server\n"); + fprintf (stderr, "%s: shutdown request failed: %s\n", + pgm, strerror (req.error_code ())); exit (1); } - client_request_shutdown *request = - new client_request_shutdown (); - request->send (transport); - transport->close(); - delete transport; - delete request; - exit(0); + + // FIXME: It would be nice to wait here for the daemon to exit. + + return 0; } - char version[200]; - /* Cygwin dll release */ - snprintf (version, 200, "%d.%d.%d(%d.%d/%d/%d)-(%d.%d.%d.%d) %s", - cygwin_version.dll_major / 1000, - cygwin_version.dll_major % 1000, - cygwin_version.dll_minor, - cygwin_version.api_major, - cygwin_version.api_minor, - cygwin_version.shared_data, - CYGWIN_SERVER_VERSION_MAJOR, - CYGWIN_SERVER_VERSION_API, - CYGWIN_SERVER_VERSION_MINOR, - CYGWIN_SERVER_VERSION_PATCH, - cygwin_version.mount_registry, - cygwin_version.dll_build_date); +#define SIGHANDLE(SIG) \ + do \ + { \ + struct sigaction act; \ + \ + act.sa_handler = &handle_signal; \ + act.sa_mask = 0; \ + act.sa_flags = 0; \ + \ + if (sigaction (SIG, &act, NULL) == -1) \ + { \ + system_printf ("failed to install handler for " #SIG ": %s", \ + strerror (errno)); \ + exit (1); \ + } \ + } while (false) + + SIGHANDLE (SIGHUP); + SIGHANDLE (SIGINT); + SIGHANDLE (SIGTERM); + + print_version (pgm); setbuf (stdout, NULL); - printf ("daemon version %s starting up", version); - if (signal (SIGQUIT, handle_signal) == SIG_ERR) + printf ("daemon starting up"); + + threaded_queue request_queue (request_threads); + printf ("."); + + transport_layer_base *const transport = create_server_transport (); + assert (transport); + printf ("."); + + process_cache cache (cleanup_threads); + printf ("."); + + server_submission_loop submission_loop (&request_queue, transport, &cache); + printf ("."); + + request_queue.add_submission_loop (&submission_loop); + printf ("."); + + if (transport->listen () == -1) { - printf ("\ncould not install signal handler (%d)- aborting startup\n", errno); exit (1); } printf ("."); - transport->listen (); - printf ("."); - class process_cache cache (2); - request_queue.initial_workers = 10; - request_queue.cache = &cache; - request_queue.create_workers (); - printf ("."); - request_queue.process_requests (transport); + + cache.start (); printf ("."); - cache.create_workers (); + + request_queue.start (); printf ("."); - cache.process_requests (); - printf (".complete\n"); - /* TODO: wait on multiple objects - the thread handle for each request loop + - * all the process handles. This should be done by querying the request_queue and - * the process cache for all their handles, and then waiting for (say) 30 seconds. - * after that we recreate the list of handles to wait on, and wait again. - * the point of all this abstraction is that we can trivially server both sockets - * and pipes simply by making a new transport, and then calling - * request_queue.process_requests (transport2); + + printf ("complete\n"); + + /* TODO: wait on multiple objects - the thread handle for each + * request loop + all the process handles. This should be done by + * querying the request_queue and the process cache for all their + * handles, and then waiting for (say) 30 seconds. after that we + * recreate the list of handles to wait on, and wait again. the + * point of all this abstraction is that we can trivially server + * both sockets and pipes simply by making a new transport, and then + * calling request_queue.process_requests (transport2); */ /* WaitForMultipleObjects abort && request_queue && process_queue && signal -- if signal event then retrigger it - */ - while (1 && request_queue.active) - { - sleep (1); - } - printf ("\nShutdown request recieved - new requests will be denied\n"); - request_queue.cleanup (); + */ + while (!shutdown_server && request_queue.running () && cache.running ()) + pause (); + + printf ("\nShutdown request received - new requests will be denied\n"); + request_queue.stop (); printf ("All pending requests processed\n"); - transport->close (); + safe_delete (transport); printf ("No longer accepting requests - cygwin will operate in daemonless mode\n"); - cache.cleanup (); + cache.stop (); printf ("All outstanding process-cache activities completed\n"); printf ("daemon shutdown\n"); + + return 0; } diff --git a/winsup/cygserver/ipc.h b/winsup/cygserver/ipc.h new file mode 100644 index 000000000..0d0ebbc76 --- /dev/null +++ b/winsup/cygserver/ipc.h @@ -0,0 +1,84 @@ +/* cygserver_ipc.h + + Copyright 2002 Red Hat, Inc. + + Originally written by Conrad Scott <conrad.scott@dsl.pipex.com> + +This file is part of Cygwin. + +This software is a copyrighted work licensed under the terms of the +Cygwin license. Please consult the file "CYGWIN_LICENSE" for +details. */ + +#ifndef __CYGSERVER_IPC_H__ +#define __CYGSERVER_IPC_H__ + +#include <assert.h> +#include <limits.h> /* For OPEN_MAX. */ + +/* + * The sysv ipc id's (msgid, semid, shmid) are integers arranged such + * that they no subsystem will generate the same id as some other + * subsystem; nor do these ids overlap file descriptors (the other + * common integer ids). Since Cygwin can allocate more than OPEN_MAX + * file descriptors, it can't be guaranteed not to overlap, but it + * should help catch some errors. + * + * msgid's: OPEN_MAX, OPEN_MAX + 3, OPEN_MAX + 6, . . . + * semid's: OPEN_MAX + 1, OPEN_MAX + 4, OPEN_MAX + 7, . . . + * shmid's: OPEN_MAX + 2, OPEN_MAX + 5, OPEN_MAX + 8, . . . + * + * To further ensure that ids are unique, if ipc objects are created + * and destroyed and then re-created, they are given new ids by + * munging the basic id (as above) with a sequence number. + * + * Internal ipc id's, which are 0, 1, ... within each subsystem (and + * not munged with a sequence number), are used solely by the ipcs(8) + * interface. + */ + +enum ipc_subsys_t + { + IPC_MSGOP = 0, + IPC_SEMOP = 1, + IPC_SHMOP = 2, + IPC_SUBSYS_COUNT + }; + +/* + * IPCMNI - The absolute maximum number of simultaneous ipc ids for + * any one subsystem. + */ + +enum + { + IPCMNI = 0x10000 // Must be a power of two. + }; + +inline int +ipc_int2ext (const int intid, const ipc_subsys_t subsys, long & sequence) +{ + assert (0 <= intid && intid < IPCMNI); + + const long tmp = InterlockedIncrement (&sequence); + + return (((tmp & 0x7fff) << 16) + | (OPEN_MAX + (intid * IPC_SUBSYS_COUNT) + subsys)); +} + +inline int +ipc_ext2int_subsys (const int extid) +{ + return ((extid & (IPCMNI - 1)) - OPEN_MAX) % IPC_SUBSYS_COUNT; +} + +inline int +ipc_ext2int (const int extid, const ipc_subsys_t subsys) +{ + if (ipc_ext2int_subsys (extid) != subsys) + return -1; + else + return ((extid & (IPCMNI - 1)) - OPEN_MAX) / IPC_SUBSYS_COUNT; +} + +#endif /* __CYGSERVER_IPC_H__ */ diff --git a/winsup/cygserver/process.cc b/winsup/cygserver/process.cc index dd13f37fb..7118bbcd9 100644 --- a/winsup/cygserver/process.cc +++ b/winsup/cygserver/process.cc @@ -4,385 +4,429 @@ Written by Robert Collins <rbtcollins@hotmail.com> - This file is part of Cygwin. +This file is part of Cygwin. - This software is a copyrighted work licensed under the terms of the - Cygwin license. Please consult the file "CYGWIN_LICENSE" for - details. */ +This software is a copyrighted work licensed under the terms of the +Cygwin license. Please consult the file "CYGWIN_LICENSE" for +details. */ +#include "woutsup.h" + +#include <sys/types.h> + +#include <assert.h> #include <errno.h> -#include <stdio.h> -#include <unistd.h> #include <stdlib.h> -#include <windows.h> -#include <sys/types.h> -#include <sys/socket.h> -#include <netdb.h> -#include "wincap.h" -#include <pthread.h> -#include <threaded_queue.h> -#include <cygwin/cygserver_process.h> - -#define debug_printf if (DEBUG) printf -#define DEBUG 1 - -/* the cache structures and classes are designed for one cache per server process. - * To make multiple process caches, a redesign will be needed - */ -/* process cache */ -process_cache::process_cache (unsigned int num_initial_workers): -head (NULL) +#include "cygerrno.h" + +#include "cygwin/cygserver_process.h" + +/*****************************************************************************/ + +#define elements(ARRAY) (sizeof (ARRAY) / sizeof (*ARRAY)) + +/*****************************************************************************/ + +process_cleanup::~process_cleanup () { - /* there can only be one */ - InitializeCriticalSection (&cache_write_access); - if ((cache_add_trigger = CreateEvent (NULL, FALSE, FALSE, NULL)) == NULL) - { - printf ("Failed to create cache add trigger (%lu), terminating\n", - GetLastError ()); - exit (1); - } - initial_workers = num_initial_workers; + safe_delete (_process); } -process_cache::~process_cache () +void +process_cleanup::process () { + _process->cleanup (); } -class process * -process_cache::process (long pid) +/*****************************************************************************/ + +/* cleanup_routine */ +cleanup_routine::~cleanup_routine () { - class process *entry = head; - /* TODO: make this more granular, so a search doesn't involve the write lock */ - EnterCriticalSection (&cache_write_access); - if (!entry) +} + +/*****************************************************************************/ + +process::process (const pid_t cygpid, const DWORD winpid) + : _cygpid (cygpid), + _winpid (winpid), + _hProcess (NULL), + _cleaning_up (false), + _exit_status (STILL_ACTIVE), + _routines_head (NULL), + _next (NULL) +{ + _hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE, winpid); + if (!_hProcess) { - entry = new class process (pid); - entry->next = - (class process *) InterlockedExchangePointer (&head, entry); - PulseEvent (cache_add_trigger); + system_printf ("unable to obtain handle for new cache process %d(%lu)", + _cygpid, _winpid); + _hProcess = INVALID_HANDLE_VALUE; + _exit_status = 0; } else - { - while (entry->winpid != pid && entry->next) - entry = entry->next; - if (entry->winpid != pid) - { - class process *new_entry = new class process (pid); - new_entry->next = - (class process *) InterlockedExchangePointer (&entry->next, - new_entry); - entry = new_entry; - PulseEvent (cache_add_trigger); - } - } - LeaveCriticalSection (&cache_write_access); - return entry; + debug_printf ("got handle %p for new cache process %d(%lu)", + _hProcess, _cygpid, _winpid); + InitializeCriticalSection (&_access); } -static DWORD WINAPI -request_loop (LPVOID LpParam) +process::~process () { - class process_process_param *params = (process_process_param *) LpParam; - return params->request_loop (); + DeleteCriticalSection (&_access); + (void) CloseHandle (_hProcess); } -void -process_cache::process_requests () +/* No need to be thread-safe as this is only ever called by + * process_cache::remove_process (). If it has to be made thread-safe + * later on, it should not use the `access' critical section as that + * is held by the client request handlers for an arbitrary length of + * time, i.e. while they do whatever processing is required for a + * client request. + */ +DWORD +process::check_exit_code () { - class process_process_param *params = new process_process_param; - threaded_queue::process_requests (params, request_loop); + if (_hProcess && _hProcess != INVALID_HANDLE_VALUE + && _exit_status == STILL_ACTIVE + && !GetExitCodeProcess (_hProcess, &_exit_status)) + { + system_printf ("failed to retrieve exit code for %d(%lu), error = %lu", + _cygpid, _winpid, GetLastError ()); + _hProcess = INVALID_HANDLE_VALUE; + } + return _exit_status; } -void -process_cache::add_task (class process * theprocess) +bool +process::add (cleanup_routine *const entry) { - /* safe to not "Try" because workers don't hog this, they wait on the event - */ - /* every derived ::add must enter the section! */ - EnterCriticalSection (&queuelock); - queue_request *listrequest = new process_cleanup (theprocess); - threaded_queue::add (listrequest); - LeaveCriticalSection (&queuelock); -} + assert (entry); -/* NOT fully MT SAFE: must be called by only one thread in a program */ -void -process_cache::remove_process (class process *theprocess) -{ - class process *entry = head; - /* unlink */ - EnterCriticalSection (&cache_write_access); - if (entry == theprocess) + bool res = false; + EnterCriticalSection (&_access); + + if (!_cleaning_up) { - entry = (class process *) InterlockedExchangePointer (&head, theprocess->next); - if (entry != theprocess) - { - printf ("Bug encountered, process cache corrupted\n"); - exit (1); - } + entry->_next = _routines_head; + _routines_head = entry; + res = true; } - else + + LeaveCriticalSection (&_access); + return res; +} + +bool +process::remove (const cleanup_routine *const entry) +{ + assert (entry); + + bool res = false; + EnterCriticalSection (&_access); + + if (!_cleaning_up) { - while (entry->next && entry->next != theprocess) - entry = entry->next; - class process *temp = (class process *) InterlockedExchangePointer (&entry->next, theprocess->next); - if (temp != theprocess) + cleanup_routine *previous = NULL; + + for (cleanup_routine *ptr = _routines_head; + ptr; + previous = ptr, ptr = ptr->_next) { - printf ("Bug encountered, process cache corrupted\n"); - exit (1); + if (*ptr == *entry) + { + if (previous) + previous->_next = ptr->_next; + else + _routines_head = ptr->_next; + + safe_delete (ptr); + res = true; + break; + } } } - LeaveCriticalSection (&cache_write_access); - /* Process any cleanup tasks */ - add_task (theprocess); + + LeaveCriticalSection (&_access); + return res; } -/* copy <= max_copy HANDLEs to dest[], starting at an offset into _our list_ of - * begin_at. (Ie begin_at = 5, the first copied handle is still written to dest[0] - * NOTE: Thread safe, but not thread guaranteed - a newly added process may be missed. - * Who cares - It'll get caught the next time. +/* This is single threaded. It's called after the process is removed + * from the cache, but inserts may be attemped by worker threads that + * have a pointer to it. */ -int -process_cache::handle_snapshot (HANDLE * hdest, class process ** edest, - ssize_t max_copy, int begin_at) +void +process::cleanup () { - /* TODO:? grab a delete-lock, to prevent deletes during this process ? */ - class process *entry = head; - int count = begin_at; - /* skip begin_at entries */ - while (entry && count) - { - if (entry->exit_code () == STILL_ACTIVE) - count--; - entry = entry->next; - } - /* hit the end of the list within begin_at entries */ - if (count) - return 0; - HANDLE *hto = hdest; - class process **eto = edest; - while (entry && count < max_copy) + EnterCriticalSection (&_access); + assert (!is_active ()); + assert (!_cleaning_up); + InterlockedExchange (&_cleaning_up, true); + cleanup_routine *entry = _routines_head; + _routines_head = NULL; + LeaveCriticalSection (&_access); + + while (entry) { - /* hack */ - if (entry->exit_code () == STILL_ACTIVE) - { - *hto = entry->handle (); - *eto = entry; - count++; - hto++; - eto++; - } - entry = entry->next; + cleanup_routine *const ptr = entry; + entry = entry->_next; + ptr->cleanup (this); + safe_delete (ptr); } - return count; } -/* process's */ -/* global process crit section */ -static CRITICAL_SECTION process_access; -static pthread_once_t process_init; +/*****************************************************************************/ void -do_process_init (void) +process_cache::submission_loop::request_loop () { - InitializeCriticalSection (&process_access); - /* we don't have a cache shutdown capability today */ + assert (this); + assert (_cache); + assert (_interrupt_event); + + while (_running) + _cache->wait_for_processes (_interrupt_event); } -process::process (long pid): -winpid (pid), next (NULL), cleaning_up (0), head (NULL), _exit_status (STILL_ACTIVE) +/*****************************************************************************/ + +process_cache::process_cache (const unsigned int initial_workers) + : _queue (initial_workers), + _submitter (this, &_queue), // true == interruptible + _processes_count (0), + _processes_head (NULL), + _cache_add_trigger (NULL) { - pthread_once (&process_init, do_process_init); - EnterCriticalSection (&process_access); - thehandle = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid); - if (!thehandle) + /* there can only be one */ + InitializeCriticalSection (&_cache_write_access); + + _cache_add_trigger = CreateEvent (NULL, // SECURITY_ATTRIBUTES + FALSE, // Auto-reset + FALSE, // Initially non-signalled + NULL); // Anonymous + + if (!_cache_add_trigger) { - printf ("unable to obtain handle for new cache process %ld\n", pid); - thehandle = INVALID_HANDLE_VALUE; + system_printf ("failed to create cache add trigger, error = %lu", + GetLastError ()); + abort (); } - debug_printf ("Got handle %p for new cache process %ld\n", thehandle, pid); - InitializeCriticalSection (&access); - LeaveCriticalSection (&process_access); -} -process::~process () -{ - DeleteCriticalSection (&access); + _queue.add_submission_loop (&_submitter); } -HANDLE -process::handle () +process_cache::~process_cache () { -// DWORD exitstate = exit_code (); -// if (exitstate == STILL_ACTIVE) - return thehandle; - - /* FIXME: call the cleanup list ? */ - -// CloseHandle (thehandle); -// debug_printf ("Process id %ld has terminated, attempting to open a new handle\n", -// winpid); -// thehandle = OpenProcess (PROCESS_ALL_ACCESS, FALSE, winpid); -// debug_printf ("Got handle %p when refreshing cache process %ld\n", thehandle, winpid); -// /* FIXME: what if OpenProcess fails ? */ -// if (thehandle) -// { -// _exit_status = STILL_ACTIVE; -// exit_code (); -// } -// else -// thehandle = INVALID_HANDLE_VALUE; -// return thehandle; + (void) CloseHandle (_cache_add_trigger); + DeleteCriticalSection (&_cache_write_access); } -DWORD process::exit_code () +/* This returns the process object to the caller already locked, that + * is, with the object's `access' critical region entered. Thus the + * caller must unlock the object when it's finished with it (via + * process::release ()). It must then not try to access the object + * afterwards, except by going through this routine again, as it may + * have been deleted once it has been unlocked. + */ +class process * +process_cache::process (const pid_t cygpid, const DWORD winpid) { - if (_exit_status != STILL_ACTIVE) - return _exit_status; - bool - err = GetExitCodeProcess (thehandle, &_exit_status); - if (!err) + /* TODO: make this more granular, so a search doesn't involve the + * write lock. + */ + EnterCriticalSection (&_cache_write_access); + class process *previous = NULL; + class process *entry = find (winpid, &previous); + + if (!entry) { - debug_printf ("Failed to retrieve exit code (%ld)\n", GetLastError ()); - thehandle = INVALID_HANDLE_VALUE; - return _exit_status; + if (_processes_count + SPECIALS_COUNT >= MAXIMUM_WAIT_OBJECTS) + { + LeaveCriticalSection (&_cache_write_access); + system_printf (("process limit (%d processes) reached; " + "new connection refused for %d(%lu)"), + MAXIMUM_WAIT_OBJECTS - SPECIALS_COUNT, + cygpid, winpid); + set_errno (EAGAIN); + return NULL; + } + + entry = safe_new (class process, cygpid, winpid); + if (!entry->is_active ()) + { + LeaveCriticalSection (&_cache_write_access); + safe_delete (entry); + set_errno (ESRCH); + return NULL; + } + + if (previous) + { + entry->_next = previous->_next; + previous->_next = entry; + } + else + { + entry->_next = _processes_head; + _processes_head = entry; + } + + _processes_count += 1; + SetEvent (_cache_add_trigger); } - else if (_exit_status == STILL_ACTIVE) - return _exit_status; - /* add new cleanup task etc etc ? */ - return _exit_status; + + EnterCriticalSection (&entry->_access); // To be released by the caller. + LeaveCriticalSection (&_cache_write_access); + assert (entry); + assert (entry->_winpid == winpid); + return entry; } -/* this is single threaded. It's called after the process is removed from the cache, - * but inserts may be attemped by worker threads that have a pointer to it */ void -process::cleanup () +process_cache::wait_for_processes (const HANDLE interrupt_event) { - /* Serialize this */ - EnterCriticalSection (&access); - InterlockedIncrement (&(long)cleaning_up); - class cleanup_routine *entry = head; - while (entry) + // Update `_wait_array' with handles of all current processes. + const size_t count = sync_wait_array (interrupt_event); + + debug_printf ("waiting on %u objects in total (%u processes)", + count, _processes_count); + + const DWORD rc = WaitForMultipleObjects (count, _wait_array, + FALSE, INFINITE); + + if (rc == WAIT_FAILED) + { + system_printf ("could not wait on the process handles, error = %lu", + GetLastError ()); + abort (); + } + + const size_t start = rc - WAIT_OBJECT_0; + + if (rc < WAIT_OBJECT_0 || start > count) { - class cleanup_routine *temp; - entry->cleanup (winpid); - temp = entry->next; - delete entry; - entry = temp; + system_printf (("unexpected return code %rc " + "from WaitForMultipleObjects: " + "expected [%u .. %u)"), + rc, WAIT_OBJECT_0, WAIT_OBJECT_0 + count); + abort (); } - LeaveCriticalSection (&access); + + // Tell all the processes, from the signalled point up, the bad news. + for (size_t index = start; index != count; index++) + if (_process_array[index]) + check_and_remove_process (index); } -bool -process::add_cleanup_routine (class cleanup_routine *new_cleanup) +/* + * process_cache::sync_wait_array () + * + * Fill-in the wait array with the handles that the cache needs to wait on. + * These handles are: + * - the process_process_param's interrupt event + * - the process_cache's cache_add_trigger event + * - the handle for each live process in the cache. + * + * Return value: the number of live handles in the array. + */ + +size_t +process_cache::sync_wait_array (const HANDLE interrupt_event) { - if (cleaning_up) - return false; - EnterCriticalSection (&access); - /* check that we didn't block with ::cleanup () - * This rigmarole is to get around win9x's glaring missing TryEnterCriticalSection call - * which would be a whole lot easier - */ - if (cleaning_up) + assert (this); + assert (_cache_add_trigger && _cache_add_trigger != INVALID_HANDLE_VALUE); + assert (interrupt_event && interrupt_event != INVALID_HANDLE_VALUE); + + EnterCriticalSection (&_cache_write_access); + + assert (_processes_count + SPECIALS_COUNT <= elements (_wait_array)); + + size_t index = 0; + + for (class process *ptr = _processes_head; ptr; ptr = ptr->_next) { - LeaveCriticalSection (&access); - return false; + assert (ptr->_hProcess && ptr->_hProcess != INVALID_HANDLE_VALUE); + assert (ptr->is_active ()); + + _wait_array[index] = ptr->handle (); + _process_array[index++] = ptr; + + assert (index <= elements (_wait_array)); } - new_cleanup->next = head; - head = new_cleanup; - LeaveCriticalSection (&access); - return true; + + /* Sorry for shouting, but THESE MUST BE ADDED AT THE END! */ + /* Well, not strictly `must', but it's more efficient if they are :-) */ + + _wait_array[index] = interrupt_event; + _process_array[index++] = NULL; + + _wait_array[index] = _cache_add_trigger; + _process_array[index++] = NULL; + + /* Phew, back to normal volume now. */ + + assert (index <= elements (_wait_array)); + + LeaveCriticalSection (&_cache_write_access); + + return index; } -/* process_cleanup */ void -process_cleanup::process () +process_cache::check_and_remove_process (const size_t index) { - theprocess->cleanup (); - delete theprocess; + assert (this); + assert (index < elements (_wait_array) - SPECIALS_COUNT); + + class process *const process = _process_array[index]; + + assert (process); + assert (process->handle () == _wait_array[index]); + + if (process->check_exit_code () == STILL_ACTIVE) + return; + + debug_printf ("process %d(%lu) has left the building ($? = %lu)", + process->_cygpid, process->_winpid, process->_exit_status); + + /* Unlink the process object from the process list. */ + + EnterCriticalSection (&_cache_write_access); + + class process *previous = NULL; + + const class process *const tmp = find (process->_winpid, &previous); + + assert (tmp == process); + assert (previous ? previous->_next == process : _processes_head == process); + + if (previous) + previous->_next = process->_next; + else + _processes_head = process->_next; + + _processes_count -= 1; + LeaveCriticalSection (&_cache_write_access); + + /* Schedule any cleanup tasks for this process. */ + _queue.add (safe_new (process_cleanup, process)); } -/* process_process_param */ -DWORD -process_process_param::request_loop () +class process * +process_cache::find (const DWORD winpid, class process **previous) { - process_cache *cache = (process_cache *) queue; - /* always malloc one, so there is no special case in the loop */ - ssize_t HandlesSize = 2; - HANDLE *Handles = (HANDLE *) malloc (sizeof (HANDLE) * HandlesSize); - process **Entries = (process **) malloc (sizeof (LPVOID) * HandlesSize); - /* TODO: put [1] at the end as it will also get done if a process dies? */ - Handles[0] = interrupt; - Handles[1] = cache->cache_add_trigger; - while (cache->active && !shutdown) - { - int copied; - copied = -1; - int offset; - offset = 1; - int count; - count = 2; - while ((copied == HandlesSize - 2 - offset) || copied < 0) - { - /* we need more storage to cope with all the HANDLES */ - if (copied == HandlesSize - 2 - offset) - { - HANDLE *temp = (HANDLE *) realloc (Handles, - sizeof (HANDLE) * - HandlesSize + 10); - if (!temp) - { - printf - ("cannot allocate more storage for the handle array!\n"); - exit (1); - } - Handles = temp; - process **ptemp = (process **) realloc (Entries, - sizeof (LPVOID) * - HandlesSize + 10); - if (!ptemp) - { - printf - ("cannot allocate more storage for the handle array!\n"); - exit (1); - } - Entries = ptemp; - HandlesSize += 10; - } - offset += copied; - copied = - cache->handle_snapshot (&Handles[2], &Entries[2], - HandlesSize - 2 - offset, offset); - count += copied; - } - debug_printf ("waiting on %u objects\n", count); - DWORD rc = WaitForMultipleObjects (count, Handles, FALSE, INFINITE); - if (rc == WAIT_FAILED) - { - printf ("Could not wait on the process handles (%ld)!\n", - GetLastError ()); - exit (1); - } - int objindex = rc - WAIT_OBJECT_0; - if (objindex > 1 && objindex < count) - { - debug_printf ("Process %ld has left the building\n", - Entries[objindex]->winpid); - /* fire off the termination routines */ - cache->remove_process (Entries[objindex]); - } - else if (objindex >= 0 && objindex < 2) - { - /* 0 is shutdown - do nothing */ - /* 1 is a cache add event - just rebuild the object list */ - } - else - { - printf - ("unexpected return code from WaitForMultiple objects in process_process_param::request_loop\n"); - } - } - running = false; - return 0; + if (previous) + *previous = NULL; + + for (class process *ptr = _processes_head; ptr; ptr = ptr->_next) + if (ptr->_winpid == winpid) + return ptr; + else if (ptr->_winpid > winpid) // The list is sorted by winpid. + return NULL; + else if (previous) + *previous = ptr; + + return NULL; } + +/*****************************************************************************/ diff --git a/winsup/cygserver/shm.cc b/winsup/cygserver/shm.cc index 260a5b1bd..18b1c3d83 100644 --- a/winsup/cygserver/shm.cc +++ b/winsup/cygserver/shm.cc @@ -1,8 +1,9 @@ -/* cygserver_shm.cc: Single unix specification IPC interface for Cygwin +/* cygserver_shm.cc: Single unix specification IPC interface for Cygwin. -Copyright 2001, 2002 Red Hat, Inc. + Copyright 2002 Red Hat, Inc. -Originally written by Robert Collins <robert.collins@hotmail.com> + Written by Conrad Scott <conrad.scott@dsl.pipex.com>. + Based on code by Robert Collins <robert.collins@hotmail.com>. This file is part of Cygwin. @@ -10,656 +11,886 @@ This software is a copyrighted work licensed under the terms of the Cygwin license. Please consult the file "CYGWIN_LICENSE" for details. */ -#ifdef __OUTSIDE_CYGWIN__ -#undef __INSIDE_CYGWIN__ -#else -#include "winsup.h" -#endif - -#ifndef __INSIDE_CYGWIN__ -#define DEBUG 0 -#define system_printf printf -#define debug_printf if (DEBUG) printf -#define api_fatal printf -#include <stdio.h> -#include <windows.h> -#endif +#include "woutsup.h" -#include <sys/stat.h> #include <errno.h> -#include "cygerrno.h" -#include <unistd.h> -#include "security.h" -//#include "fhandler.h" -//#include "dtable.h" -//#include "cygheap.h" +#include <pthread.h> #include <stdio.h> -//#include "thread.h" -#ifndef __INSIDE_CYGWIN__ -#define __INSIDE_CYGWIN__ -#include <cygwin/shm.h> -#undef __INSIDE_CYGWIN__ -#else -#include <cygwin/shm.h> -#endif -//#include "perprocess.h" -#include <threaded_queue.h> -#include <cygwin/cygserver_process.h> -#include "cygserver_shm.h" +#include <string.h> +#include <time.h> -// FIXME IS THIS CORRECT -/* Implementation notes: We use two shared memory regions per key: - * One for the control structure, and one for the shared memory. - * While this has a higher overhead tham a single shared area, - * It allows more flexability. As the entire code is transparent to the user - * We can merge these in the future should it be needed. - * Also, IPC_PRIVATE keys create unique mappings each time. The shm_ids just - * keep monotonically incrementing - system wide. - */ -size_t -getsystemallocgranularity () -{ - SYSTEM_INFO sysinfo; - static size_t buffer_offset = 0; - if (buffer_offset) - return buffer_offset; - GetSystemInfo (&sysinfo); - buffer_offset = sysinfo.dwAllocationGranularity; - return buffer_offset; -} +#include "cygserver_ipc.h" +#include "cygserver_shm.h" +#include "security.h" +#include "cygwin/cygserver.h" +#include "cygwin/cygserver_process.h" +#include "cygwin/cygserver_transport.h" -client_request_shm::client_request_shm ():client_request (CYGSERVER_REQUEST_SHM_GET, - sizeof (parameters)) -{ - buffer = (char *) ¶meters; -} +/*---------------------------------------------------------------------------* + * class server_shmmgr + * + * A singleton class. + *---------------------------------------------------------------------------*/ -/* FIXME: If building on a 64-bit compiler, the address->int typecast will fail. - * Solution: manually calculate the next id value - */ +#define shmmgr (server_shmmgr::instance ()) -#if 0 -extern -"C" void * -shmat (int shmid, const void *shmaddr, int parameters.in.shmflg) +class server_shmmgr { - class shmid_ds * - shm = (class shmid_ds *) - shmid; //FIXME: verifyable object test +private: + class attach_t + { + public: + class process *const _client; + unsigned int _refcnt; + + attach_t *_next; + + attach_t (class process *const client) + : _client (client), + _refcnt (0), + _next (NULL) + {} + }; + + class segment_t + { + private: + // Bits for the _flg field. + enum { IS_DELETED = 0x01 }; + + public: + const int _intid; + const int _shmid; + struct shmid_ds _ds; + + segment_t *_next; + + segment_t (const key_t key, const int intid, const HANDLE hFileMap); + ~segment_t (); + + bool is_deleted () const + { + return _flg & IS_DELETED; + } + + bool is_pending_delete () const + { + return !_ds.shm_nattch && is_deleted (); + } - if (shmaddr) + void mark_deleted () { - //FIXME: requested base address ?! - set_errno (EINVAL); - return (void *) -1; + assert (!is_deleted ()); + + _flg |= IS_DELETED; } - void * - rv = - MapViewOfFile (shm->attachmap, + int attach (class process *, HANDLE & hFileMap); + int detach (class process *); + + private: + static long _sequence; + int _flg; + const HANDLE _hFileMap; + attach_t *_attach_head; // A list sorted by winpid; - (parameters.in.shmflg & SHM_RDONLY) ? - FILE_MAP_READ : FILE_MAP_WRITE, 0, - 0, 0); + attach_t *find (const class process *, attach_t **previous = NULL); + }; - if (!rv) + class cleanup_t : public cleanup_routine + { + public: + cleanup_t (const segment_t *const segptr) + : cleanup_routine (reinterpret_cast<void *> (segptr->_shmid)) { - //FIXME: translate GetLastError() - set_errno (EACCES); - return (void *) -1; + assert (key ()); } -/* FIXME: this needs to be globally protected to prevent a mismatch betwen - * attach count and attachees list - */ - - InterlockedIncrement (&shm->shm_nattch); - _shmattach * - attachnode = - new - _shmattach; - - attachnode->data = rv; - attachnode->next = - (_shmattach *) InterlockedExchangePointer ((LONG *) & shm->attachhead, - (long int) attachnode); - return rv; + int shmid () const { return reinterpret_cast<int> (key ()); } + + virtual void cleanup (class process *const client) + { + const int res = shmmgr.shmdt (shmid (), client); + + if (res != 0) + debug_printf ("process cleanup failed [shmid = %d]: %s", + shmid (), strerror (-res)); + } + }; + +public: + static server_shmmgr & instance (); + + int shmat (HANDLE & hFileMap, + int shmid, int shmflg, class process *); + int shmctl (int & out_shmid, struct shmid_ds & out_ds, + struct shminfo & out_shminfo, struct shm_info & out_shm_info, + const int shmid, int cmd, const struct shmid_ds &, + class process *); + int shmdt (int shmid, class process *); + int shmget (int & out_shmid, key_t, size_t, int shmflg, uid_t, gid_t, + class process *); + +private: + static server_shmmgr *_instance; + static pthread_once_t _instance_once; + + static void initialise_instance (); + + CRITICAL_SECTION _segments_lock; + segment_t *_segments_head; // A list sorted by int_id. + + int _shm_ids; // Number of shm segments (for ipcs(8)). + int _shm_tot; // Total bytes of shm segments (for ipcs(8)). + int _shm_atts; // Number of attached segments (for ipcs(8)). + int _intid_max; // Highest intid yet allocated (for ipcs(8)). + + server_shmmgr (); + ~server_shmmgr (); + + // Undefined (as this class is a singleton): + server_shmmgr (const server_shmmgr &); + server_shmmgr & operator= (const server_shmmgr &); + + segment_t *find_by_key (key_t); + segment_t *find (int intid, segment_t **previous = NULL); + + int new_segment (key_t, size_t, int shmflg, pid_t, uid_t, gid_t); + + segment_t *new_segment (key_t, size_t, HANDLE); + void delete_segment (segment_t *); +}; + +/* static */ long server_shmmgr::segment_t::_sequence = 0; + +/* static */ server_shmmgr *server_shmmgr::_instance = NULL; +/* static */ pthread_once_t server_shmmgr::_instance_once = PTHREAD_ONCE_INIT; + +/*---------------------------------------------------------------------------* + * server_shmmgr::segment_t::segment_t () + *---------------------------------------------------------------------------*/ + +server_shmmgr::segment_t::segment_t (const key_t key, + const int intid, + const HANDLE hFileMap) + : _intid (intid), + _shmid (ipc_int2ext (intid, IPC_SHMOP, _sequence)), + _next (NULL), + _flg (0), + _hFileMap (hFileMap), + _attach_head (NULL) +{ + assert (0 <= _intid && _intid < SHMMNI); + + memset (&_ds, '\0', sizeof (_ds)); + _ds.shm_perm.key = key; } -#endif - -/* FIXME: evaluate getuid() and getgid() against the requested mode. Then - * choose PAGE_READWRITE | PAGE_READONLY and FILE_MAP_WRITE | FILE_MAP_READ - * appropriately - */ - -/* Test result from openbsd: shm ids are persistent cross process if a handle is left - * open. This could lead to resource starvation: we're not copying that behaviour - * unless we have to. (It will involve acygwin1.dll gloal shared list :[ ). - */ -/* FIXME: shmid should be a verifyable object - */ - -/* FIXME: on NT we should check everything against the SD. On 95 we just emulate. - */ - -extern GENERIC_MAPPING - access_mapping; - -extern int -check_and_dup_handle (HANDLE from_process, HANDLE to_process, - HANDLE from_process_token, - DWORD access, - HANDLE from_handle, - HANDLE * to_handle_ptr, BOOL bInheritHandle); - -//FIXME: where should this live -static shmnode * - shm_head = - NULL; -//FIXME: ditto. -static shmnode * - deleted_head = NULL; -/* must be long for InterlockedIncrement */ -static long - new_id = - 0; -static long - new_private_key = - 0; - -static void -delete_shmnode (shmnode **nodeptr) + +/*---------------------------------------------------------------------------* + * server_shmmgr::segment_t::~segment_t () + *---------------------------------------------------------------------------*/ + +server_shmmgr::segment_t::~segment_t () { - shmnode *node = *nodeptr; + assert (!_attach_head); - // remove from the list - if (node == shm_head) - shm_head = shm_head->next; - else + if (!CloseHandle (_hFileMap)) + syscall_printf ("failed to close file map [handle = 0x%x]: %E", _hFileMap); +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::segment_t::attach () + *---------------------------------------------------------------------------*/ + +int +server_shmmgr::segment_t::attach (class process *const client, + HANDLE & hFileMap) +{ + assert (client); + + if (!DuplicateHandle (GetCurrentProcess (), + _hFileMap, + client->handle (), + &hFileMap, + 0, + FALSE, // bInheritHandle + DUPLICATE_SAME_ACCESS)) + { + syscall_printf (("failed to duplicate handle for client " + "[key = 0x%016llx, shmid = %d, handle = 0x%x]: %E"), + _ds.shm_perm.key, _shmid, _hFileMap); + + return -EACCES; // FIXME: Case analysis? + } + + _ds.shm_lpid = client->cygpid (); + _ds.shm_nattch += 1; + _ds.shm_atime = time (NULL); // FIXME: sub-second times. + + attach_t *previous = NULL; + attach_t *attptr = find (client, &previous); + + if (!attptr) { - shmnode *tempnode = shm_head; - while (tempnode && tempnode->next != node) - tempnode = tempnode->next; - if (tempnode) - tempnode->next = node->next; - // else log the unexpected ! + attptr = safe_new (attach_t, client); + + if (previous) + { + attptr->_next = previous->_next; + previous->_next = attptr; + } + else + { + attptr->_next = _attach_head; + _attach_head = attptr; + } } - // release the shared data view - UnmapViewOfFile (node->shmds->mapptr); - delete node->shmds; - CloseHandle (node->filemap); - CloseHandle (node->attachmap); + attptr->_refcnt += 1; - // free the memory - delete node; - nodeptr = NULL; + cleanup_t *const cleanup = safe_new (cleanup_t, this); + + // FIXME: ::add should only fail if the process object is already + // cleaning up; but it can't be doing that since this thread has it + // locked. + + const bool result = client->add (cleanup); + + assert (result); + + return 0; } -void -client_request_shm::serve (transport_layer_base * conn, process_cache * cache) +/*---------------------------------------------------------------------------* + * server_shmmgr::segment_t::detach () + *---------------------------------------------------------------------------*/ + +int +server_shmmgr::segment_t::detach (class process *const client) { -// DWORD sd_size = 4096; -// char sd_buf[4096]; - PSECURITY_DESCRIPTOR psd = (PSECURITY_DESCRIPTOR) parameters.in.sd_buf; -// /* create a sd for our open requests based on shmflag & 0x01ff */ -// psd = alloc_sd (getuid (), getgid (), cygheap->user.logsrv (), -// parameters.in.shmflg & 0x01ff, psd, &sd_size); - - HANDLE from_process_handle = NULL; - HANDLE token_handle = NULL; - DWORD rc; - - from_process_handle = cache->process (parameters.in.pid)->handle (); - /* possible TODO: reduce the access on the handle before we use it */ - /* Note that unless we do this, we don't need to call CloseHandle - it's kept open - * by the process cache until the process terminates. - * We may need a refcount on the cache however... - */ - if (!from_process_handle) + attach_t *previous = NULL; + attach_t *const attptr = find (client, &previous); + + if (!attptr) + return -EINVAL; + + if (client->is_active ()) { - debug_printf ("error opening process (%lu)\n", GetLastError ()); - header.error_code = EACCES; - return; + const cleanup_t key (this); + + if (!client->remove (&key)) + syscall_printf (("failed to remove cleanup routine for %d(%lu) " + "[shmid = %d]"), + client->cygpid (), client->winpid (), + _shmid); } - conn->impersonate_client (); + attptr->_refcnt -= 1; - rc = OpenThreadToken (GetCurrentThread (), - TOKEN_QUERY, TRUE, &token_handle); + if (!attptr->_refcnt) + { + assert (previous ? previous->_next == attptr : _attach_head == attptr); - conn->revert_to_self (); + if (previous) + previous->_next = attptr->_next; + else + _attach_head = attptr->_next; - if (!rc) - { - debug_printf ("error opening thread token (%lu)\n", GetLastError ()); - header.error_code = EACCES; - CloseHandle (from_process_handle); - return; + safe_delete (attptr); } + assert (_ds.shm_nattch > 0); - /* we trust the clients request - we will be doing it as them, and - * the worst they can do is open their own permissions - */ + _ds.shm_lpid = client->cygpid (); + _ds.shm_nattch -= 1; + _ds.shm_dtime = time (NULL); // FIXME: sub-second times. + + return 0; +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::segment_t::find () + *---------------------------------------------------------------------------*/ + +server_shmmgr::attach_t * +server_shmmgr::segment_t::find (const class process *const client, + attach_t **previous) +{ + if (previous) + *previous = NULL; + + // Nb. The _attach_head list is sorted by winpid. + for (attach_t *attptr = _attach_head; attptr; attptr = attptr->_next) + if (attptr->_client == client) + return attptr; + else if (attptr->_client->winpid () > client->winpid ()) + return NULL; + else if (previous) + *previous = attptr; - SECURITY_ATTRIBUTES sa; - sa.nLength = sizeof (sa); - sa.lpSecurityDescriptor = psd; - sa.bInheritHandle = TRUE; /* the memory structures inherit ok */ + return NULL; +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::instance () + *---------------------------------------------------------------------------*/ + +/* static */ server_shmmgr & +server_shmmgr::instance () +{ + pthread_once (&_instance_once, &initialise_instance); + + assert (_instance); + + return *_instance; +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::shmat () + *---------------------------------------------------------------------------*/ - char *shmname = NULL, *shmaname = NULL; - char stringbuf[29], stringbuf1[29]; +int +server_shmmgr::shmat (HANDLE & hFileMap, + const int shmid, const int shmflg, + class process *const client) +{ + syscall_printf ("shmat (shmid = %d, shmflg = 0%o) for %d(%lu)", + shmid, shmflg, client->cygpid (), client->winpid ()); + + int result = 0; + EnterCriticalSection (&_segments_lock); + + segment_t *const segptr = find (ipc_ext2int (shmid, IPC_SHMOP)); + + if (!segptr) + result = -EINVAL; + else + result = segptr->attach (client, hFileMap); + + if (!result) + _shm_atts += 1; - /* TODO: make this code block a function! */ - if (parameters.in.type == SHM_REATTACH) + LeaveCriticalSection (&_segments_lock); + + if (result < 0) + syscall_printf (("-1 [%d] = shmat (shmid = %d, shmflg = 0%o) " + "for %d(%lu)"), + -result, shmid, shmflg, + client->cygpid (), client->winpid ()); + else + syscall_printf (("0x%x = shmat (shmid = %d, shmflg = 0%o) " + "for %d(%lu)"), + hFileMap, shmid, shmflg, + client->cygpid (), client->winpid ()); + + return result; +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::shmctl () + *---------------------------------------------------------------------------*/ + +int +server_shmmgr::shmctl (int & out_shmid, + struct shmid_ds & out_ds, + struct shminfo & out_shminfo, + struct shm_info & out_shm_info, + const int shmid, const int cmd, + const struct shmid_ds & ds, + class process *const client) +{ + syscall_printf ("shmctl (shmid = %d, cmd = 0x%x) for %d(%lu)", + shmid, cmd, client->cygpid (), client->winpid ()); + + int result = 0; + EnterCriticalSection (&_segments_lock); + + switch (cmd) { - /* just find and fill out the existing shm_id */ - shmnode *tempnode = shm_head; - while (tempnode) - { - if (tempnode->shm_id == parameters.in.shm_id) + case IPC_STAT: + case SHM_STAT: // Uses intids rather than shmids. + case IPC_SET: + case IPC_RMID: + { + int intid; + + if (cmd == SHM_STAT) + intid = shmid; + else + intid = ipc_ext2int (shmid, IPC_SHMOP); + + segment_t *const segptr = find (intid); + + if (!segptr) + result = -EINVAL; + else + switch (cmd) { - parameters.out.shm_id = tempnode->shm_id; - parameters.out.key = tempnode->key; - if (check_and_dup_handle - (GetCurrentProcess (), from_process_handle, token_handle, - DUPLICATE_SAME_ACCESS, tempnode->filemap, - ¶meters.out.filemap, TRUE) != 0) - { - debug_printf ("error duplicating filemap handle (%lu)\n", - GetLastError ()); - header.error_code = EACCES; - } - if (check_and_dup_handle - (GetCurrentProcess (), from_process_handle, token_handle, - DUPLICATE_SAME_ACCESS, tempnode->attachmap, - ¶meters.out.attachmap, TRUE) != 0) + case IPC_STAT: + out_ds = segptr->_ds; + break; + + case IPC_SET: + segptr->_ds.shm_perm.uid = ds.shm_perm.uid; + segptr->_ds.shm_perm.gid = ds.shm_perm.gid; + segptr->_ds.shm_perm.mode = ds.shm_perm.mode & 0777; + segptr->_ds.shm_lpid = client->cygpid (); + segptr->_ds.shm_ctime = time (NULL); // FIXME: sub-second times. + break; + + case IPC_RMID: + if (segptr->is_deleted ()) + result = -EIDRM; + else { - debug_printf ("error duplicating attachmap handle (%lu)\n", - GetLastError ()); - header.error_code = EACCES; + segptr->mark_deleted (); + if (segptr->is_pending_delete ()) + delete_segment (segptr); } - CloseHandle (token_handle); - return; + break; + + case SHM_STAT: // ipcs(8) i'face. + out_ds = segptr->_ds; + out_shmid = segptr->_shmid; + break; } - tempnode = tempnode->next; - } - header.error_code = EINVAL; - CloseHandle (token_handle); - return; + } + break; + + case IPC_INFO: + out_shminfo.shmmax = SHMMAX; + out_shminfo.shmmin = SHMMIN; + out_shminfo.shmmni = SHMMNI; + out_shminfo.shmseg = SHMSEG; + out_shminfo.shmall = SHMALL; + break; + + case SHM_INFO: // ipcs(8) i'face. + out_shmid = _intid_max; + out_shm_info.shm_ids = _shm_ids; + out_shm_info.shm_tot = _shm_tot; + out_shm_info.shm_atts = _shm_atts; + break; + + default: + result = -EINVAL; + break; } - /* someone attached */ - /* someone can send shm_id's they don't have and currently we will increment those - * attach counts. If someone wants to fix that, please go ahead. - * The problem is that shm_get has nothing to do with the ability to attach. Attach - * requires a permission check, which we get the OS to do in MapViewOfFile. - */ - if (parameters.in.type == SHM_ATTACH) + LeaveCriticalSection (&_segments_lock); + + if (result < 0) + syscall_printf (("-1 [%d] = " + "shmctl (shmid = %d, cmd = 0x%x) for %d(%lu)"), + -result, + shmid, cmd, client->cygpid (), client->winpid ()); + else + syscall_printf (("%d = " + "shmctl (shmid = %d, cmd = 0x%x) for %d(%lu)"), + ((cmd == SHM_STAT || cmd == SHM_INFO) + ? out_shmid + : result), + shmid, cmd, client->cygpid (), client->winpid ()); + + return result; +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::shmdt () + *---------------------------------------------------------------------------*/ + +int +server_shmmgr::shmdt (const int shmid, class process *const client) +{ + syscall_printf ("shmdt (shmid = %d) for %d(%lu)", + shmid, client->cygpid (), client->winpid ()); + + int result = 0; + EnterCriticalSection (&_segments_lock); + + segment_t *const segptr = find (ipc_ext2int (shmid, IPC_SHMOP)); + + if (!segptr) + result = -EINVAL; + else + result = segptr->detach (client); + + if (!result) + _shm_atts -= 1; + + if (!result && segptr->is_pending_delete ()) + delete_segment (segptr); + + LeaveCriticalSection (&_segments_lock); + + if (result < 0) + syscall_printf ("-1 [%d] = shmdt (shmid = %d) for %d(%lu)", + -result, shmid, client->cygpid (), client->winpid ()); + else + syscall_printf ("%d = shmdt (shmid = %d) for %d(%lu)", + result, shmid, client->cygpid (), client->winpid ()); + + return result; +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::shmget () + *---------------------------------------------------------------------------*/ + +int +server_shmmgr::shmget (int & out_shmid, + const key_t key, const size_t size, const int shmflg, + const uid_t uid, const gid_t gid, + class process *const client) +{ + syscall_printf (("shmget (key = 0x%016llx, size = %u, shmflg = 0%o) " + "for %d(%lu)"), + key, size, shmflg, + client->cygpid (), client->winpid ()); + + int result = 0; + EnterCriticalSection (&_segments_lock); + + if (key == IPC_PRIVATE) + result = new_segment (key, size, shmflg, + client->cygpid (), uid, gid); + else { - shmnode *tempnode = shm_head; - while (tempnode) - { - if (tempnode->shm_id == parameters.in.shm_id) - { - InterlockedIncrement (&tempnode->shmds->shm_nattch); - header.error_code = 0; - CloseHandle (token_handle); - return; - } - tempnode = tempnode->next; - } - header.error_code = EINVAL; - CloseHandle (token_handle); - return; + segment_t *const segptr = find_by_key (key); + + if (!segptr) + if (shmflg & IPC_CREAT) + result = new_segment (key, size, shmflg, + client->cygpid (), uid, gid); + else + result = -ENOENT; + else if (segptr->is_deleted ()) + result = -EIDRM; + else if ((shmflg & IPC_CREAT) && (shmflg & IPC_EXCL)) + result = -EEXIST; + else if ((shmflg & ~(segptr->_ds.shm_perm.mode)) & 0777) + result = -EACCES; + else if (size && segptr->_ds.shm_segsz < size) + result = -EINVAL; + else + result = segptr->_shmid; } - /* Someone detached */ - if (parameters.in.type == SHM_DETACH) + LeaveCriticalSection (&_segments_lock); + + if (result >= 0) { - shmnode *tempnode = shm_head; - while (tempnode) - { - if (tempnode->shm_id == parameters.in.shm_id) - { - InterlockedDecrement (&tempnode->shmds->shm_nattch); - header.error_code = 0; - CloseHandle (token_handle); - return; - } - tempnode = tempnode->next; - } - header.error_code = EINVAL; - CloseHandle (token_handle); - return; + out_shmid = result; + result = 0; } - /* Someone wants the ID removed. */ - if (parameters.in.type == SHM_DEL) + if (result < 0) + syscall_printf (("-1 [%d] = " + "shmget (key = 0x%016llx, size = %u, shmflg = 0%o) " + "for %d(%lu)"), + -result, + key, size, shmflg, + client->cygpid (), client->winpid ()); + else + syscall_printf (("%d = " + "shmget (key = 0x%016llx, size = %u, shmflg = 0%o) " + "for %d(%lu)"), + out_shmid, + key, size, shmflg, + client->cygpid (), client->winpid ()); + + return result; +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::initialise_instance () + *---------------------------------------------------------------------------*/ + +/* static */ void +server_shmmgr::initialise_instance () +{ + assert (!_instance); + + _instance = safe_new0 (server_shmmgr); + + assert (_instance); +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::server_shmmgr () + *---------------------------------------------------------------------------*/ + +server_shmmgr::server_shmmgr () + : _segments_head (NULL), + _shm_ids (0), + _shm_tot (0), + _shm_atts (0), + _intid_max (0) +{ + InitializeCriticalSection (&_segments_lock); +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::~server_shmmgr () + *---------------------------------------------------------------------------*/ + +server_shmmgr::~server_shmmgr () +{ + DeleteCriticalSection (&_segments_lock); +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::find_by_key () + *---------------------------------------------------------------------------*/ + +server_shmmgr::segment_t * +server_shmmgr::find_by_key (const key_t key) +{ + for (segment_t *segptr = _segments_head; segptr; segptr = segptr->_next) + if (segptr->_ds.shm_perm.key == key) + return segptr; + + return NULL; +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::find () + *---------------------------------------------------------------------------*/ + +server_shmmgr::segment_t * +server_shmmgr::find (const int intid, segment_t **previous) +{ + if (previous) + *previous = NULL; + + for (segment_t *segptr = _segments_head; segptr; segptr = segptr->_next) + if (segptr->_intid == intid) + return segptr; + else if (segptr->_intid > intid) // The list is sorted by intid. + return NULL; + else if (previous) + *previous = segptr; + + return NULL; +} + +/*---------------------------------------------------------------------------* + * server_shmmgr::new_segment () + *---------------------------------------------------------------------------*/ + +int +server_shmmgr::new_segment (const key_t key, + const size_t size, + const int shmflg, + const pid_t cygpid, + const uid_t uid, + const gid_t gid) +{ + if (size < SHMMIN || size > SHMMAX) + return -EINVAL; + + const HANDLE hFileMap = CreateFileMapping (INVALID_HANDLE_VALUE, + NULL, PAGE_READWRITE, + 0, size, + NULL); + + if (!hFileMap) { - shmnode **tempnode = &shm_head; - while (*tempnode) - { - if ((*tempnode)->shm_id == parameters.in.shm_id) - { - // unlink from the accessible node list - shmnode *temp2 = *tempnode; - *tempnode = temp2->next; - // link into the deleted list - temp2->next = deleted_head; - deleted_head = temp2; - - // FIXME: when/where do we delete the handles? - if (temp2->shmds->shm_nattch) - { - // FIXME: add to a pending queue? - } - else - { - delete_shmnode (&temp2); - } - - header.error_code = 0; - CloseHandle (token_handle); - return; - } - tempnode = &(*tempnode)->next; - } - header.error_code = EINVAL; - CloseHandle (token_handle); - return; + syscall_printf ("failed to create file mapping [size = %lu]: %E", size); + return -ENOMEM; // FIXME } + segment_t *const segptr = new_segment (key, size, hFileMap); - if (parameters.in.type == SHM_CREATE) + if (!segptr) { - /* FIXME: enter the checking for existing keys mutex. This mutex _must_ be system wide - * to prevent races on shmget. - */ + (void) CloseHandle (hFileMap); + return -ENOSPC; + } - if (parameters.in.key == IPC_PRIVATE) - { - /* create the mapping name (CYGWINSHMKPRIVATE_0x01234567 */ - /* The K refers to Key, the actual mapped area has D */ - long private_key = (int) InterlockedIncrement (&new_private_key); - snprintf (stringbuf, 29, "CYGWINSHMKPRIVATE_0x%0x", private_key); - shmname = stringbuf; - snprintf (stringbuf1, 29, "CYGWINSHMDPRIVATE_0x%0x", private_key); - shmaname = stringbuf1; - } - else - { - /* create the mapping name (CYGWINSHMK0x0123456789abcdef */ - /* The K refers to Key, the actual mapped area has D */ - - snprintf (stringbuf, 29, "CYGWINSHMK0x%0qx", parameters.in.key); - shmname = stringbuf; - snprintf (stringbuf1, 29, "CYGWINSHMD0x%0qx", parameters.in.key); - shmaname = stringbuf1; - debug_printf ("system id strings are \n%s\n%s\n", shmname, - shmaname); - debug_printf ("key input value is 0x%0qx\n", parameters.in.key); - } + segptr->_ds.shm_perm.cuid = segptr->_ds.shm_perm.uid = uid; + segptr->_ds.shm_perm.cgid = segptr->_ds.shm_perm.gid = gid; + segptr->_ds.shm_perm.mode = shmflg & 0777; + segptr->_ds.shm_segsz = size; + segptr->_ds.shm_cpid = cygpid; + segptr->_ds.shm_ctime = time (NULL); // FIXME: sub-second times. - /* attempt to open the key */ + return segptr->_shmid; +} - /* get an existing key */ - /* On unix the same shmid identifier is returned on multiple calls to shm_get - * with the same key and size. Different modes is a ?. - */ +/*---------------------------------------------------------------------------* + * server_shmmgr::new_segment () + * + * Allocate a new segment for the given key and file map with the + * lowest available intid and insert into the segment map. + *---------------------------------------------------------------------------*/ +server_shmmgr::segment_t * +server_shmmgr::new_segment (const key_t key, const size_t size, + const HANDLE hFileMap) +{ + // FIXME: Overflow risk. + if (_shm_tot + size > SHMALL) + return NULL; + int intid = 0; // Next expected intid value. + segment_t *previous = NULL; // Insert pointer. - /* walk the list of known keys and return the id if found. remember, we are - * authoritative... - */ + // Find first unallocated intid. + for (segment_t *segptr = _segments_head; + segptr && segptr->_intid == intid; + segptr = segptr->_next, intid++) + { + previous = segptr; + } - shmnode *tempnode = shm_head; - while (tempnode) - { - if (tempnode->key == parameters.in.key - && parameters.in.key != IPC_PRIVATE) - { - // FIXME: free the mutex - if (parameters.in.size - && tempnode->shmds->shm_segsz < parameters.in.size) - { - header.error_code = EINVAL; - CloseHandle (token_handle); - return; - } - /* FIXME: can the same process call this twice without error ? test - * on unix - */ - if ((parameters.in.shmflg & IPC_CREAT) - && (parameters.in.shmflg & IPC_EXCL)) - { - header.error_code = EEXIST; - debug_printf - ("attempt to exclusively create already created shm_area with key 0x%0qx\n", - parameters.in.key); - // FIXME: free the mutex - CloseHandle (token_handle); - return; - } - // FIXME: do we need to other tests of the requested mode with the - // tempnode->shm_id mode ? testcase on unix needed. - // FIXME how do we do the security test? or - // do we wait for shmat to bother with that? - /* One possibly solution: impersonate the client, and then test we can - * reopen the area. In fact we'll probably have to do that to get - * handles back to them, alternatively just tell them the id, and then - * let them attempt the open. - */ - parameters.out.shm_id = tempnode->shm_id; - if (check_and_dup_handle - (GetCurrentProcess (), from_process_handle, token_handle, - DUPLICATE_SAME_ACCESS, tempnode->filemap, - ¶meters.out.filemap, TRUE) != 0) - { - printf ("error duplicating filemap handle (%lu)\n", - GetLastError ()); - header.error_code = EACCES; -/*mutex*/ - CloseHandle (token_handle); - return; - } - if (check_and_dup_handle - (GetCurrentProcess (), from_process_handle, token_handle, - DUPLICATE_SAME_ACCESS, tempnode->attachmap, - ¶meters.out.attachmap, TRUE) != 0) - { - printf ("error duplicating attachmap handle (%lu)\n", - GetLastError ()); - header.error_code = EACCES; -/*mutex*/ - CloseHandle (token_handle); - return; - } + /* By the time this condition is reached (given the default value of + * SHMMNI), the linear searches should all replaced by something + * just a *little* cleverer . . . + */ + if (intid >= SHMMNI) + return NULL; - CloseHandle (token_handle); - return; - } - tempnode = tempnode->next; - } - /* couldn't find a currently open shm area. */ - - /* create one */ - /* do this as the client */ - conn->impersonate_client (); - /* This may need sh_none... it's only a control structure */ - HANDLE filemap = CreateFileMapping (INVALID_HANDLE_VALUE, // system pagefile. - &sa, - PAGE_READWRITE, // protection - 0x00000000, - getsystemallocgranularity (), - shmname // object name - ); - int lasterr = GetLastError (); - conn->revert_to_self (); - - if (filemap == NULL) - { - /* We failed to open the filemapping ? */ - system_printf ("failed to open file mapping: %lu\n", - GetLastError ()); - // free the mutex - // we can assume that it exists, and that it was an access problem. - header.error_code = EACCES; - CloseHandle (token_handle); - return; - } + segment_t *const segptr = safe_new (segment_t, key, intid, hFileMap); - /* successfully opened the control region mapping */ - /* did we create it ? */ - int oldmapping = lasterr == ERROR_ALREADY_EXISTS; - if (oldmapping) - { - /* should never happen - we are the global daemon! */ -#if 0 - if ((parameters.in.shmflg & IPC_CREAT) - && (parameters.in.shmflg & IPC_EXCL)) -#endif - { - /* FIXME free mutex */ - CloseHandle (filemap); - header.error_code = EEXIST; - CloseHandle (token_handle); - return; - } - } + assert (segptr); - /* we created a new mapping */ - if (parameters.in.key != IPC_PRIVATE && - (parameters.in.shmflg & IPC_CREAT) == 0) - { - CloseHandle (filemap); - /* FIXME free mutex */ - header.error_code = ENOENT; - CloseHandle (token_handle); - return; - } + if (previous) + { + segptr->_next = previous->_next; + previous->_next = segptr; + } + else + { + segptr->_next = _segments_head; + _segments_head = segptr; + } - conn->impersonate_client (); - void *mapptr = MapViewOfFile (filemap, FILE_MAP_WRITE, 0, 0, 0); - conn->revert_to_self (); + _shm_ids += 1; + _shm_tot += size; + if (intid > _intid_max) + _intid_max = intid; - if (!mapptr) - { - CloseHandle (filemap); - //FIXME: close filemap and free the mutex - /* we couldn't access the mapped area with the requested permissions */ - header.error_code = EACCES; - CloseHandle (token_handle); - return; - } + return segptr; +} - conn->impersonate_client (); - /* Now get the user data */ - HANDLE attachmap = CreateFileMapping (INVALID_HANDLE_VALUE, // system pagefile - &sa, - PAGE_READWRITE, // protection (FIXME) - 0x00000000, - parameters.in.size + - parameters.in.size % - getsystemallocgranularity (), - shmaname // object name - ); - conn->revert_to_self (); - - if (attachmap == NULL) - { - system_printf ("failed to get shm attachmap\n"); - header.error_code = ENOMEM; - UnmapViewOfFile (mapptr); - CloseHandle (filemap); - /* FIXME exit the mutex */ - CloseHandle (token_handle); - return; - } +/*---------------------------------------------------------------------------* + * server_shmmgr::delete_segment () + *---------------------------------------------------------------------------*/ - shmid_ds *shmtemp = new shmid_ds; - if (!shmtemp) - { - system_printf ("failed to malloc shm node\n"); - header.error_code = ENOMEM; - UnmapViewOfFile (mapptr); - CloseHandle (filemap); - CloseHandle (attachmap); - /* FIXME exit mutex */ - CloseHandle (token_handle); - return; - } +void +server_shmmgr::delete_segment (segment_t *const segptr) +{ + assert (segptr); + assert (segptr->is_pending_delete ()); - /* fill out the node data */ - shmtemp->shm_perm.cuid = getuid (); - shmtemp->shm_perm.uid = shmtemp->shm_perm.cuid; - shmtemp->shm_perm.cgid = getgid (); - shmtemp->shm_perm.gid = shmtemp->shm_perm.cgid; - shmtemp->shm_perm.mode = parameters.in.shmflg & 0x01ff; - shmtemp->shm_lpid = 0; - shmtemp->shm_nattch = 0; - shmtemp->shm_atime = 0; - shmtemp->shm_dtime = 0; - shmtemp->shm_ctime = time (NULL); - shmtemp->shm_segsz = parameters.in.size; - *(shmid_ds *) mapptr = *shmtemp; - shmtemp->mapptr = mapptr; - - /* no need for InterlockedExchange here, we're serialised by the global mutex */ - tempnode = new shmnode; - tempnode->shmds = shmtemp; - tempnode->shm_id = (int) InterlockedIncrement (&new_id); - tempnode->key = parameters.in.key; - tempnode->filemap = filemap; - tempnode->attachmap = attachmap; - tempnode->next = shm_head; - shm_head = tempnode; - - /* we now have the area in the daemon list, opened. - - FIXME: leave the system wide shm mutex */ - - parameters.out.shm_id = tempnode->shm_id; - if (check_and_dup_handle (GetCurrentProcess (), from_process_handle, - token_handle, - DUPLICATE_SAME_ACCESS, - tempnode->filemap, ¶meters.out.filemap, - TRUE) != 0) - { - printf ("error duplicating filemap handle (%lu)\n", - GetLastError ()); - header.error_code = EACCES; - CloseHandle (token_handle); -/* mutex et al */ - return; - } - if (check_and_dup_handle (GetCurrentProcess (), from_process_handle, - token_handle, - DUPLICATE_SAME_ACCESS, - tempnode->attachmap, - ¶meters.out.attachmap, TRUE) != 0) - { - printf ("error duplicating attachmap handle (%lu)\n", - GetLastError ()); - header.error_code = EACCES; - CloseHandle (from_process_handle); - CloseHandle (token_handle); -/* more cleanup... yay! */ - return; - } - CloseHandle (token_handle); + segment_t *previous = NULL; + const segment_t *const tmp = find (segptr->_intid, &previous); + + assert (tmp == segptr); + assert (previous ? previous->_next == segptr : _segments_head == segptr); + + if (previous) + previous->_next = segptr->_next; + else + _segments_head = segptr->_next; + + assert (_shm_ids > 0); + _shm_ids -= 1; + _shm_tot -= segptr->_ds.shm_segsz; + + safe_delete (segptr); +} + +/*---------------------------------------------------------------------------* + * client_request_shm::client_request_shm () + *---------------------------------------------------------------------------*/ + +client_request_shm::client_request_shm () + : client_request (CYGSERVER_REQUEST_SHM, + &_parameters, sizeof (_parameters)) +{ + // verbose: syscall_printf ("created"); +} + +/*---------------------------------------------------------------------------* + * client_request_shm::serve () + *---------------------------------------------------------------------------*/ + +void +client_request_shm::serve (transport_layer_base *const conn, + process_cache *const cache) +{ + assert (conn); + + assert (!error_code ()); + + if (msglen () != sizeof (_parameters.in)) + { + syscall_printf ("bad request body length: expecting %lu bytes, got %lu", + sizeof (_parameters), msglen ()); + error_code (EINVAL); + msglen (0); return; } - header.error_code = ENOSYS; - CloseHandle (token_handle); + // FIXME: Get a return code out of this and don't continue on error. + conn->impersonate_client (); + + class process *const client = cache->process (_parameters.in.cygpid, + _parameters.in.winpid); + + if (!client) + { + error_code (EAGAIN); + msglen (0); + return; + } + int result = -EINVAL; - return; + switch (_parameters.in.shmop) + { + case SHMOP_shmget: + result = shmmgr.shmget (_parameters.out.shmid, + _parameters.in.key, _parameters.in.size, + _parameters.in.shmflg, + _parameters.in.uid, _parameters.in.gid, + client); + break; + + case SHMOP_shmat: + result = shmmgr.shmat (_parameters.out.hFileMap, + _parameters.in.shmid, _parameters.in.shmflg, + client); + break; + + case SHMOP_shmdt: + result = shmmgr.shmdt (_parameters.in.shmid, client); + break; + + case SHMOP_shmctl: + result = shmmgr.shmctl (_parameters.out.shmid, + _parameters.out.ds, _parameters.out.shminfo, + _parameters.out.shm_info, + _parameters.in.shmid, _parameters.in.cmd, + _parameters.in.ds, + client); + break; + } + + client->release (); + conn->revert_to_self (); + + if (result < 0) + { + error_code (-result); + msglen (0); + } + else + msglen (sizeof (_parameters.out)); } diff --git a/winsup/cygserver/shm.h b/winsup/cygserver/shm.h index f1dcaa53f..b1ff353da 100755 --- a/winsup/cygserver/shm.h +++ b/winsup/cygserver/shm.h @@ -1,7 +1,9 @@ -/* cygserver_shm.h +/* cygserver_shm.h: Single unix specification IPC interface for Cygwin. - Copyright 2001, 2002 Red Hat Inc. - Written by Robert Collins <rbtcollins@hotmail.com> + Copyright 2002 Red Hat, Inc. + + Written by Conrad Scott <conrad.scott@dsl.pipex.com>. + Based on code by Robert Collins <robert.collins@hotmail.com>. This file is part of Cygwin. @@ -9,84 +11,137 @@ This software is a copyrighted work licensed under the terms of the Cygwin license. Please consult the file "CYGWIN_LICENSE" for details. */ +#ifndef __CYGSERVER_SHM_H__ +#define __CYGSERVER_SHM_H__ + #include <sys/types.h> -#include "cygwin/cygserver_transport.h" +#include <cygwin/shm.h> + +#include <assert.h> +#include <limits.h> + +#include "cygserver_ipc.h" + #include "cygwin/cygserver.h" -#define SHM_CREATE 0 -#define SHM_REATTACH 1 -#define SHM_ATTACH 2 -#define SHM_DETACH 3 -#define SHM_DEL 4 +/*---------------------------------------------------------------------------* + * Values for the shminfo entries. + * + * Nb. The values are segregated between two enums so that the `small' + * values aren't promoted to `unsigned long' equivalents. + *---------------------------------------------------------------------------*/ +enum + { + SHMMAX = ULONG_MAX, + SHMSEG = ULONG_MAX, + SHMALL = ULONG_MAX + }; + +enum + { + SHMMIN = 1, + SHMMNI = IPCMNI // Must be <= IPCMNI. + }; + +/*---------------------------------------------------------------------------* + * class client_request_shm + *---------------------------------------------------------------------------*/ -class client_request_shm : public client_request -{ - public: #ifndef __INSIDE_CYGWIN__ - virtual void serve (transport_layer_base *conn, process_cache *cache); +class transport_layer_base; +class process_cache; #endif - client_request_shm (key_t, size_t, int, char psdbuf[4096], pid_t); - client_request_shm (); - client_request_shm (int, int, pid_t); - client_request_shm (int, int); - union { - struct {int type; pid_t pid; int shm_id; key_t key; size_t size; int shmflg; char sd_buf[4096];} in; - struct {int shm_id; HANDLE filemap; HANDLE attachmap; key_t key;} out; - } parameters; -}; -#ifndef __INSIDE_CYGWIN__ -class shm_cleanup : cleanup_routine +class client_request_shm : public client_request { + friend class client_request; + public: - virtual void cleanup (long winpid); -}; + enum shmop_t + { + SHMOP_shmat, + SHMOP_shmctl, + SHMOP_shmdt, + SHMOP_shmget + }; + +#ifdef __INSIDE_CYGWIN__ + client_request_shm (int shmid, int shmflg); // shmat + client_request_shm (int shmid, int cmd, const struct shmid_ds *); // shmctl + client_request_shm (int shmid); // shmdt + client_request_shm (key_t, size_t, int shmflg); // shmget #endif -#if 0 -class _shmattach { -public: - void *data; - class _shmattach *next; -}; -class shmid_ds { -public: - struct ipc_perm shm_perm; - size_t shm_segsz; - pid_t shm_lpid; - pid_t shm_cpid; - shmatt_t shm_nattch; - time_t shm_atime; - time_t shm_dtime; - time_t shm_ctime; - HANDLE filemap; - HANDLE attachmap; - void *mapptr; - class _shmattach *attachhead; -}; + // Accessors for out parameters. -class shmnode { -public: - class shmid_ds * shmid; - class shmnode *next; - key_t key; -}; -//.... -struct shmid_ds { - struct ipc_perm shm_perm; - size_t shm_segsz; - pid_t shm_lpid; - pid_t shm_cpid; - shmatt_t shm_nattch; - time_t shm_atime; - time_t shm_dtime; - time_t shm_ctime; -}; + int shmid () const + { + assert (!error_code ()); + return _parameters.out.shmid; + } + + HANDLE hFileMap () const + { + assert (!error_code ()); + return _parameters.out.hFileMap; + } + + const struct shmid_ds & ds () const + { + assert (!error_code ()); + return _parameters.out.ds; + } + + const struct shminfo & shminfo () const + { + assert (!error_code ()); + return _parameters.out.shminfo; + } + + const struct shm_info & shm_info () const + { + assert (!error_code ()); + return _parameters.out.shm_info; + } -void *shmat(int, const void *, int); -int shmctl(int, int, struct shmid_ds *); -int shmdt(const void *); -int shmget(key_t, size_t, int); +private: + union + { + struct + { + shmop_t shmop; + key_t key; + size_t size; + int shmflg; + int shmid; + int cmd; + pid_t cygpid; + DWORD winpid; + uid_t uid; + gid_t gid; + struct shmid_ds ds; + } in; + struct { + int shmid; + union + { + HANDLE hFileMap; + struct shmid_ds ds; + struct shminfo shminfo; + struct shm_info shm_info; + }; + } out; + } _parameters; + +#ifndef __INSIDE_CYGWIN__ + client_request_shm (); +#endif + +#ifndef __INSIDE_CYGWIN__ + virtual void serve (transport_layer_base *, process_cache *); #endif +}; + +#endif /* __CYGSERVER_SHM_H__ */ diff --git a/winsup/cygserver/threaded_queue.cc b/winsup/cygserver/threaded_queue.cc index 321fa1612..ba0fe4178 100644 --- a/winsup/cygserver/threaded_queue.cc +++ b/winsup/cygserver/threaded_queue.cc @@ -4,247 +4,405 @@ Written by Robert Collins <rbtcollins@hotmail.com> - This file is part of Cygwin. +This file is part of Cygwin. - This software is a copyrighted work licensed under the terms of the - Cygwin license. Please consult the file "CYGWIN_LICENSE" for - details. */ +This software is a copyrighted work licensed under the terms of the +Cygwin license. Please consult the file "CYGWIN_LICENSE" for +details. */ +#include "woutsup.h" + +#include <assert.h> #include <errno.h> #include <stdio.h> #include <unistd.h> -#include <windows.h> #include <sys/types.h> #include <stdlib.h> -#include "wincap.h" #include "threaded_queue.h" -#define DEBUG 1 -#define debug_printf if (DEBUG) printf + +/*****************************************************************************/ + +/* queue_request */ + +queue_request::~queue_request () +{} + +/*****************************************************************************/ /* threaded_queue */ -DWORD WINAPI -worker_function (LPVOID LpParam) +threaded_queue::threaded_queue (const size_t initial_workers) + : _workers_count (0), + _running (false), + _submitters_head (NULL), + _requests_count (0), + _requests_head (NULL), + _requests_sem (NULL) { - class threaded_queue *queue = (class threaded_queue *) LpParam; - class queue_request *request; - /* FIXME use a threadsafe pop instead for speed? */ - while (queue->active) + InitializeCriticalSection (&_queue_lock); + + // This semaphore's count is the number of requests on the queue. + // The maximum count (129792) is calculated as MAXIMUM_WAIT_OBJECTS + // multiplied by max. threads per process (2028?), which is (a few) + // more requests than could ever be pending with the current design. + + _requests_sem = CreateSemaphore (NULL, // SECURITY_ATTRIBUTES + 0, // Initial count + 129792, // Maximum count + NULL); // Anonymous + + if (!_requests_sem) { - EnterCriticalSection (&queue->queuelock); - while (!queue->request && queue->active) - { - LeaveCriticalSection (&queue->queuelock); - DWORD rc = WaitForSingleObject (queue->event, INFINITE); - if (rc == WAIT_FAILED) - { - printf ("Wait for event failed\n"); - queue->running--; - ExitThread (0); - } - EnterCriticalSection (&queue->queuelock); - } - if (!queue->active) - { - queue->running--; - LeaveCriticalSection (&queue->queuelock); - ExitThread (0); - } - /* not needed, but it is efficient */ - request = - (class queue_request *) InterlockedExchangePointer (&queue->request, - queue->request-> - next); - LeaveCriticalSection (&queue->queuelock); - request->process (); - delete request; + system_printf (("failed to create the request queue semaphore, " + "error = %lu"), + GetLastError ()); + abort (); } - queue->running--; - ExitThread (0); + + create_workers (initial_workers); } -void -threaded_queue::create_workers () +threaded_queue::~threaded_queue () { - InitializeCriticalSection (&queuelock); - if ((event = CreateEvent (NULL, FALSE, FALSE, NULL)) == NULL) + if (_running) + stop (); + + debug_printf ("deleting all pending queue requests"); + queue_request *reqptr = _requests_head; + while (reqptr) { - printf ("Failed to create event queue (%lu), terminating\n", - GetLastError ()); - exit (1); + queue_request *const ptr = reqptr; + reqptr = reqptr->_next; + safe_delete (ptr); } - active = true; - /* FIXME: Use a stack pair and create threads on the fly whenever - * we have to to service a request. - */ - for (unsigned int i = 0; i < initial_workers; i++) + DeleteCriticalSection (&_queue_lock); + if (_requests_sem) + (void) CloseHandle (_requests_sem); +} + +/* FIXME: return success or failure rather than quitting */ +void +threaded_queue::add_submission_loop (queue_submission_loop *const submitter) +{ + assert (this); + assert (submitter); + assert (submitter->_queue == this); + assert (!submitter->_next); + + submitter->_next = + TInterlockedExchangePointer (&_submitters_head, submitter); + + if (_running) + submitter->start (); +} + +bool +threaded_queue::start () +{ + EnterCriticalSection (&_queue_lock); + const bool was_running = _running; + _running = true; + queue_submission_loop *loopptr = _submitters_head; + LeaveCriticalSection (&_queue_lock); + + if (!was_running) { - HANDLE hThread; - DWORD tid; - hThread = CreateThread (NULL, 0, worker_function, this, 0, &tid); - if (hThread == NULL) + debug_printf ("starting all queue submission loops"); + + while (loopptr) { - printf ("Failed to create thread (%lu), terminating\n", - GetLastError ()); - exit (1); + queue_submission_loop *const ptr = loopptr; + loopptr = loopptr->_next; + ptr->start (); } - CloseHandle (hThread); - running++; } + + return was_running; } -void -threaded_queue::cleanup () +bool +threaded_queue::stop () { - /* harvest the threads */ - active = false; - /* kill the request processing loops */ - queue_process_param *reqloop; - /* make sure we don't race with a incoming request creation */ - EnterCriticalSection (&queuelock); - reqloop = - (queue_process_param *) InterlockedExchangePointer (&process_head, NULL); - while (reqloop) + EnterCriticalSection (&_queue_lock); + const bool was_running = _running; + _running = false; + queue_submission_loop *loopptr = _submitters_head; + LeaveCriticalSection (&_queue_lock); + + if (was_running) { - queue_process_param *t = reqloop; - reqloop = reqloop->next; - delete t; + debug_printf ("stopping all queue submission loops"); + while (loopptr) + { + queue_submission_loop *const ptr = loopptr; + loopptr = loopptr->_next; + ptr->stop (); + } + + ReleaseSemaphore (_requests_sem, _workers_count, NULL); + while (_workers_count) + { + debug_printf (("waiting for worker threads to terminate: " + "%lu still running"), + _workers_count); + Sleep (1000); + } + debug_printf ("all worker threads have terminated"); } - LeaveCriticalSection (&queuelock); - if (!running) - return; - printf ("Waiting for current queue threads to terminate\n"); - for (int n = running; n; n--) - PulseEvent (event); - while (running) - sleep (1); - DeleteCriticalSection (&queuelock); - CloseHandle (event); + + return was_running; } /* FIXME: return success or failure */ void -threaded_queue::add (queue_request * therequest) +threaded_queue::add (queue_request *const therequest) { - /* safe to not "Try" because workers don't hog this, they wait on the event - */ - EnterCriticalSection (&queuelock); - if (!running) + assert (this); + assert (therequest); + assert (!therequest->_next); + + if (!_workers_count) { - printf ("No worker threads to handle request!\n"); + system_printf ("warning: no worker threads to handle request!"); + // FIXME: And then what? } - if (!request) - request = therequest; + + EnterCriticalSection (&_queue_lock); + if (!_requests_head) + _requests_head = therequest; else { - /* add to the queue end. */ - queue_request *listrequest = request; - while (listrequest->next) - listrequest = listrequest->next; - listrequest->next = therequest; + /* Add to the queue end. */ + queue_request *reqptr = _requests_head; + for (; reqptr->_next; reqptr = reqptr->_next) + {} + assert (reqptr); + assert (!reqptr->_next); + reqptr->_next = therequest; } - PulseEvent (event); - LeaveCriticalSection (&queuelock); + + _requests_count += 1; + assert (_requests_count > 0); + LeaveCriticalSection (&_queue_lock); + + (void) ReleaseSemaphore (_requests_sem, 1, NULL); } -/* FIXME: return success or failure rather than quitting */ +/*static*/ DWORD WINAPI +threaded_queue::start_routine (const LPVOID lpParam) +{ + class threaded_queue *const queue = (class threaded_queue *) lpParam; + assert (queue); + + queue->worker_loop (); + + const long count = InterlockedDecrement (&queue->_workers_count); + assert (count >= 0); + + if (queue->_running) + debug_printf ("worker loop has exited; thread about to terminate"); + + return 0; +} + +/* Called from the constructor: so no need to be thread-safe until the + * worker threads start to be created; thus the interlocked increment + * of the `_workers_count' field. + */ + void -threaded_queue::process_requests (queue_process_param * params, - threaded_queue_thread_function * - request_loop) +threaded_queue::create_workers (const size_t initial_workers) { - if (params->start (request_loop, this) == false) - exit (1); - params->next = - (queue_process_param *) InterlockedExchangePointer (&process_head, - params); + assert (initial_workers > 0); + + for (unsigned int i = 0; i != initial_workers; i++) + { + const long count = InterlockedIncrement (&_workers_count); + assert (count > 0); + + DWORD tid; + const HANDLE hThread = + CreateThread (NULL, 0, start_routine, this, 0, &tid); + + if (!hThread) + { + system_printf ("failed to create thread, error = %lu", + GetLastError ()); + abort (); + } + + (void) CloseHandle (hThread); + } } -/* queue_process_param */ -/* How does a constructor return an error? */ -queue_process_param::queue_process_param (bool ninterruptible):running (false), shutdown (false), -interruptible -(ninterruptible) +void +threaded_queue::worker_loop () { - if (!interruptible) - return; - debug_printf ("creating an interruptible processing thread\n"); - if ((interrupt = CreateEvent (NULL, FALSE, FALSE, NULL)) == NULL) + while (true) { - printf ("Failed to create interrupt event (%lu), terminating\n", - GetLastError ()); - exit (1); + const DWORD rc = WaitForSingleObject (_requests_sem, INFINITE); + if (rc == WAIT_FAILED) + { + system_printf ("wait for request semaphore failed, error = %lu", + GetLastError ()); + return; + } + assert (rc == WAIT_OBJECT_0); + + EnterCriticalSection (&_queue_lock); + if (!_running) + { + LeaveCriticalSection (&_queue_lock); + return; + } + + assert (_requests_head); + queue_request *const reqptr = _requests_head; + _requests_head = reqptr->_next; + + _requests_count -= 1; + assert (_requests_count >= 0); + LeaveCriticalSection (&_queue_lock); + + assert (reqptr); + reqptr->process (); + safe_delete (reqptr); + } +} + +/*****************************************************************************/ + +/* queue_submission_loop */ + +queue_submission_loop::queue_submission_loop (threaded_queue *const queue, + const bool ninterruptible) + : _running (false), + _interrupt_event (NULL), + _queue (queue), + _interruptible (ninterruptible), + _hThread (NULL), + _tid (0), + _next (NULL) +{ + if (_interruptible) + { + // verbose: debug_printf ("creating an interruptible processing thread"); + + _interrupt_event = CreateEvent (NULL, // SECURITY_ATTRIBUTES + FALSE, // Auto-reset + FALSE, // Initially non-signalled + NULL); // Anonymous + + if (!_interrupt_event) + { + system_printf ("failed to create interrupt event, error = %lu", + GetLastError ()); + abort (); + } } } -queue_process_param::~queue_process_param () +queue_submission_loop::~queue_submission_loop () { - if (running) + if (_running) stop (); - if (!interruptible) - return; - CloseHandle (interrupt); + if (_interrupt_event) + (void) CloseHandle (_interrupt_event); + if (_hThread) + (void) CloseHandle (_hThread); } bool - queue_process_param::start (threaded_queue_thread_function * request_loop, - threaded_queue * thequeue) +queue_submission_loop::start () { - queue = thequeue; - hThread = CreateThread (NULL, 0, request_loop, this, 0, &tid); - if (hThread) + assert (this); + assert (!_hThread); + + const bool was_running = _running; + + if (!was_running) { - running = true; - return true; + _running = true; + + _hThread = CreateThread (NULL, 0, start_routine, this, 0, &_tid); + if (!_hThread) + { + system_printf ("failed to create thread, error = %lu", + GetLastError ()); + abort (); + } } - printf ("Failed to create thread (%lu), terminating\n", GetLastError ()); - return false; + + return was_running; } -void -queue_process_param::stop () +bool +queue_submission_loop::stop () { - if (interruptible) + assert (this); + assert (_hThread && _hThread != INVALID_HANDLE_VALUE); + + const bool was_running = _running; + + if (_running) { - InterlockedExchange (&shutdown, true); - PulseEvent (interrupt); - /* Wait up to 50 ms for the thread to exit. If it doesn't _and_ we get - * scheduled again, we print an error and exit. We _should_ loop or - * try resignalling. We don't want to hand here though... - */ - int n = 5; - while (n-- && WaitForSingleObject (hThread, 1000) == WAIT_TIMEOUT); - if (!n) + _running = false; + + if (_interruptible) { - printf ("Process thread didn't shutdown cleanly after 200ms!\n"); - exit (1); + assert (_interrupt_event + && _interrupt_event != INVALID_HANDLE_VALUE); + + SetEvent (_interrupt_event); + + if (WaitForSingleObject (_hThread, 1000) == WAIT_TIMEOUT) + { + system_printf (("request loop thread %lu failed to shutdown " + "when asked politely: about to get heavy"), + _tid); + + if (!TerminateThread (_hThread, 0)) + { + system_printf (("failed to kill request loop thread %lu" + ", error = %lu"), + _tid, GetLastError ()); + abort (); + } + } } else - running = false; - } - else - { - printf ("killing request loop thread %ld\n", tid); - int rc; - if (!(rc = TerminateThread (hThread, 0))) { - printf ("error shutting down request loop worker thread\n"); + // FIXME: could wait to see if the request loop notices that + // the submission loop is no longer running and shuts down + // voluntarily. + + debug_printf ("killing request loop thread %lu", _tid); + + if (!TerminateThread (_hThread, 0)) + system_printf (("failed to kill request loop thread %lu" + ", error = %lu"), + _tid, GetLastError ()); } - running = false; } - CloseHandle (hThread); -} -/* queue_request */ -queue_request::queue_request ():next (NULL) -{ + return was_running; } -void -queue_request::process (void) +/*static*/ DWORD WINAPI +queue_submission_loop::start_routine (const LPVOID lpParam) { - printf ("\n**********************************************\n" - "Oh no! we've hit the base queue_request process() function, and this indicates a coding\n" - "fault !!!\n" "***********************************************\n"); + class queue_submission_loop *const submission_loop = + (class queue_submission_loop *) lpParam; + assert (submission_loop); + + submission_loop->request_loop (); + + debug_printf ("submission loop has exited; thread about to terminate"); + + submission_loop->stop (); + + return 0; } + +/*****************************************************************************/ diff --git a/winsup/cygserver/transport.cc b/winsup/cygserver/transport.cc index 01f044406..8684a6148 100644 --- a/winsup/cygserver/transport.cc +++ b/winsup/cygserver/transport.cc @@ -4,89 +4,48 @@ Written by Robert Collins <rbtcollins@hotmail.com> - This file is part of Cygwin. +This file is part of Cygwin. - This software is a copyrighted work licensed under the terms of the - Cygwin license. Please consult the file "CYGWIN_LICENSE" for - details. */ +This software is a copyrighted work licensed under the terms of the +Cygwin license. Please consult the file "CYGWIN_LICENSE" for +details. */ + +/* to allow this to link into cygwin and the .dll, a little magic is needed. */ +#ifdef __OUTSIDE_CYGWIN__ +#include "woutsup.h" +#else +#include "winsup.h" +#endif -#include <errno.h> -#include <stdio.h> -#include <unistd.h> -#include <windows.h> -#include <sys/types.h> #include <sys/socket.h> -#include <netdb.h> -#include "wincap.h" + +#include "safe_memory.h" + #include "cygwin/cygserver_transport.h" #include "cygwin/cygserver_transport_pipes.h" #include "cygwin/cygserver_transport_sockets.h" -/* to allow this to link into cygwin and the .dll, a little magic is needed. */ -#ifndef __OUTSIDE_CYGWIN__ -#include "winsup.h" -#else -#define debug_printf printf -#endif - /* The factory */ -class transport_layer_base *create_server_transport() +transport_layer_base * +create_server_transport () { - transport_layer_base *temp; - /* currently there is only the base class! */ if (wincap.is_winnt ()) - temp = new transport_layer_pipes (); + return safe_new0 (transport_layer_pipes); else - temp = new transport_layer_sockets (); - return temp; + return safe_new0 (transport_layer_sockets); } - -transport_layer_base::transport_layer_base () -{ - /* should we throw an error of some sort ? */ -} - -void -transport_layer_base::listen () -{ -} - -class transport_layer_base * -transport_layer_base::accept () -{ - return NULL; -} - -void -transport_layer_base::close() -{ -} - -ssize_t -transport_layer_base::read (char *buf, size_t len) -{ - return 0; -} - -ssize_t -transport_layer_base::write (char *buf, size_t len) -{ - return 0; -} - -bool -transport_layer_base::connect () -{ - return false; -} +#ifndef __INSIDE_CYGWIN__ void transport_layer_base::impersonate_client () -{ -} +{} void transport_layer_base::revert_to_self () -{ -} +{} + +#endif /* !__INSIDE_CYGWIN__ */ + +transport_layer_base::~transport_layer_base () +{} diff --git a/winsup/cygserver/transport_pipes.cc b/winsup/cygserver/transport_pipes.cc index f2221700f..f318a7592 100644 --- a/winsup/cygserver/transport_pipes.cc +++ b/winsup/cygserver/transport_pipes.cc @@ -4,207 +4,360 @@ Written by Robert Collins <rbtcollins@hotmail.com> - This file is part of Cygwin. +This file is part of Cygwin. - This software is a copyrighted work licensed under the terms of the - Cygwin license. Please consult the file "CYGWIN_LICENSE" for - details. */ +This software is a copyrighted work licensed under the terms of the +Cygwin license. Please consult the file "CYGWIN_LICENSE" for +details. */ + +/* to allow this to link into cygwin and the .dll, a little magic is needed. */ +#ifdef __OUTSIDE_CYGWIN__ +#include "woutsup.h" +#else +#include "winsup.h" +#endif -#include <errno.h> -#include <stdio.h> -#include <unistd.h> -#include <windows.h> #include <sys/types.h> -#include <sys/socket.h> + +#include <assert.h> +#include <errno.h> #include <netdb.h> -#include "wincap.h" +#include <pthread.h> +#include <unistd.h> + +#include "cygerrno.h" #include "cygwin/cygserver_transport.h" #include "cygwin/cygserver_transport_pipes.h" -/* to allow this to link into cygwin and the .dll, a little magic is needed. */ -#ifndef __OUTSIDE_CYGWIN__ -#include "winsup.h" -#else -#define DEBUG 0 -#define debug_printf if (DEBUG) printf +#ifndef __INSIDE_CYGWIN__ +#include "cygwin/cygserver.h" #endif -//SECURITY_DESCRIPTOR transport_layer_pipes::sd; -//SECURITY_ATTRIBUTES transport_layer_pipes::sec_none_nih, transport_layer_pipes::sec_all_nih; -//bool transport_layer_pipes::inited = false; +enum + { + MAX_WAIT_NAMED_PIPE_RETRY = 64, + WAIT_NAMED_PIPE_TIMEOUT = 10 // milliseconds + }; + +#ifndef __INSIDE_CYGWIN__ + +static pthread_once_t pipe_instance_lock_once = PTHREAD_ONCE_INIT; +static CRITICAL_SECTION pipe_instance_lock; +static long pipe_instance = 0; + +static void +initialise_pipe_instance_lock () +{ + assert (pipe_instance == 0); + InitializeCriticalSection (&pipe_instance_lock); +} + +#endif /* !__INSIDE_CYGWIN__ */ + +#ifndef __INSIDE_CYGWIN__ -transport_layer_pipes::transport_layer_pipes (HANDLE new_pipe) +transport_layer_pipes::transport_layer_pipes (const HANDLE hPipe) + : _pipe_name (""), + _hPipe (hPipe), + _is_accepted_endpoint (true), + _is_listening_endpoint (false) { - inited = false; //FIXME: allow inited, sd, all_nih_.. to be static members - pipe = new_pipe; - if (inited != true) - init_security(); -}; + assert (_hPipe); + assert (_hPipe != INVALID_HANDLE_VALUE); + + init_security (); +} + +#endif /* !__INSIDE_CYGWIN__ */ transport_layer_pipes::transport_layer_pipes () + : _pipe_name ("\\\\.\\pipe\\cygwin_lpc"), + _hPipe (NULL), + _is_accepted_endpoint (false), + _is_listening_endpoint (false) { - inited = false; - pipe = NULL; - strcpy(pipe_name, "\\\\.\\pipe\\cygwin_lpc"); - if (inited != true) - init_security(); + init_security (); } void -transport_layer_pipes::init_security() +transport_layer_pipes::init_security () { + assert (wincap.has_security ()); + /* FIXME: pthread_once or equivalent needed */ - InitializeSecurityDescriptor (&sd, SECURITY_DESCRIPTOR_REVISION); - SetSecurityDescriptorDacl (&sd, TRUE, 0, FALSE); - - sec_none_nih.nLength = sec_all_nih.nLength = sizeof (SECURITY_ATTRIBUTES); - sec_none_nih.bInheritHandle = sec_all_nih.bInheritHandle = FALSE; - sec_none_nih.lpSecurityDescriptor = NULL; - sec_all_nih.lpSecurityDescriptor = &sd; - inited = true; + + InitializeSecurityDescriptor (&_sd, SECURITY_DESCRIPTOR_REVISION); + SetSecurityDescriptorDacl (&_sd, TRUE, NULL, FALSE); + + _sec_all_nih.nLength = sizeof (SECURITY_ATTRIBUTES); + _sec_all_nih.lpSecurityDescriptor = &_sd; + _sec_all_nih.bInheritHandle = FALSE; } -void +transport_layer_pipes::~transport_layer_pipes () +{ + close (); +} + +#ifndef __INSIDE_CYGWIN__ + +int transport_layer_pipes::listen () { + assert (!_hPipe); + assert (!_is_accepted_endpoint); + assert (!_is_listening_endpoint); + + _is_listening_endpoint = true; + /* no-op */ + return 0; } class transport_layer_pipes * -transport_layer_pipes::accept () +transport_layer_pipes::accept (bool *const recoverable) { - if (pipe) + assert (!_hPipe); + assert (!_is_accepted_endpoint); + assert (_is_listening_endpoint); + + pthread_once (&pipe_instance_lock_once, &initialise_pipe_instance_lock); + + EnterCriticalSection (&pipe_instance_lock); + + // Read: http://www.securityinternals.com/research/papers/namedpipe.php + // See also the Microsoft security bulletins MS00-053 and MS01-031. + + // FIXME: Remove FILE_CREATE_PIPE_INSTANCE. + + const bool first_instance = (pipe_instance == 0); + + const HANDLE accept_pipe = + CreateNamedPipe (_pipe_name, + (PIPE_ACCESS_DUPLEX + | (first_instance ? FILE_FLAG_FIRST_PIPE_INSTANCE : 0)), + (PIPE_TYPE_BYTE | PIPE_WAIT), + PIPE_UNLIMITED_INSTANCES, + 0, 0, 1000, + &_sec_all_nih); + + const bool duplicate = (accept_pipe == INVALID_HANDLE_VALUE + && pipe_instance == 0 + && GetLastError () == ERROR_ACCESS_DENIED); + + if (accept_pipe != INVALID_HANDLE_VALUE) + InterlockedIncrement (&pipe_instance); + + LeaveCriticalSection (&pipe_instance_lock); + + if (duplicate) { - debug_printf ("Already have a pipe in this %p\n",this); + *recoverable = false; + system_printf ("failed to create named pipe: " + "is the daemon already running?"); return NULL; } - pipe = CreateNamedPipe (pipe_name, - PIPE_ACCESS_DUPLEX, - PIPE_TYPE_BYTE | PIPE_WAIT, - PIPE_UNLIMITED_INSTANCES, - 0, 0, 1000, - &sec_all_nih ); - if (pipe == INVALID_HANDLE_VALUE) + if (accept_pipe == INVALID_HANDLE_VALUE) { - debug_printf ("error creating pipe (%lu)\n.", GetLastError ()); + debug_printf ("error creating pipe (%lu).", GetLastError ()); + *recoverable = true; // FIXME: case analysis? return NULL; } - if ( !ConnectNamedPipe ( pipe, NULL ) && - GetLastError () != ERROR_PIPE_CONNECTED) + assert (accept_pipe); + + if (!ConnectNamedPipe (accept_pipe, NULL) + && GetLastError () != ERROR_PIPE_CONNECTED) { - printf ("error connecting to pipe (%lu)\n.", GetLastError ()); - CloseHandle (pipe); - pipe = NULL; + debug_printf ("error connecting to pipe (%lu)\n.", GetLastError ()); + (void) CloseHandle (accept_pipe); + *recoverable = true; // FIXME: case analysis? return NULL; } - transport_layer_pipes *new_conn = new transport_layer_pipes (pipe); - pipe = NULL; - - return new_conn; + return safe_new (transport_layer_pipes, accept_pipe); } +#endif /* !__INSIDE_CYGWIN__ */ + void -transport_layer_pipes::close() +transport_layer_pipes::close () { - debug_printf ("closing pipe %p\n", pipe); - if (pipe && pipe != INVALID_HANDLE_VALUE) + // verbose: debug_printf ("closing pipe %p", _hPipe); + + if (_hPipe) { - FlushFileBuffers (pipe); - DisconnectNamedPipe (pipe); - CloseHandle (pipe); + assert (_hPipe != INVALID_HANDLE_VALUE); + +#ifndef __INSIDE_CYGWIN__ + + if (_is_accepted_endpoint) + { + (void) FlushFileBuffers (_hPipe); // Blocks until client reads. + (void) DisconnectNamedPipe (_hPipe); + EnterCriticalSection (&pipe_instance_lock); + (void) CloseHandle (_hPipe); + assert (pipe_instance > 0); + InterlockedDecrement (&pipe_instance); + LeaveCriticalSection (&pipe_instance_lock); + } + else + (void) CloseHandle (_hPipe); + +#else /* __INSIDE_CYGWIN__ */ + + assert (!_is_accepted_endpoint); + (void) ForceCloseHandle (_hPipe); + +#endif /* __INSIDE_CYGWIN__ */ + + _hPipe = NULL; } } ssize_t -transport_layer_pipes::read (char *buf, size_t len) +transport_layer_pipes::read (void *const buf, const size_t len) { - debug_printf ("reading from pipe %p\n", pipe); - if (!pipe || pipe == INVALID_HANDLE_VALUE) - return -1; + // verbose: debug_printf ("reading from pipe %p", _hPipe); - DWORD bytes_read; - DWORD rc = ReadFile (pipe, buf, len, &bytes_read, NULL); - if (!rc) + assert (_hPipe); + assert (_hPipe != INVALID_HANDLE_VALUE); + assert (!_is_listening_endpoint); + + DWORD count; + if (!ReadFile (_hPipe, buf, len, &count, NULL)) { - debug_printf ("error reading from pipe (%lu)\n", GetLastError ()); + debug_printf ("error reading from pipe (%lu)", GetLastError ()); + set_errno (EINVAL); // FIXME? return -1; } - return bytes_read; + + return count; } ssize_t -transport_layer_pipes::write (char *buf, size_t len) +transport_layer_pipes::write (void *const buf, const size_t len) { - debug_printf ("writing to pipe %p\n", pipe); - DWORD bytes_written, rc; - if (!pipe || pipe == INVALID_HANDLE_VALUE) - return -1; + // verbose: debug_printf ("writing to pipe %p", _hPipe); - rc = WriteFile (pipe, buf, len, &bytes_written, NULL); - if (!rc) + assert (_hPipe); + assert (_hPipe != INVALID_HANDLE_VALUE); + assert (!_is_listening_endpoint); + + DWORD count; + if (!WriteFile (_hPipe, buf, len, &count, NULL)) { - debug_printf ("error writing to pipe (%lu)\n", GetLastError ()); + debug_printf ("error writing to pipe, error = %lu", GetLastError ()); + set_errno (EINVAL); // FIXME? return -1; } - return bytes_written; + + return count; } -bool +/* + * This routine holds a static variable, assume_cygserver, that is set + * if the transport has good reason to think that cygserver is + * running, i.e. if if successfully connected to it with the previous + * attempt. If this is set, the code tries a lot harder to get a + * connection, making the assumption that any failures are just + * congestion and overloading problems. + */ + +int transport_layer_pipes::connect () { - if (pipe && pipe != INVALID_HANDLE_VALUE) - { - debug_printf ("Already have a pipe in this %p\n",this); - return false; - } + assert (!_hPipe); + assert (!_is_accepted_endpoint); + assert (!_is_listening_endpoint); - while (1) + static bool assume_cygserver = false; + + BOOL rc = TRUE; + int retries = 0; + + while (rc) { - pipe = CreateFile (pipe_name, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - &sec_all_nih, - OPEN_EXISTING, - 0, NULL); - - if (pipe != INVALID_HANDLE_VALUE) - /* got the pipe */ - return true; - - if (GetLastError () != ERROR_PIPE_BUSY) + _hPipe = CreateFile (_pipe_name, + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + &_sec_all_nih, + OPEN_EXISTING, + SECURITY_IMPERSONATION, + NULL); + + if (_hPipe != INVALID_HANDLE_VALUE) + { + assert (_hPipe); +#ifdef __INSIDE_CYGWIN__ + ProtectHandle (_hPipe); +#endif + assume_cygserver = true; + return 0; + } + + _hPipe = NULL; + + if (!assume_cygserver && GetLastError () != ERROR_PIPE_BUSY) { - debug_printf ("Error opening the pipe (%lu)\n", GetLastError ()); - pipe = NULL; - return false; + debug_printf ("Error opening the pipe (%lu)", GetLastError ()); + return -1; } - if (!WaitNamedPipe (pipe_name, 20000)) - debug_printf ( "error connecting to server pipe after 20 seconds (%lu)\n", GetLastError () ); - /* We loop here, because the pipe exists but is busy. If it doesn't exist - * the != ERROR_PIPE_BUSY will catch it. + + /* Note: `If no instances of the specified named pipe exist, the + * WaitNamedPipe function returns immediately, regardless of the + * time-out value.' Thus the explicit Sleep if the call fails + * with ERROR_FILE_NOT_FOUND. */ + while (retries != MAX_WAIT_NAMED_PIPE_RETRY + && !(rc = WaitNamedPipe (_pipe_name, WAIT_NAMED_PIPE_TIMEOUT))) + { + if (GetLastError () == ERROR_FILE_NOT_FOUND) + Sleep (0); // Give the server a chance. + + retries += 1; + } } + + assert (retries == MAX_WAIT_NAMED_PIPE_RETRY); + + system_printf ("lost connection to cygserver, error = %lu", + GetLastError ()); + + assume_cygserver = false; + + return -1; } +#ifndef __INSIDE_CYGWIN__ + void transport_layer_pipes::impersonate_client () { - debug_printf ("impersonating pipe %p\n", pipe); - if (pipe && pipe != INVALID_HANDLE_VALUE) + assert (_hPipe); + assert (_hPipe != INVALID_HANDLE_VALUE); + assert (_is_accepted_endpoint); + + // verbose: debug_printf ("impersonating pipe %p", _hPipe); + if (_hPipe) { - BOOL rv = ImpersonateNamedPipeClient (pipe); - if (!rv) - debug_printf ("Failed to Impersonate the client, (%lu)\n", GetLastError ()); + assert (_hPipe != INVALID_HANDLE_VALUE); + + if (!ImpersonateNamedPipeClient (_hPipe)) + debug_printf ("Failed to Impersonate the client, (%lu)", + GetLastError ()); } - debug_printf("I am who you are\n"); + // verbose: debug_printf ("I am who you are"); } void transport_layer_pipes::revert_to_self () { + assert (_is_accepted_endpoint); + RevertToSelf (); - debug_printf("I am who I yam\n"); + // verbose: debug_printf ("I am who I yam"); } +#endif /* !__INSIDE_CYGWIN__ */ diff --git a/winsup/cygserver/transport_sockets.cc b/winsup/cygserver/transport_sockets.cc index a3a98b3e5..6ade14bff 100644 --- a/winsup/cygserver/transport_sockets.cc +++ b/winsup/cygserver/transport_sockets.cc @@ -4,128 +4,384 @@ Written by Robert Collins <rbtcollins@hotmail.com> - This file is part of Cygwin. +This file is part of Cygwin. - This software is a copyrighted work licensed under the terms of the - Cygwin license. Please consult the file "CYGWIN_LICENSE" for - details. */ +This software is a copyrighted work licensed under the terms of the +Cygwin license. Please consult the file "CYGWIN_LICENSE" for +details. */ +/* to allow this to link into cygwin and the .dll, a little magic is needed. */ +#ifdef __OUTSIDE_CYGWIN__ +#include "woutsup.h" +#else +#include "winsup.h" +#endif + +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/stat.h> + +#include <assert.h> #include <errno.h> #include <stdio.h> #include <unistd.h> -#include <windows.h> -#include <sys/types.h> -#include <sys/socket.h> -#include <netdb.h> -#include "wincap.h" + #include "cygwin/cygserver_transport.h" #include "cygwin/cygserver_transport_sockets.h" /* to allow this to link into cygwin and the .dll, a little magic is needed. */ #ifndef __OUTSIDE_CYGWIN__ -#include "winsup.h" -extern "C" int -cygwin_socket (int af, int type, int protocol); -extern "C" int -cygwin_connect (int fd, - const struct sockaddr *name, - int namelen); -extern "C" int -cygwin_accept (int fd, struct sockaddr *peer, int *len); -extern "C" int -cygwin_listen (int fd, int backlog); -extern "C" int -cygwin_bind (int fd, const struct sockaddr *my_addr, int addrlen); -#else -#define cygwin_accept(A,B,C) ::accept(A,B,C) -#define cygwin_socket(A,B,C) ::socket(A,B,C) -#define cygwin_listen(A,B) ::listen(A,B) -#define cygwin_bind(A,B,C) ::bind(A,B,C) -#define cygwin_connect(A,B,C) ::connect(A,B,C) -#define debug_printf printf -#endif +extern "C" int cygwin_accept (int fd, struct sockaddr *, int *len); +extern "C" int cygwin_bind (int fd, const struct sockaddr *, int len); +extern "C" int cygwin_connect (int fd, const struct sockaddr *, int len); +extern "C" int cygwin_listen (int fd, int backlog); +extern "C" int cygwin_shutdown (int fd, int how); +extern "C" int cygwin_socket (int af, int type, int protocol); + +#else /* __OUTSIDE_CYGWIN__ */ + +#define cygwin_accept(A,B,C) ::accept (A,B,C) +#define cygwin_bind(A,B,C) ::bind (A,B,C) +#define cygwin_connect(A,B,C) ::connect (A,B,C) +#define cygwin_listen(A,B) ::listen (A,B) +#define cygwin_shutdown(A,B) ::shutdown (A,B) +#define cygwin_socket(A,B,C) ::socket (A,B,C) + +#endif /* __OUTSIDE_CYGWIN__ */ -transport_layer_sockets::transport_layer_sockets (int newfd): fd(newfd) +enum + { + MAX_CONNECT_RETRY = 64 + }; + +transport_layer_sockets::transport_layer_sockets (const int fd) + : _fd (fd), + _addr_len (0), + _is_accepted_endpoint (true), + _is_listening_endpoint (false) { - /* This may not be needed in this constructor - it's only used - * when creating a connection via bind or connect - */ - sockdetails.sa_family = AF_UNIX; - strcpy (sockdetails.sa_data, "/tmp/cygdaemo"); - sdlen = strlen(sockdetails.sa_data) + sizeof(sockdetails.sa_family); -}; - -transport_layer_sockets::transport_layer_sockets (): fd (-1) + assert (_fd != -1); + + memset (&_addr, '\0', sizeof (_addr)); +} + +transport_layer_sockets::transport_layer_sockets () + : _fd (-1), + _addr_len (0), + _is_accepted_endpoint (false), + _is_listening_endpoint (false) { - sockdetails.sa_family = AF_UNIX; - strcpy (sockdetails.sa_data, "/tmp/cygdaemo"); - sdlen = strlen(sockdetails.sa_data) + sizeof(sockdetails.sa_family); + memset (&_addr, '\0', sizeof (_addr)); + + _addr.sun_family = AF_UNIX; + strcpy (_addr.sun_path, "/tmp/cygdaemo"); // FIXME: $TMP? + _addr_len = SUN_LEN (&_addr); } -void +transport_layer_sockets::~transport_layer_sockets () +{ + close (); +} + +#ifndef __INSIDE_CYGWIN__ + +int transport_layer_sockets::listen () { - /* we want a thread pool based approach. */ - if ((fd = cygwin_socket (AF_UNIX, SOCK_STREAM,0)) < 0) - printf ("Socket not created error %d\n", errno); - if (cygwin_bind(fd, &sockdetails, sdlen)) - printf ("Bind doesn't like you. Tsk Tsk. Bind said %d\n", errno); - if (cygwin_listen(fd, 5) < 0) - printf ("And the OS just isn't listening, all it says is %d\n", errno); + assert (_fd == -1); + assert (!_is_accepted_endpoint); + assert (!_is_listening_endpoint); + + debug_printf ("listen () [this = %p]", this); + + struct stat sbuf; + + if (stat (_addr.sun_path, &sbuf) == -1) + { + if (errno != ENOENT) + { + system_printf ("cannot access socket file `%s': %s", + _addr.sun_path, strerror (errno)); + return -1; + } + } + else if (S_ISSOCK (sbuf.st_mode)) + { + // The socket already exists: is a duplicate cygserver running? + + const int newfd = cygwin_socket (AF_UNIX, SOCK_STREAM, 0); + + if (newfd == -1) + { + system_printf ("failed to create UNIX domain socket: %s", + strerror (errno)); + return -1; + } + + if (cygwin_connect (newfd, (struct sockaddr *) &_addr, _addr_len) == 0) + { + system_printf ("the daemon is already running"); + (void) cygwin_shutdown (newfd, SHUT_WR); + char buf[BUFSIZ]; + while (::read (newfd, buf, sizeof (buf)) > 0) + {} + (void) ::close (newfd); + return -1; + } + + if (unlink (_addr.sun_path) == -1) + { + system_printf ("failed to remove `%s': %s", + _addr.sun_path, strerror (errno)); + (void) ::close (newfd); + return -1; + } + } + else + { + system_printf ("cannot create socket `%s': File already exists", + _addr.sun_path); + return -1; + } + + _fd = cygwin_socket (AF_UNIX, SOCK_STREAM, 0); + + if (_fd == -1) + { + system_printf ("failed to create UNIX domain socket: %s", + strerror (errno)); + return -1; + } + + if (cygwin_bind (_fd, (struct sockaddr *) &_addr, _addr_len) == -1) + { + const int saved_errno = errno; + close (); + errno = saved_errno; + system_printf ("failed to bind UNIX domain socket `%s': %s", + _addr.sun_path, strerror (errno)); + return -1; + } + + _is_listening_endpoint = true; // i.e. this really means "have bound". + + if (cygwin_listen (_fd, SOMAXCONN) == -1) + { + const int saved_errno = errno; + close (); + errno = saved_errno; + system_printf ("failed to listen on UNIX domain socket `%s': %s", + _addr.sun_path, strerror (errno)); + return -1; + } + + debug_printf ("0 = listen () [this = %p, fd = %d]", this, _fd); + + return 0; } class transport_layer_sockets * -transport_layer_sockets::accept () +transport_layer_sockets::accept (bool *const recoverable) { - /* FIXME: check we have listened */ - int new_fd; + assert (_fd != -1); + assert (!_is_accepted_endpoint); + assert (_is_listening_endpoint); + + debug_printf ("accept () [this = %p, fd = %d]", this, _fd); + + struct sockaddr_un client_addr; + socklen_t client_addr_len = sizeof (client_addr); - if ((new_fd = cygwin_accept(fd, &sockdetails, &sdlen)) < 0) + const int accept_fd = + cygwin_accept (_fd, (struct sockaddr *) &client_addr, &client_addr_len); + + if (accept_fd == -1) { - printf ("Nup, could' accept. %d\n",errno); + system_printf ("failed to accept connection: %s", strerror (errno)); + switch (errno) + { + case ECONNABORTED: + case EINTR: + case EMFILE: + case ENFILE: + case ENOBUFS: + case ENOMEM: + *recoverable = true; + break; + + default: + *recoverable = false; + break; + } return NULL; } - transport_layer_sockets *new_conn = new transport_layer_sockets (new_fd); - - return new_conn; + debug_printf ("%d = accept () [this = %p, fd = %d]", accept_fd, this, _fd); + return safe_new (transport_layer_sockets, accept_fd); } +#endif /* !__INSIDE_CYGWIN__ */ + void -transport_layer_sockets::close() +transport_layer_sockets::close () { - /* FIXME - are we open? */ - ::close (fd); + debug_printf ("close () [this = %p, fd = %d]", this, _fd); + + if (_is_listening_endpoint) + (void) unlink (_addr.sun_path); + + if (_fd != -1) + { + (void) cygwin_shutdown (_fd, SHUT_WR); + if (!_is_listening_endpoint) + { + char buf[BUFSIZ]; + while (::read (_fd, buf, sizeof (buf)) > 0) + {} + } + (void) ::close (_fd); + _fd = -1; + } + + _is_listening_endpoint = false; } ssize_t -transport_layer_sockets::read (char *buf, size_t len) +transport_layer_sockets::read (void *const buf, const size_t buf_len) { - /* FIXME: are we open? */ - return ::read (fd, buf, len); + assert (_fd != -1); + assert (!_is_listening_endpoint); + + assert (buf); + assert (buf_len > 0); + + // verbose: debug_printf ("read (buf = %p, len = %u) [this = %p, fd = %d]", + // buf, buf_len, this, _fd); + + char *read_buf = static_cast<char *> (buf); + size_t read_buf_len = buf_len; + ssize_t res = 0; + + while (read_buf_len != 0 + && (res = ::read (_fd, read_buf, read_buf_len)) > 0) + { + read_buf += res; + read_buf_len -= res; + + assert (read_buf_len >= 0); + } + + if (res != -1) + { + if (res == 0) + errno = EIO; // FIXME? + + res = buf_len - read_buf_len; + } + + if (res != static_cast<ssize_t> (buf_len)) + debug_printf ("%d = read (buf = %p, len = %u) [this = %p, fd = %d]: %s", + res, buf, buf_len, this, _fd, + (res == -1 ? strerror (errno) : "EOF")); + else + { + // verbose: debug_printf ("%d = read (buf = %p, len = %u) [this = %p, fd = %d]", + // res, buf, buf_len, this, _fd); + } + + return res; } ssize_t -transport_layer_sockets::write (char *buf, size_t len) +transport_layer_sockets::write (void *const buf, const size_t buf_len) { - /* FIXME: are we open? */ - return ::write (fd, buf, len); + assert (_fd != -1); + assert (!_is_listening_endpoint); + + assert (buf); + assert (buf_len > 0); + + // verbose: debug_printf ("write (buf = %p, len = %u) [this = %p, fd = %d]", + // buf, buf_len, this, _fd); + + char *write_buf = static_cast<char *> (buf); + size_t write_buf_len = buf_len; + ssize_t res = 0; + + while (write_buf_len != 0 + && (res = ::write (_fd, write_buf, write_buf_len)) > 0) + { + write_buf += res; + write_buf_len -= res; + + assert (write_buf_len >= 0); + } + + if (res != -1) + { + if (res == 0) + errno = EIO; // FIXME? + + res = buf_len - write_buf_len; + } + + if (res != static_cast<ssize_t> (buf_len)) + debug_printf ("%d = write (buf = %p, len = %u) [this = %p, fd = %d]: %s", + res, buf, buf_len, this, _fd, + (res == -1 ? strerror (errno) : "EOF")); + else + { + // verbose: debug_printf ("%d = write (buf = %p, len = %u) [this = %p, fd = %d]", + // res, buf, buf_len, this, _fd); + } + + return res; } -bool +int transport_layer_sockets::connect () { - /* are we already connected? */ - if (fd != -1) - return false; - fd = cygwin_socket (AF_UNIX, SOCK_STREAM, 0); - if (cygwin_connect (fd, &sockdetails, sdlen) < 0) + assert (_fd == -1); + assert (!_is_accepted_endpoint); + assert (!_is_listening_endpoint); + + static bool assume_cygserver = false; + + debug_printf ("connect () [this = %p]", this); + + for (int retries = 0; retries != MAX_CONNECT_RETRY; retries++) { - debug_printf("client connect failure %d\n", errno); - ::close (fd); - return false; + _fd = cygwin_socket (AF_UNIX, SOCK_STREAM, 0); + + if (_fd == -1) + { + system_printf ("failed to create UNIX domain socket: %s", + strerror (errno)); + return -1; + } + + if (cygwin_connect (_fd, (struct sockaddr *) &_addr, _addr_len) == 0) + { + assume_cygserver = true; + debug_printf ("0 = connect () [this = %p, fd = %d]", this, _fd); + return 0; + } + + if (!assume_cygserver || errno != ECONNREFUSED) + { + debug_printf ("failed to connect to server: %s", strerror (errno)); + (void) ::close (_fd); + _fd = -1; + return -1; + } + + (void) ::close (_fd); + _fd = -1; + Sleep (0); // Give the server a chance. } - return true; + + debug_printf ("failed to connect to server: %s", strerror (errno)); + return -1; } diff --git a/winsup/cygserver/woutsup.h b/winsup/cygserver/woutsup.h new file mode 100644 index 000000000..c048f1c19 --- /dev/null +++ b/winsup/cygserver/woutsup.h @@ -0,0 +1,110 @@ +/* woutsup.h: for Cygwin code compiled outside the DLL (i.e. cygserver). + + Copyright 2002 Red Hat, Inc. + +This file is part of Cygwin. + +This software is a copyrighted work licensed under the terms of the +Cygwin license. Please consult the file "CYGWIN_LICENSE" for +details. */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#ifdef __INSIDE_CYGWIN__ +#error "woutsup.h is not for code being compiled inside the dll" +#endif + +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0500 +#endif + +#if _WIN32_WINNT < 0x0500 +#undef _WIN32_WINNT +#define _WIN32_WINNT 0x0500 +#endif + +#define WIN32_LEAN_AND_MEAN 1 +#define _WINGDI_H +#define _WINUSER_H +#define _WINNLS_H +#define _WINVER_H +#define _WINNETWK_H +#define _WINSVC_H +#include <windows.h> +#include <wincrypt.h> +#include <lmcons.h> +#undef _WINGDI_H +#undef _WINUSER_H +#undef _WINNLS_H +#undef _WINVER_H +#undef _WINNETWK_H +#undef _WINSVC_H + +#include "wincap.h" + +/* The one function we use from winuser.h most of the time */ +extern "C" DWORD WINAPI GetLastError (void); + +extern int cygserver_running; + +#if !defined(__STDC_VERSION__) || __STDC_VERSION__ >= 199900L +#define NEW_MACRO_VARARGS +#endif + +/* + * A reproduction of the <sys/strace.h> macros. This allows code that + * runs both inside and outside the Cygwin DLL to use the same macros + * for logging messages. + */ + +extern "C" void __cygserver__printf (const char *, const char *, ...); + +#ifdef NEW_MACRO_VARARGS + +#define system_printf(...) \ + do \ + { \ + __cygserver__printf (__PRETTY_FUNCTION__, __VA_ARGS__); \ + } while (false) + +#define __noop_printf(...) do {;} while (false) + +#else /* !NEW_MACRO_VARARGS */ + +#define system_printf(args...) \ + do \ + { \ + __cygserver__printf (__PRETTY_FUNCTION__, ## args); \ + } while (false) + +#define __noop_printf(args...) do {;} while (false) + +#endif /* !NEW_MACRO_VARARGS */ + +#ifdef DEBUGGING +#define debug_printf system_printf +#define paranoid_printf system_printf +#define select_printf system_printf +#define sigproc_printf system_printf +#define syscall_printf system_printf +#define termios_printf system_printf +#define wm_printf system_printf +#define minimal_printf system_printf +#define malloc_printf system_printf +#define thread_printf system_printf +#else +#define debug_printf __noop_printf +#define paranoid_printf __noop_printf +#define select_printf __noop_printf +#define sigproc_printf __noop_printf +#define syscall_printf __noop_printf +#define termios_printf __noop_printf +#define wm_printf __noop_printf +#define minimal_printf __noop_printf +#define malloc_printf __noop_printf +#define thread_printf __noop_printf +#endif + +#include "safe_memory.h" |