From 4b2ab4975121a51150cf4db64e49f2a6c96d779b Mon Sep 17 00:00:00 2001 From: Ken Raeburn Date: Tue, 5 Feb 2008 18:33:20 +0000 Subject: [PATCH] more eol-style git-svn-id: svn://anonsvn.mit.edu/krb5/trunk@20218 dc483132-0cff-0310-8789-dd5450dbe970 --- src/ccapi/common/win/OldCC/autolock.hxx | 106 +-- src/ccapi/common/win/OldCC/ccutil.cxx | 374 ++++---- src/ccapi/common/win/OldCC/ccutil.def | 8 +- src/ccapi/common/win/OldCC/init.cxx | 374 ++++---- src/ccapi/common/win/OldCC/init.hxx | 204 ++--- src/ccapi/common/win/OldCC/opts.cxx | 376 ++++---- src/ccapi/common/win/OldCC/opts.hxx | 112 +-- src/ccapi/common/win/OldCC/secure.cxx | 320 +++---- src/ccapi/common/win/OldCC/secure.hxx | 120 +-- src/ccapi/common/win/OldCC/util.cxx | 1038 +++++++++++------------ src/ccapi/common/win/ccs_reply.Acf | 62 +- src/ccapi/common/win/ccs_reply.Idl | 120 +-- src/ccapi/common/win/ccs_request.Acf | 62 +- src/ccapi/common/win/ccs_request.idl | 116 +-- src/ccapi/doc/CCAPI-Windows-Design.html | 296 +++---- src/ccapi/lib/win/OldCC/client.cxx | 778 ++++++++--------- src/ccapi/lib/win/OldCC/rpc.cxx | 156 ++-- src/ccapi/lib/win/ccapi.def | 76 +- src/ccapi/lib/win/ccapi_os_ipc.cxx | 744 ++++++++-------- src/ccapi/lib/win/dllmain.cxx | 558 ++++++------ src/ccapi/test/Makefile.w32 | 148 ++-- 21 files changed, 3074 insertions(+), 3074 deletions(-) diff --git a/src/ccapi/common/win/OldCC/autolock.hxx b/src/ccapi/common/win/OldCC/autolock.hxx index 9fc759514..bbd773488 100644 --- a/src/ccapi/common/win/OldCC/autolock.hxx +++ b/src/ccapi/common/win/OldCC/autolock.hxx @@ -1,53 +1,53 @@ -/* - - Copyright (C) 1998 Danilo Almeida. All rights reserved. - - automatic stack-based locking object - - This file is part of FIFS (Framework for Implementing File Systems). - - This software is distributed with NO WARRANTY OF ANY KIND. No - author or distributor accepts any responsibility for the - consequences of using it, or for whether it serves any particular - purpose or works at all, unless he or she says so in writing. - Refer to the included modified Alladin Free Public License (the - "License") for full details. - - Every copy of this software must include a copy of the License, in - a plain ASCII text file named COPYING. The License grants you the - right to copy, modify and redistribute this software, but only - under certain conditions described in the License. Among other - things, the License requires that the copyright notice and this - notice be preserved on all copies. - -*/ - -#ifndef __AUTOLOCK_HXX__ -#define __AUTOLOCK_HXX__ - -#include - -class CcOsLock { - CRITICAL_SECTION cs; - bool valid; -public: - CcOsLock() {InitializeCriticalSection(&cs); valid = true; } - ~CcOsLock() {DeleteCriticalSection(&cs); valid = false;} - void lock() {if (valid) EnterCriticalSection(&cs);} - void unlock() {if (valid) LeaveCriticalSection(&cs);} -#if 0 - bool trylock() {return valid ? (TryEnterCriticalSection(&cs) ? true : false) - : false; } -#endif -}; - -class CcAutoLock { - CcOsLock& m_lock; -public: - static void Start(CcAutoLock*& a, CcOsLock& lock) { a = new CcAutoLock(lock); }; - static void Stop (CcAutoLock*& a) { delete a; a = 0; }; - CcAutoLock(CcOsLock& lock):m_lock(lock) { m_lock.lock(); } - ~CcAutoLock() { m_lock.unlock(); } -}; - -#endif /* __AUTOLOCK_HXX */ +/* + + Copyright (C) 1998 Danilo Almeida. All rights reserved. + + automatic stack-based locking object + + This file is part of FIFS (Framework for Implementing File Systems). + + This software is distributed with NO WARRANTY OF ANY KIND. No + author or distributor accepts any responsibility for the + consequences of using it, or for whether it serves any particular + purpose or works at all, unless he or she says so in writing. + Refer to the included modified Alladin Free Public License (the + "License") for full details. + + Every copy of this software must include a copy of the License, in + a plain ASCII text file named COPYING. The License grants you the + right to copy, modify and redistribute this software, but only + under certain conditions described in the License. Among other + things, the License requires that the copyright notice and this + notice be preserved on all copies. + +*/ + +#ifndef __AUTOLOCK_HXX__ +#define __AUTOLOCK_HXX__ + +#include + +class CcOsLock { + CRITICAL_SECTION cs; + bool valid; +public: + CcOsLock() {InitializeCriticalSection(&cs); valid = true; } + ~CcOsLock() {DeleteCriticalSection(&cs); valid = false;} + void lock() {if (valid) EnterCriticalSection(&cs);} + void unlock() {if (valid) LeaveCriticalSection(&cs);} +#if 0 + bool trylock() {return valid ? (TryEnterCriticalSection(&cs) ? true : false) + : false; } +#endif +}; + +class CcAutoLock { + CcOsLock& m_lock; +public: + static void Start(CcAutoLock*& a, CcOsLock& lock) { a = new CcAutoLock(lock); }; + static void Stop (CcAutoLock*& a) { delete a; a = 0; }; + CcAutoLock(CcOsLock& lock):m_lock(lock) { m_lock.lock(); } + ~CcAutoLock() { m_lock.unlock(); } +}; + +#endif /* __AUTOLOCK_HXX */ diff --git a/src/ccapi/common/win/OldCC/ccutil.cxx b/src/ccapi/common/win/OldCC/ccutil.cxx index e5e5baef5..729104de7 100644 --- a/src/ccapi/common/win/OldCC/ccutil.cxx +++ b/src/ccapi/common/win/OldCC/ccutil.cxx @@ -1,187 +1,187 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#include -#include "init.hxx" -#include "secure.hxx" - -extern "C" { -#include "cci_debugging.h" - } - - -CcOsLock Init::s_lock; -DWORD Init::s_refcount = 0; -DWORD Init::s_error = ERROR_INVALID_HANDLE; -bool Init::s_init = false; -Init::InitInfo Init::s_info = { 0 }; -HINSTANCE Init::s_hRpcDll = 0; - -#define INIT "INIT: " - -static -void -ShowInfo( - Init::InitInfo& info - ); - -DWORD -Init::Info( - InitInfo& info - ) -{ - // This funciton will not do automatic initialization. - CcAutoLock AL(s_lock); - if (!s_init) { - memset(&info, 0, sizeof(info)); - return s_error ? s_error : ERROR_INVALID_HANDLE; - } else { - info = s_info; - return 0; - } -} - -DWORD -Init::Initialize() { - CcAutoLock AL(s_lock); - cci_debug_printf("%s s_init:%d", __FUNCTION__, s_init); - if (s_init) { - s_refcount++; - return 0; - } - SecureClient s; - DWORD status = 0; - OSVERSIONINFO osvi; - BOOL isSupportedVersion = FALSE; - memset(&s_info, 0, sizeof(s_info)); - memset(&osvi, 0, sizeof(osvi)); - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - - status = !GetVersionEx(&osvi); // Returns a boolean. Invert to 0 is OK. - - if (!status) { - switch(osvi.dwPlatformId) { - case VER_PLATFORM_WIN32_WINDOWS: - s_info.isNT = FALSE; - isSupportedVersion = TRUE; - break; - case VER_PLATFORM_WIN32_NT: - s_info.isNT = TRUE; - isSupportedVersion = TRUE; - break; - case VER_PLATFORM_WIN32s: - default: - s_info.isNT = FALSE; - break; - } - - if (!isSupportedVersion) { - cci_debug_printf("%s Trying to run on an unsupported version of Windows", __FUNCTION__); - status = 1; - } - } - - if (!status) {status = !s_info.isNT;} - - if (!status) {status = !(s_hRpcDll = LoadLibrary(TEXT("rpcrt4.dll")));} - - if (!status) { - s_info.fRpcBindingSetAuthInfoEx = (FP_RpcBindingSetAuthInfoEx) - GetProcAddress(s_hRpcDll, TEXT(FN_RpcBindingSetAuthInfoEx)); - if (!s_info.fRpcBindingSetAuthInfoEx) { - cci_debug_printf(" Running on NT but could not find RpcBindinSetAuthInfoEx"); - status = 1; - } - } - - if (!status) { - s_info.fRpcServerRegisterIfEx = (FP_RpcServerRegisterIfEx) - GetProcAddress(s_hRpcDll, TEXT(FN_RpcServerRegisterIfEx)); - if (!s_info.fRpcServerRegisterIfEx) { - cci_debug_printf(" Running on NT but could not find RpcServerRegisterIfEx"); - status = 1; - } - } - - if (!status) { - status = SecureClient::Attach(); - if (status) { - cci_debug_printf(" SecureClient::Attach() failed (%u)", status); - } - } - - if (status) { - memset(&s_info, 0, sizeof(s_info)); - if (s_hRpcDll) { - FreeLibrary(s_hRpcDll); - s_hRpcDll = 0; - } - cci_debug_printf(" Init::Attach() failed (%u)", status); - } else { - s_refcount++; - s_init = true; - ShowInfo(s_info); - } - s_error = status; - return status; -} - -DWORD -Init::Cleanup( - ) -{ - CcAutoLock AL(s_lock); - s_refcount--; - if (s_refcount) return 0; - if (!s_init) return 0; - DWORD error = 0; - if (s_hRpcDll) { - FreeLibrary(s_hRpcDll); - s_hRpcDll = 0; - } - error = SecureClient::Detach(); - memset(&s_info, 0, sizeof(s_info)); - s_init = false; - s_error = 0; - if (error) { - cci_debug_printf(" Init::Detach() had an error (%u)", error); - } - return error; -} - -static -void -ShowInfo( - Init::InitInfo& info - ) -{ - if (info.isNT) { - cci_debug_printf(" Running on Windows NT using secure mode"); - } else { - cci_debug_printf(" Running insecurely on non-NT Windows"); - } - return; -} +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#include +#include "init.hxx" +#include "secure.hxx" + +extern "C" { +#include "cci_debugging.h" + } + + +CcOsLock Init::s_lock; +DWORD Init::s_refcount = 0; +DWORD Init::s_error = ERROR_INVALID_HANDLE; +bool Init::s_init = false; +Init::InitInfo Init::s_info = { 0 }; +HINSTANCE Init::s_hRpcDll = 0; + +#define INIT "INIT: " + +static +void +ShowInfo( + Init::InitInfo& info + ); + +DWORD +Init::Info( + InitInfo& info + ) +{ + // This funciton will not do automatic initialization. + CcAutoLock AL(s_lock); + if (!s_init) { + memset(&info, 0, sizeof(info)); + return s_error ? s_error : ERROR_INVALID_HANDLE; + } else { + info = s_info; + return 0; + } +} + +DWORD +Init::Initialize() { + CcAutoLock AL(s_lock); + cci_debug_printf("%s s_init:%d", __FUNCTION__, s_init); + if (s_init) { + s_refcount++; + return 0; + } + SecureClient s; + DWORD status = 0; + OSVERSIONINFO osvi; + BOOL isSupportedVersion = FALSE; + memset(&s_info, 0, sizeof(s_info)); + memset(&osvi, 0, sizeof(osvi)); + osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + + status = !GetVersionEx(&osvi); // Returns a boolean. Invert to 0 is OK. + + if (!status) { + switch(osvi.dwPlatformId) { + case VER_PLATFORM_WIN32_WINDOWS: + s_info.isNT = FALSE; + isSupportedVersion = TRUE; + break; + case VER_PLATFORM_WIN32_NT: + s_info.isNT = TRUE; + isSupportedVersion = TRUE; + break; + case VER_PLATFORM_WIN32s: + default: + s_info.isNT = FALSE; + break; + } + + if (!isSupportedVersion) { + cci_debug_printf("%s Trying to run on an unsupported version of Windows", __FUNCTION__); + status = 1; + } + } + + if (!status) {status = !s_info.isNT;} + + if (!status) {status = !(s_hRpcDll = LoadLibrary(TEXT("rpcrt4.dll")));} + + if (!status) { + s_info.fRpcBindingSetAuthInfoEx = (FP_RpcBindingSetAuthInfoEx) + GetProcAddress(s_hRpcDll, TEXT(FN_RpcBindingSetAuthInfoEx)); + if (!s_info.fRpcBindingSetAuthInfoEx) { + cci_debug_printf(" Running on NT but could not find RpcBindinSetAuthInfoEx"); + status = 1; + } + } + + if (!status) { + s_info.fRpcServerRegisterIfEx = (FP_RpcServerRegisterIfEx) + GetProcAddress(s_hRpcDll, TEXT(FN_RpcServerRegisterIfEx)); + if (!s_info.fRpcServerRegisterIfEx) { + cci_debug_printf(" Running on NT but could not find RpcServerRegisterIfEx"); + status = 1; + } + } + + if (!status) { + status = SecureClient::Attach(); + if (status) { + cci_debug_printf(" SecureClient::Attach() failed (%u)", status); + } + } + + if (status) { + memset(&s_info, 0, sizeof(s_info)); + if (s_hRpcDll) { + FreeLibrary(s_hRpcDll); + s_hRpcDll = 0; + } + cci_debug_printf(" Init::Attach() failed (%u)", status); + } else { + s_refcount++; + s_init = true; + ShowInfo(s_info); + } + s_error = status; + return status; +} + +DWORD +Init::Cleanup( + ) +{ + CcAutoLock AL(s_lock); + s_refcount--; + if (s_refcount) return 0; + if (!s_init) return 0; + DWORD error = 0; + if (s_hRpcDll) { + FreeLibrary(s_hRpcDll); + s_hRpcDll = 0; + } + error = SecureClient::Detach(); + memset(&s_info, 0, sizeof(s_info)); + s_init = false; + s_error = 0; + if (error) { + cci_debug_printf(" Init::Detach() had an error (%u)", error); + } + return error; +} + +static +void +ShowInfo( + Init::InitInfo& info + ) +{ + if (info.isNT) { + cci_debug_printf(" Running on Windows NT using secure mode"); + } else { + cci_debug_printf(" Running insecurely on non-NT Windows"); + } + return; +} diff --git a/src/ccapi/common/win/OldCC/ccutil.def b/src/ccapi/common/win/OldCC/ccutil.def index a187c805d..57113f094 100644 --- a/src/ccapi/common/win/OldCC/ccutil.def +++ b/src/ccapi/common/win/OldCC/ccutil.def @@ -1,5 +1,5 @@ -;LIBRARY COMERR32 -HEAPSIZE 8192 - -EXPORTS +;LIBRARY COMERR32 +HEAPSIZE 8192 + +EXPORTS \ No newline at end of file diff --git a/src/ccapi/common/win/OldCC/init.cxx b/src/ccapi/common/win/OldCC/init.cxx index af93722fe..feb7ad3ad 100644 --- a/src/ccapi/common/win/OldCC/init.cxx +++ b/src/ccapi/common/win/OldCC/init.cxx @@ -1,187 +1,187 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#include -#include "init.hxx" -#include "secure.hxx" - -extern "C" { -#include "cci_debugging.h" - } - - -CcOsLock Init::s_lock; -DWORD Init::s_refcount = 0; -DWORD Init::s_error = ERROR_INVALID_HANDLE; -bool Init::s_init = false; -Init::InitInfo Init::s_info = { 0 }; -HINSTANCE Init::s_hRpcDll = 0; - -#define INIT "INIT: " - -static -void -ShowInfo( - Init::InitInfo& info - ); - -DWORD -Init::Info( - InitInfo& info - ) -{ - // This funciton will not do automatic initialization. - CcAutoLock AL(s_lock); - if (!s_init) { - memset(&info, 0, sizeof(info)); - return s_error ? s_error : ERROR_INVALID_HANDLE; - } else { - info = s_info; - return 0; - } -} - -DWORD -Init::Initialize() { - CcAutoLock AL(s_lock); -// cci_debug_printf("%s s_init:%d", __FUNCTION__, s_init); - if (s_init) { - s_refcount++; - return 0; - } - SecureClient s; - DWORD status = 0; - OSVERSIONINFO osvi; - BOOL isSupportedVersion = FALSE; - memset(&s_info, 0, sizeof(s_info)); - memset(&osvi, 0, sizeof(osvi)); - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - - status = !GetVersionEx(&osvi); // Returns a boolean. Invert to 0 is OK. - - if (!status) { - switch(osvi.dwPlatformId) { - case VER_PLATFORM_WIN32_WINDOWS: - s_info.isNT = FALSE; - isSupportedVersion = TRUE; - break; - case VER_PLATFORM_WIN32_NT: - s_info.isNT = TRUE; - isSupportedVersion = TRUE; - break; - case VER_PLATFORM_WIN32s: - default: - s_info.isNT = FALSE; - break; - } - - if (!isSupportedVersion) { - cci_debug_printf("%s Trying to run on an unsupported version of Windows", __FUNCTION__); - status = 1; - } - } - - if (!status) {status = !s_info.isNT;} - - if (!status) {status = !(s_hRpcDll = LoadLibrary(TEXT("rpcrt4.dll")));} - - if (!status) { - s_info.fRpcBindingSetAuthInfoEx = (FP_RpcBindingSetAuthInfoEx) - GetProcAddress(s_hRpcDll, TEXT(FN_RpcBindingSetAuthInfoEx)); - if (!s_info.fRpcBindingSetAuthInfoEx) { - cci_debug_printf(" Running on NT but could not find RpcBindinSetAuthInfoEx"); - status = 1; - } - } - - if (!status) { - s_info.fRpcServerRegisterIfEx = (FP_RpcServerRegisterIfEx) - GetProcAddress(s_hRpcDll, TEXT(FN_RpcServerRegisterIfEx)); - if (!s_info.fRpcServerRegisterIfEx) { - cci_debug_printf(" Running on NT but could not find RpcServerRegisterIfEx"); - status = 1; - } - } - - if (!status) { - status = SecureClient::Attach(); - if (status) { - cci_debug_printf(" SecureClient::Attach() failed (%u)", status); - } - } - - if (status) { - memset(&s_info, 0, sizeof(s_info)); - if (s_hRpcDll) { - FreeLibrary(s_hRpcDll); - s_hRpcDll = 0; - } - cci_debug_printf(" Init::Attach() failed (%u)", status); - } else { - s_refcount++; - s_init = true; - ShowInfo(s_info); - } - s_error = status; - return status; -} - -DWORD -Init::Cleanup( - ) -{ - CcAutoLock AL(s_lock); - s_refcount--; - if (s_refcount) return 0; - if (!s_init) return 0; - DWORD error = 0; - if (s_hRpcDll) { - FreeLibrary(s_hRpcDll); - s_hRpcDll = 0; - } - error = SecureClient::Detach(); - memset(&s_info, 0, sizeof(s_info)); - s_init = false; - s_error = 0; - if (error) { - cci_debug_printf(" Init::Detach() had an error (%u)", error); - } - return error; -} - -static -void -ShowInfo( - Init::InitInfo& info - ) -{ - if (info.isNT) { - cci_debug_printf(" Running on Windows NT using secure mode"); - } else { - cci_debug_printf(" Running insecurely on non-NT Windows"); - } - return; -} +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#include +#include "init.hxx" +#include "secure.hxx" + +extern "C" { +#include "cci_debugging.h" + } + + +CcOsLock Init::s_lock; +DWORD Init::s_refcount = 0; +DWORD Init::s_error = ERROR_INVALID_HANDLE; +bool Init::s_init = false; +Init::InitInfo Init::s_info = { 0 }; +HINSTANCE Init::s_hRpcDll = 0; + +#define INIT "INIT: " + +static +void +ShowInfo( + Init::InitInfo& info + ); + +DWORD +Init::Info( + InitInfo& info + ) +{ + // This funciton will not do automatic initialization. + CcAutoLock AL(s_lock); + if (!s_init) { + memset(&info, 0, sizeof(info)); + return s_error ? s_error : ERROR_INVALID_HANDLE; + } else { + info = s_info; + return 0; + } +} + +DWORD +Init::Initialize() { + CcAutoLock AL(s_lock); +// cci_debug_printf("%s s_init:%d", __FUNCTION__, s_init); + if (s_init) { + s_refcount++; + return 0; + } + SecureClient s; + DWORD status = 0; + OSVERSIONINFO osvi; + BOOL isSupportedVersion = FALSE; + memset(&s_info, 0, sizeof(s_info)); + memset(&osvi, 0, sizeof(osvi)); + osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + + status = !GetVersionEx(&osvi); // Returns a boolean. Invert to 0 is OK. + + if (!status) { + switch(osvi.dwPlatformId) { + case VER_PLATFORM_WIN32_WINDOWS: + s_info.isNT = FALSE; + isSupportedVersion = TRUE; + break; + case VER_PLATFORM_WIN32_NT: + s_info.isNT = TRUE; + isSupportedVersion = TRUE; + break; + case VER_PLATFORM_WIN32s: + default: + s_info.isNT = FALSE; + break; + } + + if (!isSupportedVersion) { + cci_debug_printf("%s Trying to run on an unsupported version of Windows", __FUNCTION__); + status = 1; + } + } + + if (!status) {status = !s_info.isNT;} + + if (!status) {status = !(s_hRpcDll = LoadLibrary(TEXT("rpcrt4.dll")));} + + if (!status) { + s_info.fRpcBindingSetAuthInfoEx = (FP_RpcBindingSetAuthInfoEx) + GetProcAddress(s_hRpcDll, TEXT(FN_RpcBindingSetAuthInfoEx)); + if (!s_info.fRpcBindingSetAuthInfoEx) { + cci_debug_printf(" Running on NT but could not find RpcBindinSetAuthInfoEx"); + status = 1; + } + } + + if (!status) { + s_info.fRpcServerRegisterIfEx = (FP_RpcServerRegisterIfEx) + GetProcAddress(s_hRpcDll, TEXT(FN_RpcServerRegisterIfEx)); + if (!s_info.fRpcServerRegisterIfEx) { + cci_debug_printf(" Running on NT but could not find RpcServerRegisterIfEx"); + status = 1; + } + } + + if (!status) { + status = SecureClient::Attach(); + if (status) { + cci_debug_printf(" SecureClient::Attach() failed (%u)", status); + } + } + + if (status) { + memset(&s_info, 0, sizeof(s_info)); + if (s_hRpcDll) { + FreeLibrary(s_hRpcDll); + s_hRpcDll = 0; + } + cci_debug_printf(" Init::Attach() failed (%u)", status); + } else { + s_refcount++; + s_init = true; + ShowInfo(s_info); + } + s_error = status; + return status; +} + +DWORD +Init::Cleanup( + ) +{ + CcAutoLock AL(s_lock); + s_refcount--; + if (s_refcount) return 0; + if (!s_init) return 0; + DWORD error = 0; + if (s_hRpcDll) { + FreeLibrary(s_hRpcDll); + s_hRpcDll = 0; + } + error = SecureClient::Detach(); + memset(&s_info, 0, sizeof(s_info)); + s_init = false; + s_error = 0; + if (error) { + cci_debug_printf(" Init::Detach() had an error (%u)", error); + } + return error; +} + +static +void +ShowInfo( + Init::InitInfo& info + ) +{ + if (info.isNT) { + cci_debug_printf(" Running on Windows NT using secure mode"); + } else { + cci_debug_printf(" Running insecurely on non-NT Windows"); + } + return; +} diff --git a/src/ccapi/common/win/OldCC/init.hxx b/src/ccapi/common/win/OldCC/init.hxx index f50db776a..9bac7f8f9 100644 --- a/src/ccapi/common/win/OldCC/init.hxx +++ b/src/ccapi/common/win/OldCC/init.hxx @@ -1,102 +1,102 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#pragma once -#include "autolock.hxx" -#include - -typedef RPC_STATUS (RPC_ENTRY *FP_RpcBindingSetAuthInfoExA)( - IN RPC_BINDING_HANDLE Binding, - IN unsigned char __RPC_FAR * ServerPrincName, - IN unsigned long AuthnLevel, - IN unsigned long AuthnSvc, - IN RPC_AUTH_IDENTITY_HANDLE AuthIdentity, OPTIONAL - IN unsigned long AuthzSvc, - IN RPC_SECURITY_QOS *SecurityQos OPTIONAL - ); - -typedef RPC_STATUS (RPC_ENTRY *FP_RpcBindingSetAuthInfoExW)( - IN RPC_BINDING_HANDLE Binding, - IN unsigned short __RPC_FAR * ServerPrincName, - IN unsigned long AuthnLevel, - IN unsigned long AuthnSvc, - IN RPC_AUTH_IDENTITY_HANDLE AuthIdentity, OPTIONAL - IN unsigned long AuthzSvc, OPTIONAL - IN RPC_SECURITY_QOS *SecurityQOS - ); - -typedef RPC_STATUS (RPC_ENTRY *FP_RpcServerRegisterIfEx)( - IN RPC_IF_HANDLE IfSpec, - IN UUID __RPC_FAR * MgrTypeUuid, - IN RPC_MGR_EPV __RPC_FAR * MgrEpv, - IN unsigned int Flags, - IN unsigned int MaxCalls, - IN RPC_IF_CALLBACK_FN __RPC_FAR *IfCallback - ); - -#ifdef UNICODE -#define FP_RpcBindingSetAuthInfoEx FP_RpcBindingSetAuthInfoExW -#define FN_RpcBindingSetAuthInfoEx "RpcBindingSetAuthInfoExW" -#else -#define FP_RpcBindingSetAuthInfoEx FP_RpcBindingSetAuthInfoExA -#define FN_RpcBindingSetAuthInfoEx "RpcBindingSetAuthInfoExA" -#endif - -#define FN_RpcServerRegisterIfEx "RpcServerRegisterIfEx" - -class Init -{ -public: - struct InitInfo { - BOOL isNT; - FP_RpcBindingSetAuthInfoEx fRpcBindingSetAuthInfoEx; - FP_RpcServerRegisterIfEx fRpcServerRegisterIfEx; - }; - - static DWORD Initialize(); - static DWORD Cleanup(); - static DWORD Info(InitInfo& info); - - static bool Initialized() { return s_init; } - -private: - static CcOsLock s_lock; - static DWORD s_refcount; - static DWORD s_error; - static bool s_init; - static InitInfo s_info; - static HINSTANCE s_hRpcDll; -}; - -#define INIT_INIT_EX(trap, error) \ -do \ -{ \ - if (!Init::Initialized()) \ - { \ - DWORD rc = Init::Initialize(); \ - if (rc) return (trap) ? (error) : rc; \ - } \ -} while(0) +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#pragma once +#include "autolock.hxx" +#include + +typedef RPC_STATUS (RPC_ENTRY *FP_RpcBindingSetAuthInfoExA)( + IN RPC_BINDING_HANDLE Binding, + IN unsigned char __RPC_FAR * ServerPrincName, + IN unsigned long AuthnLevel, + IN unsigned long AuthnSvc, + IN RPC_AUTH_IDENTITY_HANDLE AuthIdentity, OPTIONAL + IN unsigned long AuthzSvc, + IN RPC_SECURITY_QOS *SecurityQos OPTIONAL + ); + +typedef RPC_STATUS (RPC_ENTRY *FP_RpcBindingSetAuthInfoExW)( + IN RPC_BINDING_HANDLE Binding, + IN unsigned short __RPC_FAR * ServerPrincName, + IN unsigned long AuthnLevel, + IN unsigned long AuthnSvc, + IN RPC_AUTH_IDENTITY_HANDLE AuthIdentity, OPTIONAL + IN unsigned long AuthzSvc, OPTIONAL + IN RPC_SECURITY_QOS *SecurityQOS + ); + +typedef RPC_STATUS (RPC_ENTRY *FP_RpcServerRegisterIfEx)( + IN RPC_IF_HANDLE IfSpec, + IN UUID __RPC_FAR * MgrTypeUuid, + IN RPC_MGR_EPV __RPC_FAR * MgrEpv, + IN unsigned int Flags, + IN unsigned int MaxCalls, + IN RPC_IF_CALLBACK_FN __RPC_FAR *IfCallback + ); + +#ifdef UNICODE +#define FP_RpcBindingSetAuthInfoEx FP_RpcBindingSetAuthInfoExW +#define FN_RpcBindingSetAuthInfoEx "RpcBindingSetAuthInfoExW" +#else +#define FP_RpcBindingSetAuthInfoEx FP_RpcBindingSetAuthInfoExA +#define FN_RpcBindingSetAuthInfoEx "RpcBindingSetAuthInfoExA" +#endif + +#define FN_RpcServerRegisterIfEx "RpcServerRegisterIfEx" + +class Init +{ +public: + struct InitInfo { + BOOL isNT; + FP_RpcBindingSetAuthInfoEx fRpcBindingSetAuthInfoEx; + FP_RpcServerRegisterIfEx fRpcServerRegisterIfEx; + }; + + static DWORD Initialize(); + static DWORD Cleanup(); + static DWORD Info(InitInfo& info); + + static bool Initialized() { return s_init; } + +private: + static CcOsLock s_lock; + static DWORD s_refcount; + static DWORD s_error; + static bool s_init; + static InitInfo s_info; + static HINSTANCE s_hRpcDll; +}; + +#define INIT_INIT_EX(trap, error) \ +do \ +{ \ + if (!Init::Initialized()) \ + { \ + DWORD rc = Init::Initialize(); \ + if (rc) return (trap) ? (error) : rc; \ + } \ +} while(0) diff --git a/src/ccapi/common/win/OldCC/opts.cxx b/src/ccapi/common/win/OldCC/opts.cxx index c6a40d64d..bd5f503ea 100644 --- a/src/ccapi/common/win/OldCC/opts.cxx +++ b/src/ccapi/common/win/OldCC/opts.cxx @@ -1,188 +1,188 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#include -#include -#include -#include - -#if 0 -const struct Opts* -GetOpts( - ) -{ - bool done = false; - struct Opts* o; - if (!(o = new Opts)) - goto cleanup; - if (!(o->pszString = new char[lstrlenA(opts.pszString) + 1])) - goto cleanup; - if (!(o->pszEndpoint = new char[lstrlenA(opts.pszEndpoint) + 1])) - goto cleanup; - strcpy(o->pszString, opts.pszString); - strcpy(o->pszEndpoint, opts.pszEndpoint); - done = true; - cleanup: - if (!done) { - FreeOpts(o); - o = 0; - } - return o; -} - -void -FreeOpts( - struct Opts* o - ) -{ - if (o) { - if (o->pszString) - delete [] o->pszString; - if (o->pszEndpoint) - delete [] o->pszEndpoint; - delete o; - } -} -#endif - -bool -ParseOpts::IsValidOpt( - char ch - ) -{ - return (m_ValidOpts[ch % 256] != 0); -} - -void -ParseOpts::PrintOpt( - char ch, - char* text - ) -{ - if (IsValidOpt(ch)) - fprintf(stderr, " -%c %s\n", ch, text); -} - -void -ParseOpts::UsageOpts( - char * program, - int code - ) -{ - fprintf(stderr, "Usage: %s [options]\n", program); - PrintOpt('k', "stop server"); -#ifdef CCAPI_TEST_OPTIONS - PrintOpt('s', "string"); - PrintOpt('e', "endpoint"); - PrintOpt('m', "maxcalls"); - PrintOpt('n', "mincalls"); - PrintOpt('f', "flag_wait_op"); - PrintOpt('u', "unprotected"); - PrintOpt('b', "use security callback"); -#endif - PrintOpt('c', "output debug info to console"); - exit(code); -} - -void -ParseOpts::SetValidOpts( - char* valid_opts - ) -{ - memset(m_ValidOpts, 0, sizeof(m_ValidOpts)); - char *p = valid_opts; - for (p = valid_opts; *p; p++) { - m_ValidOpts[*p % sizeof(m_ValidOpts)] = 1; - } -} - -void -ParseOpts::Parse( - Opts& opts, - int argc, - char **argv - ) -{ - int i; - for (i = 1; i < argc; i++) { - if ((*argv[i] == '-') || (*argv[i] == '/')) { - char ch = tolower(*(argv[i]+1)); - if (!IsValidOpt(ch)) - UsageOpts(argv[0]); - switch (ch) { - case 'k': - opts.bShutdown = TRUE; - break; -#ifdef CCAPI_TEST_OPTIONS - case 's': - opts.pszString = argv[++i]; - break; - case 'e': - opts.pszEndpoint = argv[++i]; - break; - case 'm': - opts.cMaxCalls = (unsigned int) atoi(argv[++i]); - break; - case 'n': - opts.cMinCalls = (unsigned int) atoi(argv[++i]); - break; - case 'f': - opts.fDontWait = (unsigned int) atoi(argv[++i]); - break; - case 'u': - opts.bDontProtect = TRUE; - break; - case 'b': - opts.bSecCallback = TRUE; - break; -#endif - case 'c': - opts.bConsole = TRUE; - break; - case 'h': - case '?': - default: - UsageOpts(argv[0]); - } - } - else - UsageOpts(argv[0]); - } - -} - -ParseOpts::ParseOpts(char* valid_opts) -{ - SetValidOpts(valid_opts); -} - -ParseOpts::ParseOpts() -{ -} - -ParseOpts::~ParseOpts() -{ -} +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#include +#include +#include +#include + +#if 0 +const struct Opts* +GetOpts( + ) +{ + bool done = false; + struct Opts* o; + if (!(o = new Opts)) + goto cleanup; + if (!(o->pszString = new char[lstrlenA(opts.pszString) + 1])) + goto cleanup; + if (!(o->pszEndpoint = new char[lstrlenA(opts.pszEndpoint) + 1])) + goto cleanup; + strcpy(o->pszString, opts.pszString); + strcpy(o->pszEndpoint, opts.pszEndpoint); + done = true; + cleanup: + if (!done) { + FreeOpts(o); + o = 0; + } + return o; +} + +void +FreeOpts( + struct Opts* o + ) +{ + if (o) { + if (o->pszString) + delete [] o->pszString; + if (o->pszEndpoint) + delete [] o->pszEndpoint; + delete o; + } +} +#endif + +bool +ParseOpts::IsValidOpt( + char ch + ) +{ + return (m_ValidOpts[ch % 256] != 0); +} + +void +ParseOpts::PrintOpt( + char ch, + char* text + ) +{ + if (IsValidOpt(ch)) + fprintf(stderr, " -%c %s\n", ch, text); +} + +void +ParseOpts::UsageOpts( + char * program, + int code + ) +{ + fprintf(stderr, "Usage: %s [options]\n", program); + PrintOpt('k', "stop server"); +#ifdef CCAPI_TEST_OPTIONS + PrintOpt('s', "string"); + PrintOpt('e', "endpoint"); + PrintOpt('m', "maxcalls"); + PrintOpt('n', "mincalls"); + PrintOpt('f', "flag_wait_op"); + PrintOpt('u', "unprotected"); + PrintOpt('b', "use security callback"); +#endif + PrintOpt('c', "output debug info to console"); + exit(code); +} + +void +ParseOpts::SetValidOpts( + char* valid_opts + ) +{ + memset(m_ValidOpts, 0, sizeof(m_ValidOpts)); + char *p = valid_opts; + for (p = valid_opts; *p; p++) { + m_ValidOpts[*p % sizeof(m_ValidOpts)] = 1; + } +} + +void +ParseOpts::Parse( + Opts& opts, + int argc, + char **argv + ) +{ + int i; + for (i = 1; i < argc; i++) { + if ((*argv[i] == '-') || (*argv[i] == '/')) { + char ch = tolower(*(argv[i]+1)); + if (!IsValidOpt(ch)) + UsageOpts(argv[0]); + switch (ch) { + case 'k': + opts.bShutdown = TRUE; + break; +#ifdef CCAPI_TEST_OPTIONS + case 's': + opts.pszString = argv[++i]; + break; + case 'e': + opts.pszEndpoint = argv[++i]; + break; + case 'm': + opts.cMaxCalls = (unsigned int) atoi(argv[++i]); + break; + case 'n': + opts.cMinCalls = (unsigned int) atoi(argv[++i]); + break; + case 'f': + opts.fDontWait = (unsigned int) atoi(argv[++i]); + break; + case 'u': + opts.bDontProtect = TRUE; + break; + case 'b': + opts.bSecCallback = TRUE; + break; +#endif + case 'c': + opts.bConsole = TRUE; + break; + case 'h': + case '?': + default: + UsageOpts(argv[0]); + } + } + else + UsageOpts(argv[0]); + } + +} + +ParseOpts::ParseOpts(char* valid_opts) +{ + SetValidOpts(valid_opts); +} + +ParseOpts::ParseOpts() +{ +} + +ParseOpts::~ParseOpts() +{ +} diff --git a/src/ccapi/common/win/OldCC/opts.hxx b/src/ccapi/common/win/OldCC/opts.hxx index 1732ceb25..755ce4ae6 100644 --- a/src/ccapi/common/win/OldCC/opts.hxx +++ b/src/ccapi/common/win/OldCC/opts.hxx @@ -1,56 +1,56 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#pragma once - -class ParseOpts -{ -public: - struct Opts { - char* pszString; - char* pszEndpoint; - unsigned int cMinCalls; - unsigned int cMaxCalls; - unsigned int fDontWait; - bool bDontProtect; - bool bShutdown; - bool bSecCallback; - bool bConsole; - }; - - ParseOpts(char* valid_opts); - ParseOpts(); - ~ParseOpts(); - void SetValidOpts(char* valid_opts); - void Parse(Opts& opts, int argc, char **argv); - -private: - bool IsValidOpt(char ch); - void PrintOpt(char ch, char* text); - void UsageOpts(char* program, int code = 0); - - char m_ValidOpts[256]; -}; +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#pragma once + +class ParseOpts +{ +public: + struct Opts { + char* pszString; + char* pszEndpoint; + unsigned int cMinCalls; + unsigned int cMaxCalls; + unsigned int fDontWait; + bool bDontProtect; + bool bShutdown; + bool bSecCallback; + bool bConsole; + }; + + ParseOpts(char* valid_opts); + ParseOpts(); + ~ParseOpts(); + void SetValidOpts(char* valid_opts); + void Parse(Opts& opts, int argc, char **argv); + +private: + bool IsValidOpt(char ch); + void PrintOpt(char ch, char* text); + void UsageOpts(char* program, int code = 0); + + char m_ValidOpts[256]; +}; diff --git a/src/ccapi/common/win/OldCC/secure.cxx b/src/ccapi/common/win/OldCC/secure.cxx index a32235fd6..99ba08a25 100644 --- a/src/ccapi/common/win/OldCC/secure.cxx +++ b/src/ccapi/common/win/OldCC/secure.cxx @@ -1,161 +1,161 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#include -#include "secure.hxx" - -extern "C" { -#include "cci_debugging.h" - } - -CcOsLock SecureClient::s_lock; -DWORD SecureClient::s_refcount = 0; -DWORD SecureClient::s_error = 0; -HANDLE SecureClient::s_hToken = 0; - -#include "util.h" - -#define SC "SecureClient::" - -DWORD -SecureClient::Attach( - ) -{ - CcAutoLock AL(s_lock); - if (s_hToken) { - s_refcount++; - return 0; - } - if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, - &s_hToken)) { - s_refcount++; - s_error = 0; - } else { - s_hToken = 0; - s_error = GetLastError(); - } - return s_error; -} - -DWORD -SecureClient::Detach( - ) -{ - CcAutoLock AL(s_lock); - s_refcount--; - if (s_refcount) return 0; - if (!s_hToken) return 0; - DWORD error = 0; - if (!CloseHandle(s_hToken)) - error = GetLastError(); - s_hToken = 0; - s_error = 0; - return error; -} - -DWORD SecureClient::Token(HANDLE& hToken) { - // This function will not do automatic initialization. - CcAutoLock AL(s_lock); - hToken = 0; - if (!s_hToken) { - cci_debug_printf("%s no process token initialized (%u)", __FUNCTION__, s_error); - return s_error ? s_error : ERROR_INVALID_HANDLE; - } - else { - DWORD status = 0; - if (!DuplicateHandle(GetCurrentProcess(), s_hToken, - GetCurrentProcess(), &hToken, 0, FALSE, - DUPLICATE_SAME_ACCESS)) { - status = GetLastError(); - cci_debug_printf(" Could not duplicate handle (%u)", status); - } - return status; - } - } - -void -SecureClient::Start(SecureClient*& s) { - s = new SecureClient; -} - -void -SecureClient::Stop(SecureClient*& s) { - delete s; - s = 0; -} - -/////////////////////////////////////////////////////////////////////////////// - -/* This constructor turns off impersonation. - * It is OK for OpenThreadToken to return an error -- that just means impersonation - * is off. - */ -SecureClient::SecureClient(): - m_Error(0), - m_hToken(0), - m_NeedRestore(false) { - - HANDLE hThread = GetCurrentThread(); - HANDLE hThDuplicate; - - int status = DuplicateHandle( GetCurrentProcess(), - hThread, - GetCurrentProcess(), - &hThDuplicate, - TOKEN_ALL_ACCESS, - FALSE, - 0); - if (!status) return; - - if (!OpenThreadToken(hThDuplicate, TOKEN_ALL_ACCESS, FALSE, &m_hToken)) { - m_Error = GetLastError(); - return; - } - if (SetThreadToken(&hThDuplicate, NULL)) { - m_NeedRestore = true; - } else { - m_Error = GetLastError(); - } - CloseHandle(hThDuplicate); - } - -SecureClient::~SecureClient() { - if (m_NeedRestore) { - HANDLE hThread = GetCurrentThread(); - if (!SetThreadToken(&hThread, m_hToken)) { - m_Error = cci_check_error(GetLastError()); - } - } - if (m_hToken) { - if (!CloseHandle(m_hToken)) { - m_Error = cci_check_error(GetLastError()); - } - } - } - -DWORD SecureClient::Error() { - return m_Error; +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#include +#include "secure.hxx" + +extern "C" { +#include "cci_debugging.h" + } + +CcOsLock SecureClient::s_lock; +DWORD SecureClient::s_refcount = 0; +DWORD SecureClient::s_error = 0; +HANDLE SecureClient::s_hToken = 0; + +#include "util.h" + +#define SC "SecureClient::" + +DWORD +SecureClient::Attach( + ) +{ + CcAutoLock AL(s_lock); + if (s_hToken) { + s_refcount++; + return 0; + } + if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, + &s_hToken)) { + s_refcount++; + s_error = 0; + } else { + s_hToken = 0; + s_error = GetLastError(); + } + return s_error; +} + +DWORD +SecureClient::Detach( + ) +{ + CcAutoLock AL(s_lock); + s_refcount--; + if (s_refcount) return 0; + if (!s_hToken) return 0; + DWORD error = 0; + if (!CloseHandle(s_hToken)) + error = GetLastError(); + s_hToken = 0; + s_error = 0; + return error; +} + +DWORD SecureClient::Token(HANDLE& hToken) { + // This function will not do automatic initialization. + CcAutoLock AL(s_lock); + hToken = 0; + if (!s_hToken) { + cci_debug_printf("%s no process token initialized (%u)", __FUNCTION__, s_error); + return s_error ? s_error : ERROR_INVALID_HANDLE; + } + else { + DWORD status = 0; + if (!DuplicateHandle(GetCurrentProcess(), s_hToken, + GetCurrentProcess(), &hToken, 0, FALSE, + DUPLICATE_SAME_ACCESS)) { + status = GetLastError(); + cci_debug_printf(" Could not duplicate handle (%u)", status); + } + return status; + } + } + +void +SecureClient::Start(SecureClient*& s) { + s = new SecureClient; +} + +void +SecureClient::Stop(SecureClient*& s) { + delete s; + s = 0; +} + +/////////////////////////////////////////////////////////////////////////////// + +/* This constructor turns off impersonation. + * It is OK for OpenThreadToken to return an error -- that just means impersonation + * is off. + */ +SecureClient::SecureClient(): + m_Error(0), + m_hToken(0), + m_NeedRestore(false) { + + HANDLE hThread = GetCurrentThread(); + HANDLE hThDuplicate; + + int status = DuplicateHandle( GetCurrentProcess(), + hThread, + GetCurrentProcess(), + &hThDuplicate, + TOKEN_ALL_ACCESS, + FALSE, + 0); + if (!status) return; + + if (!OpenThreadToken(hThDuplicate, TOKEN_ALL_ACCESS, FALSE, &m_hToken)) { + m_Error = GetLastError(); + return; + } + if (SetThreadToken(&hThDuplicate, NULL)) { + m_NeedRestore = true; + } else { + m_Error = GetLastError(); + } + CloseHandle(hThDuplicate); + } + +SecureClient::~SecureClient() { + if (m_NeedRestore) { + HANDLE hThread = GetCurrentThread(); + if (!SetThreadToken(&hThread, m_hToken)) { + m_Error = cci_check_error(GetLastError()); + } + } + if (m_hToken) { + if (!CloseHandle(m_hToken)) { + m_Error = cci_check_error(GetLastError()); + } + } + } + +DWORD SecureClient::Error() { + return m_Error; } \ No newline at end of file diff --git a/src/ccapi/common/win/OldCC/secure.hxx b/src/ccapi/common/win/OldCC/secure.hxx index 009e36c74..3714c6f84 100644 --- a/src/ccapi/common/win/OldCC/secure.hxx +++ b/src/ccapi/common/win/OldCC/secure.hxx @@ -1,60 +1,60 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#pragma once - -#include -#include "autolock.hxx" - -class SecureClient -{ -public: - static DWORD Attach(); - static DWORD Detach(); - static DWORD Token(HANDLE& hToken); - static void Start(SecureClient*& s); - static void Stop(SecureClient*& s); - -#if 0 - static DWORD CheckImpersonation(); - static bool IsImp(); - static DWORD DuplicateImpAsPrimary(HANDLE& hPrimary); -#endif - - SecureClient(); - ~SecureClient(); - DWORD Error(); - -private: - static CcOsLock s_lock; - static DWORD s_refcount; - static DWORD s_error; - static HANDLE s_hToken; - - DWORD m_Error; - HANDLE m_hToken; - bool m_NeedRestore; -}; +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#pragma once + +#include +#include "autolock.hxx" + +class SecureClient +{ +public: + static DWORD Attach(); + static DWORD Detach(); + static DWORD Token(HANDLE& hToken); + static void Start(SecureClient*& s); + static void Stop(SecureClient*& s); + +#if 0 + static DWORD CheckImpersonation(); + static bool IsImp(); + static DWORD DuplicateImpAsPrimary(HANDLE& hPrimary); +#endif + + SecureClient(); + ~SecureClient(); + DWORD Error(); + +private: + static CcOsLock s_lock; + static DWORD s_refcount; + static DWORD s_error; + static HANDLE s_hToken; + + DWORD m_Error; + HANDLE m_hToken; + bool m_NeedRestore; +}; diff --git a/src/ccapi/common/win/OldCC/util.cxx b/src/ccapi/common/win/OldCC/util.cxx index 62b204b92..8694c373c 100644 --- a/src/ccapi/common/win/OldCC/util.cxx +++ b/src/ccapi/common/win/OldCC/util.cxx @@ -1,519 +1,519 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#include -#include // for _snprintf - -#include "util.h" -#include "secure.hxx" - -extern "C" { -#include "cci_debugging.h" -#include "ccutils.h" - } - - - -void* malloc_alloc_p(size_t size) { - return malloc(size); - } - -void free_alloc_p(void *pptr) { - void **real_pptr = (void**)pptr; - if (*real_pptr) { - free(*real_pptr); - *real_pptr = 0; - } - } - -extern "C" DWORD alloc_textual_sid( - PSID pSid, // binary Sid - LPSTR *pTextualSid // buffer for Textual representaion of Sid - ) { - PSID_IDENTIFIER_AUTHORITY psia; - DWORD dwSubAuthorities; - DWORD dwSidRev = SID_REVISION; - DWORD dwCounter; - DWORD dwSidSize; - - *pTextualSid = 0; - - // - // test if Sid passed in is valid - // - if(!IsValidSid(pSid)) return ERROR_INVALID_PARAMETER; - - // obtain SidIdentifierAuthority - psia = GetSidIdentifierAuthority(pSid); - - // obtain sidsubauthority count - dwSubAuthorities =* GetSidSubAuthorityCount(pSid); - - // - // compute buffer length - // S-SID_REVISION- + identifierauthority- + subauthorities- + NULL - // - dwSidSize = (15 + 12 + (12 * dwSubAuthorities) + 1) * sizeof(TCHAR); - *pTextualSid = (LPSTR)malloc_alloc_p(dwSidSize); - if (!*pTextualSid) - return GetLastError(); - - LPSTR TextualSid = *pTextualSid; - - // - // prepare S-SID_REVISION- - // - wsprintf(TextualSid, TEXT("S-%lu-"), dwSidRev ); - - // - // prepare SidIdentifierAuthority - // - if ( (psia->Value[0] != 0) || (psia->Value[1] != 0) ) - { - wsprintf(TextualSid + lstrlen(TextualSid), - TEXT("0x%02hx%02hx%02hx%02hx%02hx%02hx"), - (USHORT)psia->Value[0], - (USHORT)psia->Value[1], - (USHORT)psia->Value[2], - (USHORT)psia->Value[3], - (USHORT)psia->Value[4], - (USHORT)psia->Value[5]); - } - else - { - wsprintf(TextualSid + lstrlen(TextualSid), TEXT("%lu"), - (ULONG)(psia->Value[5] ) + - (ULONG)(psia->Value[4] << 8) + - (ULONG)(psia->Value[3] << 16) + - (ULONG)(psia->Value[2] << 24) ); - } - - // - // loop through SidSubAuthorities - // - for (dwCounter=0 ; dwCounter < dwSubAuthorities ; dwCounter++) - { - wsprintf(TextualSid + lstrlen(TextualSid), TEXT("-%lu"), - *GetSidSubAuthority(pSid, dwCounter) ); - } - return 0; -} - -DWORD alloc_token_user(HANDLE hToken, PTOKEN_USER *pptu) { - DWORD status = 0; - DWORD size = 0; - *pptu = 0; - - GetTokenInformation(hToken, TokenUser, *pptu, 0, &size); - if (size == 0) status = GetLastError(); - - if (!status) { - if (!(*pptu = (PTOKEN_USER)malloc_alloc_p(size))) - status = GetLastError(); - } - - if (!status) { - if (!GetTokenInformation(hToken, TokenUser, *pptu, size, &size)) - status = GetLastError(); - } - - if (status && *pptu) { - free_alloc_p(pptu); - } - return status; - } - -DWORD -alloc_username( - PSID Sid, - LPSTR* pname, - LPSTR* pdomain = 0 - ) -{ - DWORD status = 0; - DWORD name_len = 0; - DWORD domain_len = 0; - SID_NAME_USE snu; - LPSTR name = 0; - LPSTR domain = 0; - - *pname = 0; - if (pdomain) *pdomain = 0; - - LookupAccountSidA(NULL, Sid, 0, &name_len, 0, &domain_len, &snu); - if ((name_len == 0) || (domain_len == 0)) status = GetLastError(); - - if (!status) { - if (!(name = (LPSTR)malloc_alloc_p(name_len))) status = GetLastError(); - } - - if (!status) { - if (!(domain = (LPSTR)malloc_alloc_p(domain_len))) status = GetLastError(); - } - - if (!status) { - if (!LookupAccountSidA(NULL, Sid, name, &name_len, domain, &domain_len, &snu)) status = GetLastError(); - } - - if (status) { - if (name) free_alloc_p(&name); - if (domain) free_alloc_p(&domain); - } - else { - if (pdomain) { - *pname = name; - *pdomain = domain; - } - else { - DWORD size = name_len + domain_len + 1; - *pname = (LPSTR)malloc_alloc_p(size); - if (!*pname) status = GetLastError(); - else _snprintf(*pname, size, "%s\\%s", name, domain); - } - } - return status; - } - -DWORD get_authentication_id(HANDLE hToken, LUID* pAuthId) { - TOKEN_STATISTICS ts; - DWORD len; - - if (!GetTokenInformation(hToken, TokenStatistics, &ts, sizeof(ts), &len)) - return GetLastError(); - *pAuthId = ts.AuthenticationId; - return 0; - } - -DWORD -alloc_name_9x( - LPSTR* pname, - LPSTR postfix - ) -{ - char prefix[] = "krbcc"; - DWORD len = (sizeof(prefix) - 1) + 1 + strlen(postfix) + 1; - - *pname = (LPSTR)malloc_alloc_p(len); - if (!*pname) return GetLastError(); - _snprintf(*pname, len, "%s.%s", prefix, postfix); - return 0; -} - -DWORD alloc_name_NT(LPSTR* pname, LPSTR postfix) { - DWORD status = 0; - HANDLE hToken = 0; - LUID auth_id; -#ifdef _DEBUG - PTOKEN_USER ptu = 0; - LPSTR name = 0; - LPSTR domain = 0; - LPSTR sid = 0; -#endif - char prefix[] = "krbcc"; - // Play it safe and say 3 characters are needed per 8 bits (byte). - // Note that 20 characters are needed for a 64-bit number in - // decimal (plus one for the string termination. - // and include room for sessionId. - char lid[3*sizeof(LUID)+1+5]; - DWORD sessionId; - DWORD len = 0; - - *pname = 0; - - status = SecureClient::Token(hToken); - - if (!status) { - status = get_authentication_id(hToken, &auth_id); - } - - if (!status) { - if (!ProcessIdToSessionId(GetCurrentProcessId(), &sessionId)) - sessionId = 0; - } - -#ifdef _DEBUG - if (!status) {status = alloc_token_user(hToken, &ptu);} - if (!status) {status = alloc_username(ptu->User.Sid, &name, &domain);} - if (!status) {status = alloc_textual_sid(ptu->User.Sid, &sid);} -#endif - - if (!status) { - _snprintf(lid, sizeof(lid), "%I64u.%u", auth_id, sessionId); - lid[sizeof(lid)-1] = 0; // be safe - - len = (sizeof(prefix) - 1) + 1 + strlen(lid) + 1 + strlen(postfix) + 1; - *pname = (LPSTR)malloc_alloc_p(len); - if (!*pname) status = GetLastError(); - } - - // - // We used to allocate a name of the form: - // "prefix.domain.name.sid.lid.postfix" (usually under 80 - // characters, depending on username). However, XP thought this - // was "invalid" (too long?) for some reason. - // - // Therefore, we now use "prefix.lid.postfix" - // and for Terminal server we use "prefix.lid.sessionId.postfix" - // - - if (!status) { - _snprintf(*pname, len, "%s.%s.%s", prefix, lid, postfix); - } - -#ifdef _DEBUG - if (sid) - free_alloc_p(&sid); - if (name) - free_alloc_p(&name); - if (domain) - free_alloc_p(&domain); - if (ptu) - free_alloc_p(&ptu); -#endif - if (hToken && hToken != INVALID_HANDLE_VALUE) - CloseHandle(hToken); - if (status && *pname) - free_alloc_p(pname); - return status; -} - -extern "C" DWORD alloc_name(LPSTR* pname, LPSTR postfix, BOOL isNT) { - return isNT ? alloc_name_NT(pname, postfix) : - alloc_name_9x(pname, postfix); - } - -extern "C" DWORD alloc_own_security_descriptor_NT(PSECURITY_DESCRIPTOR* ppsd) { - DWORD status = 0; - HANDLE hToken = 0; - PTOKEN_USER ptu = 0; - PSID pSid = 0; - PACL pAcl = 0; - DWORD size = 0; - SECURITY_DESCRIPTOR sd; - - *ppsd = 0; - - if (!status) {status = SecureClient::Token(hToken);} - - // Get SID: - if (!status) {status = alloc_token_user(hToken, &ptu);} - - if (!status) { - size = GetLengthSid(ptu->User.Sid); - pSid = (PSID) malloc_alloc_p(size); - if (!pSid) status = GetLastError(); - } - if (!status) { - if (!CopySid(size, pSid, ptu->User.Sid)) status = GetLastError(); - } - - if (!status) { - // Prepare ACL: - size = sizeof(ACL); - // Add an ACE: - size += sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) + GetLengthSid(pSid); - pAcl = (PACL) malloc_alloc_p(size); - if (!pAcl) status = GetLastError(); - } - - if (!status) { - if (!InitializeAcl(pAcl, size, ACL_REVISION)) status = GetLastError(); - } - - if (!status) { - if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_ALL, pSid)) status = GetLastError(); - } - - if (!status) { - // Prepare SD itself: - if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) status = GetLastError(); - } - - if (!status) { - if (!SetSecurityDescriptorDacl(&sd, TRUE, pAcl, FALSE)) status = GetLastError(); - } - - if (!status) { - if (!SetSecurityDescriptorOwner(&sd, pSid, FALSE)) status = GetLastError(); - } - - if (!status) { - if (!IsValidSecurityDescriptor(&sd)) status = ERROR_INVALID_PARAMETER; - } - - if (!status) { - // We now have a SD. Let's copy it. - { - // This should not succeed. Instead it should give us the size. - BOOL ok = MakeSelfRelativeSD(&sd, 0, &size); - } - if (size == 0) status = GetLastError(); - } - - if (!status) { - *ppsd = (PSECURITY_DESCRIPTOR) malloc_alloc_p(size); - if (!*ppsd) status = GetLastError(); - } - - if (!status) { - if (!MakeSelfRelativeSD(&sd, *ppsd, &size)) status = GetLastError(); - } - - if (ptu) free_alloc_p(&ptu); - if (pSid) free_alloc_p(&pSid); - if (pAcl) free_alloc_p(&pAcl); - if (hToken && hToken != INVALID_HANDLE_VALUE) CloseHandle(hToken); - if (status && *ppsd) free_alloc_p(ppsd); - return status; -} - -DWORD -alloc_module_file_name( - char* module, - char** pname - ) -{ - const DWORD max = 8192; - DWORD status = 0; - DWORD got = 0; - DWORD size = 512; // use low number to test... - HMODULE h = 0; - BOOL ok = FALSE; - char* name = 0; - - if (!pname) - return ERROR_INVALID_PARAMETER; - *pname = 0; - - h = GetModuleHandle(module); - - if (!h) return GetLastError(); - - // We assume size < max and size > 0 - while (!status && !ok) { - if (size > max) { - // XXX - Assert? - status = ERROR_INVALID_DATA; - continue; - } - if (name) free_alloc_p(&name); - name = (char*)malloc_alloc_p(size + 1); - if (!name) { - status = ERROR_NOT_ENOUGH_MEMORY; - continue; - } - name[size] = 0; - got = GetModuleFileName(h, name, size); - if (!got) { - status = GetLastError(); - // sanity check: - if (!status) { - // XXX - print nasty message...assert? - status = ERROR_INVALID_DATA; - } - continue; - } - // To know we're ok, we need to verify that what we got - // was bigger than GetModuleSize thought it got. - ok = got && (got < size) && !name[got]; - size *= 2; - } - if (status && name) - free_alloc_p(&name); - else - *pname = name; - return status; -} - -DWORD -alloc_module_dir_name( - char* module, - char** pname - ) -{ - DWORD status = alloc_module_file_name(module, pname); - if (!status) { - char* name = *pname; - char* p = name + strlen(name); - while ((p >= name) && (*p != '\\') && (*p != '/')) p--; - if (p < name) { - free_alloc_p(pname); - status = ERROR_INVALID_DATA; - } else { - *p = 0; - } - } - return status; -} - -DWORD -alloc_module_dir_name_with_file( - char* module, - char* file, - char** pname - ) -{ - DWORD status = alloc_module_dir_name(module, pname); - if (!status) { - char* name = *pname; - size_t name_size = strlen(name); - size_t size = name_size + 1 + strlen(file) + 1; - char* result = (char*)malloc_alloc_p(size); - if (!result) { - status = ERROR_NOT_ENOUGH_MEMORY; - free_alloc_p(pname); - } else { - strcpy(result, name); - result[name_size] = '\\'; - strcpy(result + name_size + 1, file); - free_alloc_p(pname); - *pname = result; - } - } - return status; -} - -DWORD alloc_cmdline_2_args(char* prog, - char* arg1, - char* arg2, - char** pname) { - DWORD status = 0; - size_t size = strlen(prog) + strlen(arg1) + strlen(arg2) + 4; - char* result = (char*)malloc_alloc_p(size); - if (!result) { - status = ERROR_NOT_ENOUGH_MEMORY; - } - else { - strcpy(result, prog); - strcat(result, " "); - strcat(result, arg1); - strcat(result, " "); - strcat(result, arg2); - *pname = result; - } - cci_debug_printf("%s made <%s>", __FUNCTION__, result); - return status; - } +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#include +#include // for _snprintf + +#include "util.h" +#include "secure.hxx" + +extern "C" { +#include "cci_debugging.h" +#include "ccutils.h" + } + + + +void* malloc_alloc_p(size_t size) { + return malloc(size); + } + +void free_alloc_p(void *pptr) { + void **real_pptr = (void**)pptr; + if (*real_pptr) { + free(*real_pptr); + *real_pptr = 0; + } + } + +extern "C" DWORD alloc_textual_sid( + PSID pSid, // binary Sid + LPSTR *pTextualSid // buffer for Textual representaion of Sid + ) { + PSID_IDENTIFIER_AUTHORITY psia; + DWORD dwSubAuthorities; + DWORD dwSidRev = SID_REVISION; + DWORD dwCounter; + DWORD dwSidSize; + + *pTextualSid = 0; + + // + // test if Sid passed in is valid + // + if(!IsValidSid(pSid)) return ERROR_INVALID_PARAMETER; + + // obtain SidIdentifierAuthority + psia = GetSidIdentifierAuthority(pSid); + + // obtain sidsubauthority count + dwSubAuthorities =* GetSidSubAuthorityCount(pSid); + + // + // compute buffer length + // S-SID_REVISION- + identifierauthority- + subauthorities- + NULL + // + dwSidSize = (15 + 12 + (12 * dwSubAuthorities) + 1) * sizeof(TCHAR); + *pTextualSid = (LPSTR)malloc_alloc_p(dwSidSize); + if (!*pTextualSid) + return GetLastError(); + + LPSTR TextualSid = *pTextualSid; + + // + // prepare S-SID_REVISION- + // + wsprintf(TextualSid, TEXT("S-%lu-"), dwSidRev ); + + // + // prepare SidIdentifierAuthority + // + if ( (psia->Value[0] != 0) || (psia->Value[1] != 0) ) + { + wsprintf(TextualSid + lstrlen(TextualSid), + TEXT("0x%02hx%02hx%02hx%02hx%02hx%02hx"), + (USHORT)psia->Value[0], + (USHORT)psia->Value[1], + (USHORT)psia->Value[2], + (USHORT)psia->Value[3], + (USHORT)psia->Value[4], + (USHORT)psia->Value[5]); + } + else + { + wsprintf(TextualSid + lstrlen(TextualSid), TEXT("%lu"), + (ULONG)(psia->Value[5] ) + + (ULONG)(psia->Value[4] << 8) + + (ULONG)(psia->Value[3] << 16) + + (ULONG)(psia->Value[2] << 24) ); + } + + // + // loop through SidSubAuthorities + // + for (dwCounter=0 ; dwCounter < dwSubAuthorities ; dwCounter++) + { + wsprintf(TextualSid + lstrlen(TextualSid), TEXT("-%lu"), + *GetSidSubAuthority(pSid, dwCounter) ); + } + return 0; +} + +DWORD alloc_token_user(HANDLE hToken, PTOKEN_USER *pptu) { + DWORD status = 0; + DWORD size = 0; + *pptu = 0; + + GetTokenInformation(hToken, TokenUser, *pptu, 0, &size); + if (size == 0) status = GetLastError(); + + if (!status) { + if (!(*pptu = (PTOKEN_USER)malloc_alloc_p(size))) + status = GetLastError(); + } + + if (!status) { + if (!GetTokenInformation(hToken, TokenUser, *pptu, size, &size)) + status = GetLastError(); + } + + if (status && *pptu) { + free_alloc_p(pptu); + } + return status; + } + +DWORD +alloc_username( + PSID Sid, + LPSTR* pname, + LPSTR* pdomain = 0 + ) +{ + DWORD status = 0; + DWORD name_len = 0; + DWORD domain_len = 0; + SID_NAME_USE snu; + LPSTR name = 0; + LPSTR domain = 0; + + *pname = 0; + if (pdomain) *pdomain = 0; + + LookupAccountSidA(NULL, Sid, 0, &name_len, 0, &domain_len, &snu); + if ((name_len == 0) || (domain_len == 0)) status = GetLastError(); + + if (!status) { + if (!(name = (LPSTR)malloc_alloc_p(name_len))) status = GetLastError(); + } + + if (!status) { + if (!(domain = (LPSTR)malloc_alloc_p(domain_len))) status = GetLastError(); + } + + if (!status) { + if (!LookupAccountSidA(NULL, Sid, name, &name_len, domain, &domain_len, &snu)) status = GetLastError(); + } + + if (status) { + if (name) free_alloc_p(&name); + if (domain) free_alloc_p(&domain); + } + else { + if (pdomain) { + *pname = name; + *pdomain = domain; + } + else { + DWORD size = name_len + domain_len + 1; + *pname = (LPSTR)malloc_alloc_p(size); + if (!*pname) status = GetLastError(); + else _snprintf(*pname, size, "%s\\%s", name, domain); + } + } + return status; + } + +DWORD get_authentication_id(HANDLE hToken, LUID* pAuthId) { + TOKEN_STATISTICS ts; + DWORD len; + + if (!GetTokenInformation(hToken, TokenStatistics, &ts, sizeof(ts), &len)) + return GetLastError(); + *pAuthId = ts.AuthenticationId; + return 0; + } + +DWORD +alloc_name_9x( + LPSTR* pname, + LPSTR postfix + ) +{ + char prefix[] = "krbcc"; + DWORD len = (sizeof(prefix) - 1) + 1 + strlen(postfix) + 1; + + *pname = (LPSTR)malloc_alloc_p(len); + if (!*pname) return GetLastError(); + _snprintf(*pname, len, "%s.%s", prefix, postfix); + return 0; +} + +DWORD alloc_name_NT(LPSTR* pname, LPSTR postfix) { + DWORD status = 0; + HANDLE hToken = 0; + LUID auth_id; +#ifdef _DEBUG + PTOKEN_USER ptu = 0; + LPSTR name = 0; + LPSTR domain = 0; + LPSTR sid = 0; +#endif + char prefix[] = "krbcc"; + // Play it safe and say 3 characters are needed per 8 bits (byte). + // Note that 20 characters are needed for a 64-bit number in + // decimal (plus one for the string termination. + // and include room for sessionId. + char lid[3*sizeof(LUID)+1+5]; + DWORD sessionId; + DWORD len = 0; + + *pname = 0; + + status = SecureClient::Token(hToken); + + if (!status) { + status = get_authentication_id(hToken, &auth_id); + } + + if (!status) { + if (!ProcessIdToSessionId(GetCurrentProcessId(), &sessionId)) + sessionId = 0; + } + +#ifdef _DEBUG + if (!status) {status = alloc_token_user(hToken, &ptu);} + if (!status) {status = alloc_username(ptu->User.Sid, &name, &domain);} + if (!status) {status = alloc_textual_sid(ptu->User.Sid, &sid);} +#endif + + if (!status) { + _snprintf(lid, sizeof(lid), "%I64u.%u", auth_id, sessionId); + lid[sizeof(lid)-1] = 0; // be safe + + len = (sizeof(prefix) - 1) + 1 + strlen(lid) + 1 + strlen(postfix) + 1; + *pname = (LPSTR)malloc_alloc_p(len); + if (!*pname) status = GetLastError(); + } + + // + // We used to allocate a name of the form: + // "prefix.domain.name.sid.lid.postfix" (usually under 80 + // characters, depending on username). However, XP thought this + // was "invalid" (too long?) for some reason. + // + // Therefore, we now use "prefix.lid.postfix" + // and for Terminal server we use "prefix.lid.sessionId.postfix" + // + + if (!status) { + _snprintf(*pname, len, "%s.%s.%s", prefix, lid, postfix); + } + +#ifdef _DEBUG + if (sid) + free_alloc_p(&sid); + if (name) + free_alloc_p(&name); + if (domain) + free_alloc_p(&domain); + if (ptu) + free_alloc_p(&ptu); +#endif + if (hToken && hToken != INVALID_HANDLE_VALUE) + CloseHandle(hToken); + if (status && *pname) + free_alloc_p(pname); + return status; +} + +extern "C" DWORD alloc_name(LPSTR* pname, LPSTR postfix, BOOL isNT) { + return isNT ? alloc_name_NT(pname, postfix) : + alloc_name_9x(pname, postfix); + } + +extern "C" DWORD alloc_own_security_descriptor_NT(PSECURITY_DESCRIPTOR* ppsd) { + DWORD status = 0; + HANDLE hToken = 0; + PTOKEN_USER ptu = 0; + PSID pSid = 0; + PACL pAcl = 0; + DWORD size = 0; + SECURITY_DESCRIPTOR sd; + + *ppsd = 0; + + if (!status) {status = SecureClient::Token(hToken);} + + // Get SID: + if (!status) {status = alloc_token_user(hToken, &ptu);} + + if (!status) { + size = GetLengthSid(ptu->User.Sid); + pSid = (PSID) malloc_alloc_p(size); + if (!pSid) status = GetLastError(); + } + if (!status) { + if (!CopySid(size, pSid, ptu->User.Sid)) status = GetLastError(); + } + + if (!status) { + // Prepare ACL: + size = sizeof(ACL); + // Add an ACE: + size += sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) + GetLengthSid(pSid); + pAcl = (PACL) malloc_alloc_p(size); + if (!pAcl) status = GetLastError(); + } + + if (!status) { + if (!InitializeAcl(pAcl, size, ACL_REVISION)) status = GetLastError(); + } + + if (!status) { + if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_ALL, pSid)) status = GetLastError(); + } + + if (!status) { + // Prepare SD itself: + if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) status = GetLastError(); + } + + if (!status) { + if (!SetSecurityDescriptorDacl(&sd, TRUE, pAcl, FALSE)) status = GetLastError(); + } + + if (!status) { + if (!SetSecurityDescriptorOwner(&sd, pSid, FALSE)) status = GetLastError(); + } + + if (!status) { + if (!IsValidSecurityDescriptor(&sd)) status = ERROR_INVALID_PARAMETER; + } + + if (!status) { + // We now have a SD. Let's copy it. + { + // This should not succeed. Instead it should give us the size. + BOOL ok = MakeSelfRelativeSD(&sd, 0, &size); + } + if (size == 0) status = GetLastError(); + } + + if (!status) { + *ppsd = (PSECURITY_DESCRIPTOR) malloc_alloc_p(size); + if (!*ppsd) status = GetLastError(); + } + + if (!status) { + if (!MakeSelfRelativeSD(&sd, *ppsd, &size)) status = GetLastError(); + } + + if (ptu) free_alloc_p(&ptu); + if (pSid) free_alloc_p(&pSid); + if (pAcl) free_alloc_p(&pAcl); + if (hToken && hToken != INVALID_HANDLE_VALUE) CloseHandle(hToken); + if (status && *ppsd) free_alloc_p(ppsd); + return status; +} + +DWORD +alloc_module_file_name( + char* module, + char** pname + ) +{ + const DWORD max = 8192; + DWORD status = 0; + DWORD got = 0; + DWORD size = 512; // use low number to test... + HMODULE h = 0; + BOOL ok = FALSE; + char* name = 0; + + if (!pname) + return ERROR_INVALID_PARAMETER; + *pname = 0; + + h = GetModuleHandle(module); + + if (!h) return GetLastError(); + + // We assume size < max and size > 0 + while (!status && !ok) { + if (size > max) { + // XXX - Assert? + status = ERROR_INVALID_DATA; + continue; + } + if (name) free_alloc_p(&name); + name = (char*)malloc_alloc_p(size + 1); + if (!name) { + status = ERROR_NOT_ENOUGH_MEMORY; + continue; + } + name[size] = 0; + got = GetModuleFileName(h, name, size); + if (!got) { + status = GetLastError(); + // sanity check: + if (!status) { + // XXX - print nasty message...assert? + status = ERROR_INVALID_DATA; + } + continue; + } + // To know we're ok, we need to verify that what we got + // was bigger than GetModuleSize thought it got. + ok = got && (got < size) && !name[got]; + size *= 2; + } + if (status && name) + free_alloc_p(&name); + else + *pname = name; + return status; +} + +DWORD +alloc_module_dir_name( + char* module, + char** pname + ) +{ + DWORD status = alloc_module_file_name(module, pname); + if (!status) { + char* name = *pname; + char* p = name + strlen(name); + while ((p >= name) && (*p != '\\') && (*p != '/')) p--; + if (p < name) { + free_alloc_p(pname); + status = ERROR_INVALID_DATA; + } else { + *p = 0; + } + } + return status; +} + +DWORD +alloc_module_dir_name_with_file( + char* module, + char* file, + char** pname + ) +{ + DWORD status = alloc_module_dir_name(module, pname); + if (!status) { + char* name = *pname; + size_t name_size = strlen(name); + size_t size = name_size + 1 + strlen(file) + 1; + char* result = (char*)malloc_alloc_p(size); + if (!result) { + status = ERROR_NOT_ENOUGH_MEMORY; + free_alloc_p(pname); + } else { + strcpy(result, name); + result[name_size] = '\\'; + strcpy(result + name_size + 1, file); + free_alloc_p(pname); + *pname = result; + } + } + return status; +} + +DWORD alloc_cmdline_2_args(char* prog, + char* arg1, + char* arg2, + char** pname) { + DWORD status = 0; + size_t size = strlen(prog) + strlen(arg1) + strlen(arg2) + 4; + char* result = (char*)malloc_alloc_p(size); + if (!result) { + status = ERROR_NOT_ENOUGH_MEMORY; + } + else { + strcpy(result, prog); + strcat(result, " "); + strcat(result, arg1); + strcat(result, " "); + strcat(result, arg2); + *pname = result; + } + cci_debug_printf("%s made <%s>", __FUNCTION__, result); + return status; + } diff --git a/src/ccapi/common/win/ccs_reply.Acf b/src/ccapi/common/win/ccs_reply.Acf index 89e8abe7a..aea44d74c 100644 --- a/src/ccapi/common/win/ccs_reply.Acf +++ b/src/ccapi/common/win/ccs_reply.Acf @@ -1,31 +1,31 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -[implicit_handle(handle_t ccs_reply_IfHandle)] - -interface ccs_reply { - [async] ccapi_listen(); - } +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +[implicit_handle(handle_t ccs_reply_IfHandle)] + +interface ccs_reply { + [async] ccapi_listen(); + } diff --git a/src/ccapi/common/win/ccs_reply.Idl b/src/ccapi/common/win/ccs_reply.Idl index 4c6f6f304..9035a4d00 100644 --- a/src/ccapi/common/win/ccs_reply.Idl +++ b/src/ccapi/common/win/ccs_reply.Idl @@ -1,60 +1,60 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -[ uuid (6E3B5060-CA46-1067-B31A-00DD010662DA), - version(1.0), - pointer_default(unique) -] - -/* This interface sends a cci_stream via rpc. - */ - -interface ccs_reply { - const long HSIZE = sizeof(void*); - -/* The reply from the server to a request from the client: */ -void ccs_rpc_request_reply( - [in] const long rpcmsg, /* Message type */ - [in, size_is(HSIZE)] const char tsphandle[], - [in, string] const char* uuid, - [in] const long srvStartTime, /* Server Start Time */ - [in] const long cbIn, /* Length of buffer */ - [in, size_is(cbIn)] const unsigned char chIn[], /* Data buffer */ - [out] long* status ); /* Return code */ - -void ccs_rpc_connect_reply( - [in] const long rpcmsg, /* Message type */ - [in, size_is(HSIZE)] const char tsphandle[], - [in, string] const char* uuid, - [in] const long srvStartTime, /* Server Start Time */ - [out] long* status ); /* Return code */ - -void ccapi_listen( - handle_t hBinding, - [in] const long rpcmsg, /* Message type */ - [out] long* status ); /* Return code */ - - } +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +[ uuid (6E3B5060-CA46-1067-B31A-00DD010662DA), + version(1.0), + pointer_default(unique) +] + +/* This interface sends a cci_stream via rpc. + */ + +interface ccs_reply { + const long HSIZE = sizeof(void*); + +/* The reply from the server to a request from the client: */ +void ccs_rpc_request_reply( + [in] const long rpcmsg, /* Message type */ + [in, size_is(HSIZE)] const char tsphandle[], + [in, string] const char* uuid, + [in] const long srvStartTime, /* Server Start Time */ + [in] const long cbIn, /* Length of buffer */ + [in, size_is(cbIn)] const unsigned char chIn[], /* Data buffer */ + [out] long* status ); /* Return code */ + +void ccs_rpc_connect_reply( + [in] const long rpcmsg, /* Message type */ + [in, size_is(HSIZE)] const char tsphandle[], + [in, string] const char* uuid, + [in] const long srvStartTime, /* Server Start Time */ + [out] long* status ); /* Return code */ + +void ccapi_listen( + handle_t hBinding, + [in] const long rpcmsg, /* Message type */ + [out] long* status ); /* Return code */ + + } diff --git a/src/ccapi/common/win/ccs_request.Acf b/src/ccapi/common/win/ccs_request.Acf index 853a15252..625bcce65 100644 --- a/src/ccapi/common/win/ccs_request.Acf +++ b/src/ccapi/common/win/ccs_request.Acf @@ -1,31 +1,31 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -[implicit_handle(handle_t ccs_request_IfHandle)] -interface ccs_request -{ - -} +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +[implicit_handle(handle_t ccs_request_IfHandle)] +interface ccs_request +{ + +} diff --git a/src/ccapi/common/win/ccs_request.idl b/src/ccapi/common/win/ccs_request.idl index bd693142c..8c68fd8f3 100644 --- a/src/ccapi/common/win/ccs_request.idl +++ b/src/ccapi/common/win/ccs_request.idl @@ -1,58 +1,58 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -[ uuid (906B0CE0-C70B-1067-B317-00DD010662DA), - version(1.0), - pointer_default(unique) -] - -interface ccs_request { - -typedef char CC_CHAR; -typedef unsigned char CC_UCHAR; -typedef int CC_INT32; -typedef unsigned int CC_UINT32; - -const long HSIZE = sizeof(void*); - -void ccs_rpc_request( - [in] const long rpcmsg, /* Message type */ - [in, size_is(HSIZE)] const char tsphandle[], - [in, string] const char* pszUUID, /* Requestor's UUID */ - [in] const long lenRequest, /* Length of buffer */ - [in, size_is(lenRequest)] const char* pszRequest, /* Data buffer */ - [in] const long serverStartTime,/* Which server session we're talking to */ - [out] long* status ); /* Return code */ - -void ccs_rpc_connect( - [in] const long rpcmsg, /* Message type */ - [in, size_is(HSIZE)] const char tsphandle[], - [in, string] const char* pszUUID, /* Requestor's UUID */ - [out] long* status ); /* Return code */ - -CC_UINT32 ccs_authenticate( - [in, string] const CC_CHAR* name ); -} +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +[ uuid (906B0CE0-C70B-1067-B317-00DD010662DA), + version(1.0), + pointer_default(unique) +] + +interface ccs_request { + +typedef char CC_CHAR; +typedef unsigned char CC_UCHAR; +typedef int CC_INT32; +typedef unsigned int CC_UINT32; + +const long HSIZE = sizeof(void*); + +void ccs_rpc_request( + [in] const long rpcmsg, /* Message type */ + [in, size_is(HSIZE)] const char tsphandle[], + [in, string] const char* pszUUID, /* Requestor's UUID */ + [in] const long lenRequest, /* Length of buffer */ + [in, size_is(lenRequest)] const char* pszRequest, /* Data buffer */ + [in] const long serverStartTime,/* Which server session we're talking to */ + [out] long* status ); /* Return code */ + +void ccs_rpc_connect( + [in] const long rpcmsg, /* Message type */ + [in, size_is(HSIZE)] const char tsphandle[], + [in, string] const char* pszUUID, /* Requestor's UUID */ + [out] long* status ); /* Return code */ + +CC_UINT32 ccs_authenticate( + [in, string] const CC_CHAR* name ); +} diff --git a/src/ccapi/doc/CCAPI-Windows-Design.html b/src/ccapi/doc/CCAPI-Windows-Design.html index 8be161447..72af7e92a 100644 --- a/src/ccapi/doc/CCAPI-Windows-Design.html +++ b/src/ccapi/doc/CCAPI-Windows-Design.html @@ -1,148 +1,148 @@ - - - - -Windows CCAPI RPC design - - - - -

Proposed RPC design for Windows CCAPI clients and server

-

The proposal is for a single user; the solution is replicated for each user logged onto the PC.

-

Conventions & clarifications

-

"Client" and "server" refer to the CCAPI client and server.

-

The CCAPI client acts as both an RPC client and RPC server and the CCAPI server acts as both an RPC client and RPC server.

-
    -
  • The RPC call from the CCAPI client to the CCAPI server is called the "request." In this mode, the CCAPI client is the RPC client and the CCAPI server is the RPC server.
  • -
  • The RPC call from the CCAPI server to the CCAPI client is called the "reply." In this mode, the CCAPI client is the RPC server and the CCAPI server is the RPC client.
  • -
-

The Windows username is referred to below as "<USER>."

-

The Windows Logon Security Identifier is referred to as "<LSID>."

-

<UUID> means a thread-specific UUID.

-

<SST> means server start time, a time_t.

-

A description of client and server authentication has not been added yet.

-

Design Requirements

-
    -
  • The server's OS-independent code is single threaded, because it must operate on platforms that do not allow multiple threads.
  • -
  • The client and server must be able to maintain connections, where state is maintained between individual messages.
  • -
  • Individual messages must be handled in a single threaded server.
  • -
  • The server must be able to detect when a client dies, so that any connection state can be cleaned up.
  • -
-

Design

-

The server and each client create an RPC endpoint. The server's endpoint is CCS_<LSID> and the client's endpoint is CCAPI_<UUID>, where each client geta a UUID.

-

On Windows, the server's ccs_pipe_t type is a char* and is set to the client UUID.

-

How is the request handled in the server and the reply sent to the client?

-

One straightforward way is for the reply to be the returned data in the request RPC call (an [out] parameter). That is, data passed from the RPC server to the RPC client. The request handler calls ccs_server_handle_request. Eventually, the server code calls ccs_os_server_send_reply, which saves the reply somewhere. When the server eventually returns to the request handler, the handler returns the saved reply to the client.

-

But this doesn't work. If two clients A and B ask for the same lock, A will acquire the lock and B will have to wait. But if the single threaded server waits for B's lock, it will never handle A's unlock message. Therefore the server must return to B's request handler and not send a reply to B. So this method will not work.

-

Instead, there are listener and worker threads in Windows-specific code.

-

The client's cci_os_ipc function waits for ccs_reply. The client sends the request, including it's UUID, from which the server can construct the endpoint on which to call ccs_reply.

-

The server's listener thread listens for RPC requests. The request handler puts each request/reply endpoint in a queue and returns to the client.

-

The server's worker thread removes items from the queue, calls ccs_server_handle_request. ccs_server_handle_request takes both the request data and the client UUID . Eventually ccs_os_server_send_reply is called, with the reply data and client UUID in the reply_pipe. ccs_os_server_send_reply calls ccs_reply on the client's endpoint, which sends the reply to the client.

-

Is there any security issue with the client listening for RPC calls from the server?

-

Connections

-

If the client wants state to be maintained on the server, the client creates a connection. When the connection is closed, the server cleans up any state associated with the connection.

-

Any given thread in an application process could want to create a connection. When cci_ipc_thread_init is called, the connection thread-local variables are initialized. New connections are created when cci_os_ipc() (via _cci_ipc_send) is called and no connection was previously established. Basically we lazily establish connections so the client doesn't talk to the server until it has to.

-

Detecting client exit

-

The server must be able to detect when clients disappear, so the server can free any resources that had been held for the client.

-

The Windows RPC API does not appear to provide a notification for an endpoint disappearing. It does provide a way to ask if an endpoint is listening. This is useful for polling, but we want a better performing solution than that.

-

The client has an isAlive function on its endpoint.

-

To detect the client disappearing without using polling, the server makes an asynchronous call to the isAlive function on the client's endpoint. The isAlive function never returns. When the client exits for any reason, it's endpoint will be closed and the server's function call will return an error. The asynchronous call on the server means no additional threads are used.

-

Windows provides a number of notification methods to signal I/O completion. Among them are I/O completion ports and callback functions. I chose callback functions because they appear to consume fewer resources.

-

RPC Endpoint / Function summary

-
    -
  • The server creates one CCS_<LSID> endpoint to listen for connection requests and client requests. - It has the functions -
      -
    • ccs_rpc_connect(msgtype, UUIDlen, <UUID>, status)
    • -
    • ccs_rpc_request(msgtype, UUIDlen, <UUID>, msglen, msg, SST, status) called by client. NB: The windows server sets the in_client_pipe to the in_reply_pipe.
      -
    • -
    -
  • -
  • Each client thread creates a CCAPI_<UUID> endpoint. It has the functions -
      -
    • isAlive [function never returns.]
    • -
    • ccs_rpc_request_reply(msgtype, SST, replylen, reply, status)
    • -
    • ccs_rpc_connect_reply(msgtype, SST, status
    • -
    -
  • -
-

Windows-specific implementation details

-

Client CCAPI library initialization:

-

This code runs when the CCAPI DLL is loaded.

-
    -
  • ?
  • -
-

Client initialization:

-

This code runs when cci_os_ipc_thread_init is called:

-
    -
  • Generate <UUID> and save in thread-specific storage. This serves as the client ID / ccs_pipe_t.
  • -
  • Create client endpoint.
  • -
  • Listen on client endpoint.
  • -
  • Create canonical server connection endpoint from the <LSID>, which the client and server should have in common.
  • -
  • Test if server is listening to the CCS_<LSID> endpoint. -
      -
    • If not, quit. (! Start it?)
    • -
    -
  • -
  • Call ccs_connect(<UUID>) on the CCS_<LSID> endpoint.
  • -
  • Save SST in thread-specific storage.
  • -
-

Server initialization:

-

[old]

-
    -
  • Server is initialized by client starting a new process. There should be only one server process per Windows username.
  • -
-

[new]

-
    -
  • Server is started by kfwlogon (as is done currently).
  • -
  • Capture server start time (SST).
  • -
  • Start listener thread, create listener endpoint, listen on CCS_<LSID> endpoint.
  • -
-

Establishing a connection:

-
    -
  • Client calls ccs_connect(<UUID>) on server's CCS_<LSID> endpoint.
  • -
  • Client gets back and stores SST in thread-specific storage.
  • -
  • If new connection, server ... -
      -
    • adds connection to connection table
    • -
    • calls isAlive on CCAPI_<UUID>. -
        -
      • NB: isAlive never returns.
      • -
      -
    • -
    -
  • -
-

Client request:

-

The server's reply to the client's request is not synchronous.

-
    -
  • Client calls ccs_rpc_request(msglen, msg, msgtype, UUIDlen, <UUID>, SST, status) on server's endpoint.
  • -
  • Server listen thread receives message, queues request.
  • -
  • Server worker thread dequeues request, processes, calls ccs_rpc_reply(replylen, reply, msgtype, status) on CCAPI_<UUID>.
  • -
  • Server checks SST. If server's SST is different, it means server has restarted since client created connection.
  • -
  • Client receives reply.
  • -
-

Detecting client exit

-
    -
  • When connection created, client created an endpoint.
  • -
  • Server calls isAlive on client's endpoint.
  • -
  • When isAlive returns, the server's notification callback will be called. Call back routine queues a DISCONNECT pseudo-message. When the server's worker thread handles the DISCONNECT, it will release connection resources.
  • -
-

Detecting server exit

-
    -
  • Client's call to ccs_rpc_request will return an error if the server has gone away.
  • -
-

 

-

------
- Stop:
-Start:

- - + + + + +Windows CCAPI RPC design + + + + +

Proposed RPC design for Windows CCAPI clients and server

+

The proposal is for a single user; the solution is replicated for each user logged onto the PC.

+

Conventions & clarifications

+

"Client" and "server" refer to the CCAPI client and server.

+

The CCAPI client acts as both an RPC client and RPC server and the CCAPI server acts as both an RPC client and RPC server.

+
    +
  • The RPC call from the CCAPI client to the CCAPI server is called the "request." In this mode, the CCAPI client is the RPC client and the CCAPI server is the RPC server.
  • +
  • The RPC call from the CCAPI server to the CCAPI client is called the "reply." In this mode, the CCAPI client is the RPC server and the CCAPI server is the RPC client.
  • +
+

The Windows username is referred to below as "<USER>."

+

The Windows Logon Security Identifier is referred to as "<LSID>."

+

<UUID> means a thread-specific UUID.

+

<SST> means server start time, a time_t.

+

A description of client and server authentication has not been added yet.

+

Design Requirements

+
    +
  • The server's OS-independent code is single threaded, because it must operate on platforms that do not allow multiple threads.
  • +
  • The client and server must be able to maintain connections, where state is maintained between individual messages.
  • +
  • Individual messages must be handled in a single threaded server.
  • +
  • The server must be able to detect when a client dies, so that any connection state can be cleaned up.
  • +
+

Design

+

The server and each client create an RPC endpoint. The server's endpoint is CCS_<LSID> and the client's endpoint is CCAPI_<UUID>, where each client geta a UUID.

+

On Windows, the server's ccs_pipe_t type is a char* and is set to the client UUID.

+

How is the request handled in the server and the reply sent to the client?

+

One straightforward way is for the reply to be the returned data in the request RPC call (an [out] parameter). That is, data passed from the RPC server to the RPC client. The request handler calls ccs_server_handle_request. Eventually, the server code calls ccs_os_server_send_reply, which saves the reply somewhere. When the server eventually returns to the request handler, the handler returns the saved reply to the client.

+

But this doesn't work. If two clients A and B ask for the same lock, A will acquire the lock and B will have to wait. But if the single threaded server waits for B's lock, it will never handle A's unlock message. Therefore the server must return to B's request handler and not send a reply to B. So this method will not work.

+

Instead, there are listener and worker threads in Windows-specific code.

+

The client's cci_os_ipc function waits for ccs_reply. The client sends the request, including it's UUID, from which the server can construct the endpoint on which to call ccs_reply.

+

The server's listener thread listens for RPC requests. The request handler puts each request/reply endpoint in a queue and returns to the client.

+

The server's worker thread removes items from the queue, calls ccs_server_handle_request. ccs_server_handle_request takes both the request data and the client UUID . Eventually ccs_os_server_send_reply is called, with the reply data and client UUID in the reply_pipe. ccs_os_server_send_reply calls ccs_reply on the client's endpoint, which sends the reply to the client.

+

Is there any security issue with the client listening for RPC calls from the server?

+

Connections

+

If the client wants state to be maintained on the server, the client creates a connection. When the connection is closed, the server cleans up any state associated with the connection.

+

Any given thread in an application process could want to create a connection. When cci_ipc_thread_init is called, the connection thread-local variables are initialized. New connections are created when cci_os_ipc() (via _cci_ipc_send) is called and no connection was previously established. Basically we lazily establish connections so the client doesn't talk to the server until it has to.

+

Detecting client exit

+

The server must be able to detect when clients disappear, so the server can free any resources that had been held for the client.

+

The Windows RPC API does not appear to provide a notification for an endpoint disappearing. It does provide a way to ask if an endpoint is listening. This is useful for polling, but we want a better performing solution than that.

+

The client has an isAlive function on its endpoint.

+

To detect the client disappearing without using polling, the server makes an asynchronous call to the isAlive function on the client's endpoint. The isAlive function never returns. When the client exits for any reason, it's endpoint will be closed and the server's function call will return an error. The asynchronous call on the server means no additional threads are used.

+

Windows provides a number of notification methods to signal I/O completion. Among them are I/O completion ports and callback functions. I chose callback functions because they appear to consume fewer resources.

+

RPC Endpoint / Function summary

+
    +
  • The server creates one CCS_<LSID> endpoint to listen for connection requests and client requests. + It has the functions +
      +
    • ccs_rpc_connect(msgtype, UUIDlen, <UUID>, status)
    • +
    • ccs_rpc_request(msgtype, UUIDlen, <UUID>, msglen, msg, SST, status) called by client. NB: The windows server sets the in_client_pipe to the in_reply_pipe.
      +
    • +
    +
  • +
  • Each client thread creates a CCAPI_<UUID> endpoint. It has the functions +
      +
    • isAlive [function never returns.]
    • +
    • ccs_rpc_request_reply(msgtype, SST, replylen, reply, status)
    • +
    • ccs_rpc_connect_reply(msgtype, SST, status
    • +
    +
  • +
+

Windows-specific implementation details

+

Client CCAPI library initialization:

+

This code runs when the CCAPI DLL is loaded.

+
    +
  • ?
  • +
+

Client initialization:

+

This code runs when cci_os_ipc_thread_init is called:

+
    +
  • Generate <UUID> and save in thread-specific storage. This serves as the client ID / ccs_pipe_t.
  • +
  • Create client endpoint.
  • +
  • Listen on client endpoint.
  • +
  • Create canonical server connection endpoint from the <LSID>, which the client and server should have in common.
  • +
  • Test if server is listening to the CCS_<LSID> endpoint. +
      +
    • If not, quit. (! Start it?)
    • +
    +
  • +
  • Call ccs_connect(<UUID>) on the CCS_<LSID> endpoint.
  • +
  • Save SST in thread-specific storage.
  • +
+

Server initialization:

+

[old]

+
    +
  • Server is initialized by client starting a new process. There should be only one server process per Windows username.
  • +
+

[new]

+
    +
  • Server is started by kfwlogon (as is done currently).
  • +
  • Capture server start time (SST).
  • +
  • Start listener thread, create listener endpoint, listen on CCS_<LSID> endpoint.
  • +
+

Establishing a connection:

+
    +
  • Client calls ccs_connect(<UUID>) on server's CCS_<LSID> endpoint.
  • +
  • Client gets back and stores SST in thread-specific storage.
  • +
  • If new connection, server ... +
      +
    • adds connection to connection table
    • +
    • calls isAlive on CCAPI_<UUID>. +
        +
      • NB: isAlive never returns.
      • +
      +
    • +
    +
  • +
+

Client request:

+

The server's reply to the client's request is not synchronous.

+
    +
  • Client calls ccs_rpc_request(msglen, msg, msgtype, UUIDlen, <UUID>, SST, status) on server's endpoint.
  • +
  • Server listen thread receives message, queues request.
  • +
  • Server worker thread dequeues request, processes, calls ccs_rpc_reply(replylen, reply, msgtype, status) on CCAPI_<UUID>.
  • +
  • Server checks SST. If server's SST is different, it means server has restarted since client created connection.
  • +
  • Client receives reply.
  • +
+

Detecting client exit

+
    +
  • When connection created, client created an endpoint.
  • +
  • Server calls isAlive on client's endpoint.
  • +
  • When isAlive returns, the server's notification callback will be called. Call back routine queues a DISCONNECT pseudo-message. When the server's worker thread handles the DISCONNECT, it will release connection resources.
  • +
+

Detecting server exit

+
    +
  • Client's call to ccs_rpc_request will return an error if the server has gone away.
  • +
+

 

+

------
+ Stop:
+Start:

+ + diff --git a/src/ccapi/lib/win/OldCC/client.cxx b/src/ccapi/lib/win/OldCC/client.cxx index 1f9051093..4928d4c53 100644 --- a/src/ccapi/lib/win/OldCC/client.cxx +++ b/src/ccapi/lib/win/OldCC/client.cxx @@ -1,389 +1,389 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#include "stdio.h" // KPKDBG - -#include "ccs_request.h" - -#include "ccapi.h" -#include "util.h" - -extern "C" { -#include "cci_debugging.h" -#include "tls.h" // KPKDBG - } - -#include "client.h" -#include "init.hxx" -#include "name.h" -#include "secure.hxx" - -#define SECONDS_TO_WAIT 10 - -#define STARTUP "CLIENT STARTUP: " -#define DISCONNECT "CLIENT DISCONNECT: " - -bool Client::s_init = false; -CcOsLock Client::sLock; - -static DWORD bind_client(char* ep OPTIONAL, Init::InitInfo& info, LPSTR* endpoint) { - DWORD status = 0; - unsigned char * pszStringBinding = NULL; - - if (!ep) { - status = alloc_name(endpoint, "ep", isNT()); - } - else { - *endpoint = ep; - } - - if (!status) { - /* Use a convenience function to concatenate the elements of */ - /* the string binding into the proper sequence. */ - status = RpcStringBindingCompose(0, // uuid - (unsigned char*)"ncalrpc", // protseq - 0, // address - (unsigned char*)(*endpoint), // endpoint - 0, // options - &pszStringBinding); - cci_check_error(status); - } - - if (!status) { - /* Set the binding handle that will be used to bind to the server. */ - status = RpcBindingFromStringBinding(pszStringBinding, &ccs_request_IfHandle); - cci_check_error(status); - } - - if (!status) { - // Win9x might call RpcBindingSetAuthInfo (not Ex), but it does not - // quite work on Win9x... - if (isNT()) { - RPC_SECURITY_QOS qos; - qos.Version = RPC_C_SECURITY_QOS_VERSION; - qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT; - qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; - qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY; - - status = info.fRpcBindingSetAuthInfoEx(ccs_request_IfHandle, - 0, // principal - RPC_C_AUTHN_LEVEL_CONNECT, - RPC_C_AUTHN_WINNT, - 0, // current address space - RPC_C_AUTHZ_NAME, - &qos); - cci_check_error(status); - } - } - - if (pszStringBinding) { - DWORD status = RpcStringFree(&pszStringBinding); - cci_check_error(status); - } - return cci_check_error(status); - } - -DWORD find_server(Init::InitInfo& info, LPSTR endpoint) { - DWORD status = 0; - LPSTR event_name = 0; - HANDLE hEvent = 0; - SECURITY_ATTRIBUTES sa = { 0 }; - PSECURITY_ATTRIBUTES psa = 0; - STARTUPINFO si = { 0 }; - PROCESS_INFORMATION pi = { 0 }; - char* szExe = 0; - char* szDir = 0; - BOOL bRes = FALSE; - char* cmdline = NULL; -#if 0 - HANDLE hToken = 0; -#endif - - psa = isNT() ? &sa : 0; - -// cci_debug_printf("%s Looking for server; ccs_request_IfHandle:0x%X", __FUNCTION__, ccs_request_IfHandle); - status = cci_check_error(RpcMgmtIsServerListening(ccs_request_IfHandle)); - if (status == RPC_S_NOT_LISTENING) { -// cci_debug_printf(" Server *NOT* found!"); - si.cb = sizeof(si); - - status = alloc_module_dir_name(CCAPI_DLL, &szDir); - - if (!status) { - status = alloc_module_dir_name_with_file(CCAPI_DLL, CCAPI_EXE, &szExe); - } - - if (!status) { - status = alloc_name(&event_name, "startup", isNT()); - cci_check_error(status); - } - - if (!status) { - if (isNT()) { - sa.nLength = sizeof(sa); - status = alloc_own_security_descriptor_NT(&sa.lpSecurityDescriptor); - cci_check_error(status); - } - } - - if (!status) { - hEvent = CreateEvent(psa, FALSE, FALSE, event_name); - cci_debug_printf(" CreateEvent(... %s) returned hEvent 0x%X", event_name, hEvent); - if (!hEvent) status = GetLastError(); - } - - if (!status) { - -#if 0 - if (SecureClient::IsImp()) { - cci_debug_printf(STARTUP "Token is impersonation token")); - SecureClient::DuplicateImpAsPrimary(hToken); - } - else { - cci_debug_printf(STARTUP "Token is NOT impersonation token")); - } -#endif - -#if 0 - if (hToken) - bRes = CreateProcessAsUser(hToken, - szExe, // app name - NULL, // cmd line - psa, // SA - psa, // SA - FALSE, - CREATE_NEW_PROCESS_GROUP | - //CREATE_NEW_CONSOLE | - NORMAL_PRIORITY_CLASS | - // CREATE_NO_WINDOW | - DETACHED_PROCESS | - 0 - , - NULL, // environment - szDir, // current dir - &si, - &pi); - else -#endif - alloc_cmdline_2_args(szExe, endpoint, "-D", &cmdline); - bRes = CreateProcess( szExe, // app name - NULL, //cmdline, // cmd line is - psa, // SA - psa, // SA - FALSE, - CREATE_NEW_PROCESS_GROUP | - CREATE_NEW_CONSOLE | - NORMAL_PRIORITY_CLASS | - // CREATE_NO_WINDOW | - // DETACHED_PROCESS | /* KPK TODO: was set - restore */ - 0 - , - NULL, // environment - szDir, // current dir - &si, - &pi); - if (!bRes) { - status = GetLastError(); - cci_debug_printf(" CreateProcess returned %d; LastError: %d", bRes, status); - } - cci_debug_printf(" Waiting..."); - } - cci_check_error(status); - - if (!status) { - status = WaitForSingleObject(hEvent, (SECONDS_TO_WAIT)*1000); - status = RpcMgmtIsServerListening(ccs_request_IfHandle); - } - } - else if (status) { - cci_debug_printf(" unexpected error while looking for server: 0D%d / 0U%u / 0X%X", status, status, status); - } - -#if 0 - if (hToken) - CloseHandle(hToken); -#endif - if (szDir) free_alloc_p(&szDir); - if (szExe) free_alloc_p(&szExe); - if (hEvent) CloseHandle(hEvent); - if (pi.hThread) CloseHandle(pi.hThread); - if (pi.hProcess) CloseHandle(pi.hProcess); - if (sa.lpSecurityDescriptor) free_alloc_p(&sa.lpSecurityDescriptor); - return cci_check_error(status); - -} - -static -DWORD -authenticate_server(Init::InitInfo& info) { - DWORD challenge = 17; // XXX - maybe use random number - DWORD desired_response= challenge + 1; - HANDLE hMap = 0; - LPSTR mem_name = 0; - PDWORD pvalue = 0; - CC_UINT32 response = 0; - SECURITY_ATTRIBUTES sa = { 0 }; - DWORD status = 0; - - cci_debug_printf("%s entry", __FUNCTION__); - - status = alloc_name(&mem_name, "auth", isNT()); - cci_check_error(status); - - if (!status) { - if (isNT()) { - sa.nLength = sizeof(sa); - status = alloc_own_security_descriptor_NT(&sa.lpSecurityDescriptor); - } - } - cci_check_error(status); - - if (!status) { - hMap = CreateFileMapping(INVALID_HANDLE_VALUE, isNT() ? &sa : 0, - PAGE_READWRITE, 0, sizeof(DWORD), mem_name); - if (!hMap) - status = GetLastError(); - } - cci_check_error(status); - - if (!status) { - pvalue = (PDWORD)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0); - if (!pvalue) status = GetLastError(); - } - cci_check_error(status); - - if (!status) { - *pvalue = challenge; - - RpcTryExcept { - response = ccs_authenticate( (CC_CHAR*)mem_name ); - } - RpcExcept(1) { - status = RpcExceptionCode(); - cci_check_error(status); - } - RpcEndExcept; - } - cci_check_error(status); - - if (!status) { - // Check response - if ((response != desired_response) && (*pvalue != desired_response)) { - cci_debug_printf(" Could not authenticate server."); - status = ERROR_ACCESS_DENIED; // XXX - CO_E_NOMATCHINGSIDFOUND? - } - else { - cci_debug_printf(" Server authenticated!"); - } - cci_check_error(status); - } - - free_alloc_p(&mem_name); - free_alloc_p(&sa.lpSecurityDescriptor); - if (pvalue) { - BOOL ok = UnmapViewOfFile(pvalue); -// DEBUG_ASSERT(ok); - } - if (hMap) CloseHandle(hMap); - return status; -} - -DWORD -Client::Disconnect() { - DWORD status = 0; - if (ccs_request_IfHandle) { - /* The calls to the remote procedures are complete. */ - /* Free the binding handle */ - status = RpcBindingFree(&ccs_request_IfHandle); - } - s_init = false; - return status; - } - -DWORD -Client::Connect(char* ep OPTIONAL) { - LPSTR endpoint = 0; - DWORD status = 0; - - if (!ccs_request_IfHandle) { - Init::InitInfo info; - - status = Init::Info(info); - cci_check_error(status); - - if (!status) { - status = bind_client(ep, info, &endpoint); - cci_check_error(status); - } - - if (!status) { - status = find_server(info, endpoint); - cci_check_error(status); - } - - if (!status) { - status = authenticate_server(info); - cci_check_error(status); - } - } - - - if (endpoint && (endpoint != ep)) free_alloc_p(&endpoint); - - if (status) Client::Disconnect(); - return status; - } - -DWORD Client::Initialize(char* ep OPTIONAL) { - CcAutoLock AL(Client::sLock); - SecureClient s; - ccs_request_IfHandle = NULL; - if (s_init) return 0; - DWORD status = Client::Connect(ep); - if (!status) s_init = true; - return status; - } - -DWORD Client::Cleanup() { - CcAutoLock AL(Client::sLock); - SecureClient s; - return Client::Disconnect(); - } - -DWORD Client::Reconnect(char* ep OPTIONAL) { - CcAutoLock AL(Client::sLock); - SecureClient s; - DWORD status = 0; - - if (Initialized()) { - DWORD status = Client::Cleanup(); - } - if ( (!status) ) { - status = Client::Initialize(ep); - } - - return status; - } +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#include "stdio.h" // KPKDBG + +#include "ccs_request.h" + +#include "ccapi.h" +#include "util.h" + +extern "C" { +#include "cci_debugging.h" +#include "tls.h" // KPKDBG + } + +#include "client.h" +#include "init.hxx" +#include "name.h" +#include "secure.hxx" + +#define SECONDS_TO_WAIT 10 + +#define STARTUP "CLIENT STARTUP: " +#define DISCONNECT "CLIENT DISCONNECT: " + +bool Client::s_init = false; +CcOsLock Client::sLock; + +static DWORD bind_client(char* ep OPTIONAL, Init::InitInfo& info, LPSTR* endpoint) { + DWORD status = 0; + unsigned char * pszStringBinding = NULL; + + if (!ep) { + status = alloc_name(endpoint, "ep", isNT()); + } + else { + *endpoint = ep; + } + + if (!status) { + /* Use a convenience function to concatenate the elements of */ + /* the string binding into the proper sequence. */ + status = RpcStringBindingCompose(0, // uuid + (unsigned char*)"ncalrpc", // protseq + 0, // address + (unsigned char*)(*endpoint), // endpoint + 0, // options + &pszStringBinding); + cci_check_error(status); + } + + if (!status) { + /* Set the binding handle that will be used to bind to the server. */ + status = RpcBindingFromStringBinding(pszStringBinding, &ccs_request_IfHandle); + cci_check_error(status); + } + + if (!status) { + // Win9x might call RpcBindingSetAuthInfo (not Ex), but it does not + // quite work on Win9x... + if (isNT()) { + RPC_SECURITY_QOS qos; + qos.Version = RPC_C_SECURITY_QOS_VERSION; + qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT; + qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; + qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY; + + status = info.fRpcBindingSetAuthInfoEx(ccs_request_IfHandle, + 0, // principal + RPC_C_AUTHN_LEVEL_CONNECT, + RPC_C_AUTHN_WINNT, + 0, // current address space + RPC_C_AUTHZ_NAME, + &qos); + cci_check_error(status); + } + } + + if (pszStringBinding) { + DWORD status = RpcStringFree(&pszStringBinding); + cci_check_error(status); + } + return cci_check_error(status); + } + +DWORD find_server(Init::InitInfo& info, LPSTR endpoint) { + DWORD status = 0; + LPSTR event_name = 0; + HANDLE hEvent = 0; + SECURITY_ATTRIBUTES sa = { 0 }; + PSECURITY_ATTRIBUTES psa = 0; + STARTUPINFO si = { 0 }; + PROCESS_INFORMATION pi = { 0 }; + char* szExe = 0; + char* szDir = 0; + BOOL bRes = FALSE; + char* cmdline = NULL; +#if 0 + HANDLE hToken = 0; +#endif + + psa = isNT() ? &sa : 0; + +// cci_debug_printf("%s Looking for server; ccs_request_IfHandle:0x%X", __FUNCTION__, ccs_request_IfHandle); + status = cci_check_error(RpcMgmtIsServerListening(ccs_request_IfHandle)); + if (status == RPC_S_NOT_LISTENING) { +// cci_debug_printf(" Server *NOT* found!"); + si.cb = sizeof(si); + + status = alloc_module_dir_name(CCAPI_DLL, &szDir); + + if (!status) { + status = alloc_module_dir_name_with_file(CCAPI_DLL, CCAPI_EXE, &szExe); + } + + if (!status) { + status = alloc_name(&event_name, "startup", isNT()); + cci_check_error(status); + } + + if (!status) { + if (isNT()) { + sa.nLength = sizeof(sa); + status = alloc_own_security_descriptor_NT(&sa.lpSecurityDescriptor); + cci_check_error(status); + } + } + + if (!status) { + hEvent = CreateEvent(psa, FALSE, FALSE, event_name); + cci_debug_printf(" CreateEvent(... %s) returned hEvent 0x%X", event_name, hEvent); + if (!hEvent) status = GetLastError(); + } + + if (!status) { + +#if 0 + if (SecureClient::IsImp()) { + cci_debug_printf(STARTUP "Token is impersonation token")); + SecureClient::DuplicateImpAsPrimary(hToken); + } + else { + cci_debug_printf(STARTUP "Token is NOT impersonation token")); + } +#endif + +#if 0 + if (hToken) + bRes = CreateProcessAsUser(hToken, + szExe, // app name + NULL, // cmd line + psa, // SA + psa, // SA + FALSE, + CREATE_NEW_PROCESS_GROUP | + //CREATE_NEW_CONSOLE | + NORMAL_PRIORITY_CLASS | + // CREATE_NO_WINDOW | + DETACHED_PROCESS | + 0 + , + NULL, // environment + szDir, // current dir + &si, + &pi); + else +#endif + alloc_cmdline_2_args(szExe, endpoint, "-D", &cmdline); + bRes = CreateProcess( szExe, // app name + NULL, //cmdline, // cmd line is + psa, // SA + psa, // SA + FALSE, + CREATE_NEW_PROCESS_GROUP | + CREATE_NEW_CONSOLE | + NORMAL_PRIORITY_CLASS | + // CREATE_NO_WINDOW | + // DETACHED_PROCESS | /* KPK TODO: was set - restore */ + 0 + , + NULL, // environment + szDir, // current dir + &si, + &pi); + if (!bRes) { + status = GetLastError(); + cci_debug_printf(" CreateProcess returned %d; LastError: %d", bRes, status); + } + cci_debug_printf(" Waiting..."); + } + cci_check_error(status); + + if (!status) { + status = WaitForSingleObject(hEvent, (SECONDS_TO_WAIT)*1000); + status = RpcMgmtIsServerListening(ccs_request_IfHandle); + } + } + else if (status) { + cci_debug_printf(" unexpected error while looking for server: 0D%d / 0U%u / 0X%X", status, status, status); + } + +#if 0 + if (hToken) + CloseHandle(hToken); +#endif + if (szDir) free_alloc_p(&szDir); + if (szExe) free_alloc_p(&szExe); + if (hEvent) CloseHandle(hEvent); + if (pi.hThread) CloseHandle(pi.hThread); + if (pi.hProcess) CloseHandle(pi.hProcess); + if (sa.lpSecurityDescriptor) free_alloc_p(&sa.lpSecurityDescriptor); + return cci_check_error(status); + +} + +static +DWORD +authenticate_server(Init::InitInfo& info) { + DWORD challenge = 17; // XXX - maybe use random number + DWORD desired_response= challenge + 1; + HANDLE hMap = 0; + LPSTR mem_name = 0; + PDWORD pvalue = 0; + CC_UINT32 response = 0; + SECURITY_ATTRIBUTES sa = { 0 }; + DWORD status = 0; + + cci_debug_printf("%s entry", __FUNCTION__); + + status = alloc_name(&mem_name, "auth", isNT()); + cci_check_error(status); + + if (!status) { + if (isNT()) { + sa.nLength = sizeof(sa); + status = alloc_own_security_descriptor_NT(&sa.lpSecurityDescriptor); + } + } + cci_check_error(status); + + if (!status) { + hMap = CreateFileMapping(INVALID_HANDLE_VALUE, isNT() ? &sa : 0, + PAGE_READWRITE, 0, sizeof(DWORD), mem_name); + if (!hMap) + status = GetLastError(); + } + cci_check_error(status); + + if (!status) { + pvalue = (PDWORD)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0); + if (!pvalue) status = GetLastError(); + } + cci_check_error(status); + + if (!status) { + *pvalue = challenge; + + RpcTryExcept { + response = ccs_authenticate( (CC_CHAR*)mem_name ); + } + RpcExcept(1) { + status = RpcExceptionCode(); + cci_check_error(status); + } + RpcEndExcept; + } + cci_check_error(status); + + if (!status) { + // Check response + if ((response != desired_response) && (*pvalue != desired_response)) { + cci_debug_printf(" Could not authenticate server."); + status = ERROR_ACCESS_DENIED; // XXX - CO_E_NOMATCHINGSIDFOUND? + } + else { + cci_debug_printf(" Server authenticated!"); + } + cci_check_error(status); + } + + free_alloc_p(&mem_name); + free_alloc_p(&sa.lpSecurityDescriptor); + if (pvalue) { + BOOL ok = UnmapViewOfFile(pvalue); +// DEBUG_ASSERT(ok); + } + if (hMap) CloseHandle(hMap); + return status; +} + +DWORD +Client::Disconnect() { + DWORD status = 0; + if (ccs_request_IfHandle) { + /* The calls to the remote procedures are complete. */ + /* Free the binding handle */ + status = RpcBindingFree(&ccs_request_IfHandle); + } + s_init = false; + return status; + } + +DWORD +Client::Connect(char* ep OPTIONAL) { + LPSTR endpoint = 0; + DWORD status = 0; + + if (!ccs_request_IfHandle) { + Init::InitInfo info; + + status = Init::Info(info); + cci_check_error(status); + + if (!status) { + status = bind_client(ep, info, &endpoint); + cci_check_error(status); + } + + if (!status) { + status = find_server(info, endpoint); + cci_check_error(status); + } + + if (!status) { + status = authenticate_server(info); + cci_check_error(status); + } + } + + + if (endpoint && (endpoint != ep)) free_alloc_p(&endpoint); + + if (status) Client::Disconnect(); + return status; + } + +DWORD Client::Initialize(char* ep OPTIONAL) { + CcAutoLock AL(Client::sLock); + SecureClient s; + ccs_request_IfHandle = NULL; + if (s_init) return 0; + DWORD status = Client::Connect(ep); + if (!status) s_init = true; + return status; + } + +DWORD Client::Cleanup() { + CcAutoLock AL(Client::sLock); + SecureClient s; + return Client::Disconnect(); + } + +DWORD Client::Reconnect(char* ep OPTIONAL) { + CcAutoLock AL(Client::sLock); + SecureClient s; + DWORD status = 0; + + if (Initialized()) { + DWORD status = Client::Cleanup(); + } + if ( (!status) ) { + status = Client::Initialize(ep); + } + + return status; + } diff --git a/src/ccapi/lib/win/OldCC/rpc.cxx b/src/ccapi/lib/win/OldCC/rpc.cxx index 332f1c503..29edc3c57 100644 --- a/src/ccapi/lib/win/OldCC/rpc.cxx +++ b/src/ccapi/lib/win/OldCC/rpc.cxx @@ -1,79 +1,79 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#include -#include - -extern "C" { -#include "CredentialsCache.h" -#include "secure.hxx" -#include "client.h" -#include "autolock.hxx" -#include "cci_debugging.h" - } - -extern HANDLE hCCAPIv2Mutex; - -#define MAKE_RPC_CALL(rc, x) \ -do { \ - WaitForSingleObject( hCCAPIv2Mutex, INFINITE ); \ - SecureClient* s = 0; \ - SecureClient::Start(s); \ - CcAutoLock* a = 0; \ - CcAutoLock::Start(a, Client::sLock); \ - RpcTryExcept { \ - cci_debug_printf("RpcTry: #x"); \ - x; \ - } \ - RpcExcept(1) { \ - rc = handle_exception(RpcExceptionCode()); \ - } \ - RpcEndExcept; \ - CcAutoLock::Stop(a); \ - SecureClient::Stop(s); \ - ReleaseMutex( hCCAPIv2Mutex ); \ -} while (0) - -static -DWORD -handle_exception(DWORD code) { - cci_debug_printf("Runtime reported exception %u", code); - if (code == RPC_S_SERVER_UNAVAILABLE) { - Client::Reconnect(0); - } - return 4; - } - -////////////////////////////////////////////////////////////////////////////// - -cc_int32 cc_initialize() { - - CLIENT_INIT_EX(true, 4); - cc_int32 rc = ccNoError; - - MAKE_RPC_CALL(rc, rc = 5); - return rc; +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#include +#include + +extern "C" { +#include "CredentialsCache.h" +#include "secure.hxx" +#include "client.h" +#include "autolock.hxx" +#include "cci_debugging.h" + } + +extern HANDLE hCCAPIv2Mutex; + +#define MAKE_RPC_CALL(rc, x) \ +do { \ + WaitForSingleObject( hCCAPIv2Mutex, INFINITE ); \ + SecureClient* s = 0; \ + SecureClient::Start(s); \ + CcAutoLock* a = 0; \ + CcAutoLock::Start(a, Client::sLock); \ + RpcTryExcept { \ + cci_debug_printf("RpcTry: #x"); \ + x; \ + } \ + RpcExcept(1) { \ + rc = handle_exception(RpcExceptionCode()); \ + } \ + RpcEndExcept; \ + CcAutoLock::Stop(a); \ + SecureClient::Stop(s); \ + ReleaseMutex( hCCAPIv2Mutex ); \ +} while (0) + +static +DWORD +handle_exception(DWORD code) { + cci_debug_printf("Runtime reported exception %u", code); + if (code == RPC_S_SERVER_UNAVAILABLE) { + Client::Reconnect(0); + } + return 4; + } + +////////////////////////////////////////////////////////////////////////////// + +cc_int32 cc_initialize() { + + CLIENT_INIT_EX(true, 4); + cc_int32 rc = ccNoError; + + MAKE_RPC_CALL(rc, rc = 5); + return rc; } \ No newline at end of file diff --git a/src/ccapi/lib/win/ccapi.def b/src/ccapi/lib/win/ccapi.def index 0450331ec..d062e55f5 100644 --- a/src/ccapi/lib/win/ccapi.def +++ b/src/ccapi/lib/win/ccapi.def @@ -1,39 +1,39 @@ -;LIBRARY COMERR32 -HEAPSIZE 8192 - -EXPORTS - cci_debug_printf - - cc_initialize - - cci_string_new - cci_string_d_initializer - ccapi_string_release - - cci_credentials_iterator_new - cci_credentials_iterator_write - - cci_ccache_iterator_new - cci_ccache_iterator_write - - ccapi_ccache_iterator_release - ccapi_ccache_iterator_next - ccapi_ccache_iterator_clone - - ccapi_credentials_iterator_release - ccapi_credentials_iterator_next - ccapi_credentials_iterator_clone - -;debugging: - _cci_check_error - cci_os_ipc - cci_os_ipc_msg - cci_os_ipc_thread_init - cci_stream_data - cci_stream_write - cci_stream_new - - ccs_authenticate - - +;LIBRARY COMERR32 +HEAPSIZE 8192 + +EXPORTS + cci_debug_printf + + cc_initialize + + cci_string_new + cci_string_d_initializer + ccapi_string_release + + cci_credentials_iterator_new + cci_credentials_iterator_write + + cci_ccache_iterator_new + cci_ccache_iterator_write + + ccapi_ccache_iterator_release + ccapi_ccache_iterator_next + ccapi_ccache_iterator_clone + + ccapi_credentials_iterator_release + ccapi_credentials_iterator_next + ccapi_credentials_iterator_clone + +;debugging: + _cci_check_error + cci_os_ipc + cci_os_ipc_msg + cci_os_ipc_thread_init + cci_stream_data + cci_stream_write + cci_stream_new + + ccs_authenticate + + \ No newline at end of file diff --git a/src/ccapi/lib/win/ccapi_os_ipc.cxx b/src/ccapi/lib/win/ccapi_os_ipc.cxx index 7ee917627..770e75b6a 100644 --- a/src/ccapi/lib/win/ccapi_os_ipc.cxx +++ b/src/ccapi/lib/win/ccapi_os_ipc.cxx @@ -1,373 +1,373 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -extern "C" { -#include "k5-thread.h" -#include "ccapi_os_ipc.h" -#include "tls.h" -#include "dllmain.h" -#include "ccs_reply.h" -#include "ccs_request.h" -#include "win-utils.h" -#include "ccutils.h" -#include "util.h" - } - -#include "CredentialsCache.h" -#include "secure.hxx" -#include "opts.hxx" -#include "client.h" -#include "autolock.hxx" -#include "cci_debugging.h" - -#define SECONDS_TO_WAIT 10 -#define CLIENT_REQUEST_RPC_HANDLE ccs_request_IfHandle - -extern HANDLE hCCAPIv2Mutex; -ParseOpts::Opts opts = { 0 }; -PSECURITY_ATTRIBUTES psa = 0; -SECURITY_ATTRIBUTES sa = { 0 }; - -/* The layout of the rest of this module: - - The entrypoints defined in ccs_os_ipc.h: - cci_os_ipc_thread_init - cci_os_ipc - - Other routines needed by those four. - cci_os_connect - handle_exception - */ - -cc_int32 ccapi_connect(const struct tspdata* tsp); -static DWORD handle_exception(DWORD code); - -extern "C" { -cc_int32 cci_os_ipc_msg( cc_int32 in_launch_server, - cci_stream_t in_request_stream, - cc_int32 in_msg, - cci_stream_t* out_reply_stream); - } - -/* ------------------------------------------------------------------------ */ - -extern "C" cc_int32 cci_os_ipc_thread_init (void) { - cc_int32 err = ccNoError; - struct tspdata* ptspdata; - HANDLE replyEvent; - UUID __RPC_FAR uuid; - unsigned char __RPC_FAR* uuidString = NULL; - - if (!GetTspData(&ptspdata)) return ccErrNoMem; - - opts.cMinCalls = 1; - opts.cMaxCalls = 20; - opts.fDontWait = TRUE; - - err = cci_check_error(UuidCreate(&uuid)); // Get a UUID - if (err == RPC_S_OK) { // Convert to string - err = UuidToString(&uuid, &uuidString); - } - if (!err) { // Save in thread local storage - tspdata_setUUID(ptspdata, uuidString); - } - cci_debug_printf("%s UUID:<%s>", __FUNCTION__, tspdata_getUUID(ptspdata)); - - // Initialize old CCAPI if necessary: - if (!err) if (!Init:: Initialized()) err = Init:: Initialize( ); - if (!err) if (!Client::Initialized()) err = Client::Initialize(0); - - if (!err) { - /* Whenever a reply to an RPC request is received, the RPC caller needs to - know when the reply has been received. It does that by waiting for a - client-specific event to be set. Define the event name to be _reply: */ - replyEvent = createThreadEvent((char*)uuidString, REPLY_SUFFIX); - } - - if (replyEvent) tspdata_setReplyEvent(ptspdata, replyEvent); - else err = cci_check_error(GetLastError()); - - if (uuidString) RpcStringFree(&uuidString); - - return cci_check_error(err); - } - - -/* ------------------------------------------------------------------------ */ - -cc_int32 cci_os_ipc (cc_int32 in_launch_server, - cci_stream_t in_request_stream, - cci_stream_t* out_reply_stream) { - return cci_os_ipc_msg( in_launch_server, - in_request_stream, - CCMSG_REQUEST, - out_reply_stream); - } - -extern "C" cc_int32 cci_os_ipc_msg( cc_int32 in_launch_server, - cci_stream_t in_request_stream, - cc_int32 in_msg, - cci_stream_t* out_reply_stream) { - - cc_int32 err = ccNoError; - cc_int32 done = FALSE; - cc_int32 try_count = 0; - cc_int32 server_died = FALSE; - TCHAR* pszStringBinding= NULL; - struct tspdata* ptspdata = NULL; - char* uuid = NULL; - int lenUUID = 0; - unsigned int trycount = 0; - time_t sst = 0; - STARTUPINFO si = { 0 }; - PROCESS_INFORMATION pi = { 0 }; - HANDLE replyEvent = 0; - BOOL bCCAPI_Connected= FALSE; - - if (!in_request_stream) { err = cci_check_error (ccErrBadParam); } - if (!out_reply_stream ) { err = cci_check_error (ccErrBadParam); } - - if (!GetTspData(&ptspdata)) {return ccErrBadParam;} - bCCAPI_Connected = tspdata_getConnected (ptspdata); - replyEvent = tspdata_getReplyEvent (ptspdata); - sst = tspdata_getSST (ptspdata); - uuid = tspdata_getUUID(ptspdata); - - // The lazy connection to the server has been put off as long as possible! - // ccapi_connect starts listening for replies as an RPC server and then - // calls ccs_rpc_connect. - if (!bCCAPI_Connected) { - err = cci_check_error(ccapi_connect(ptspdata)); - bCCAPI_Connected = !err; - tspdata_setConnected(ptspdata, bCCAPI_Connected); - } - - // Clear replyEvent so we can detect when a reply to our request has been received: - ResetEvent(replyEvent); - - //++ Use the old CCAPI implementation to try to talk to the server: - // It has all the code to use the RPC in a thread-safe way, make the endpoint, - // (re)connect and (re)start the server. - // Note: the old implementation wrapped the thread-safety stuff in a macro. - // Here it is expanded and thus duplicated for each RPC call. The new code has - // a very limited number of RPC calls, unlike the older code. - WaitForSingleObject( hCCAPIv2Mutex, INFINITE ); - SecureClient* s = 0; - SecureClient::Start(s); - CcAutoLock* a = 0; - CcAutoLock::Start(a, Client::sLock); - - // Initialize old CCAPI if necessary: - if (!err) if (!Init:: Initialized()) err = cci_check_error(Init:: Initialize( )); - if (!err) if (!Client::Initialized()) err = cci_check_error(Client::Initialize(0)); - - // New code using new RPC procedures for sending the data and receiving a reply: - if (!err) { - RpcTryExcept { - if (!GetTspData(&ptspdata)) {return ccErrBadParam;} - uuid = tspdata_getUUID(ptspdata); - lenUUID = 1 + strlen(uuid); /* 1+ includes terminating \0. */ - cci_debug_printf("%s calling remote ccs_rpc_request tsp*:0x%X", __FUNCTION__, ptspdata); - cci_debug_printf(" rpcmsg:%d; UUID[%d]:<%s> SST:%ld", in_msg, lenUUID, uuid, sst); - - ccs_rpc_request( /* make call with user message: */ - in_msg, /* Message type */ - (unsigned char*)&ptspdata, /* Our tspdata* will be sent back to the reply proc. */ - (unsigned char*)uuid, - cci_stream_size(in_request_stream), - (unsigned char*)cci_stream_data(in_request_stream), /* Data buffer */ - sst, /* session start time */ - (long*)(&err) ); /* Return code */ - } - RpcExcept(1) { - handle_exception(RpcExceptionCode()); - } - RpcEndExcept; - } - - cci_check_error(err); - CcAutoLock::Stop(a); - SecureClient::Stop(s); - ReleaseMutex(hCCAPIv2Mutex); - //-- Use the old CCAPI implementation to try to talk to the server. - - // Wait for reply handler to set event: - if (!err) { - cci_debug_printf(" Waiting for request reply."); - err = cci_check_error(WaitForSingleObject(replyEvent, INFINITE));//(SECONDS_TO_WAIT)*1000)); - cci_debug_printf(" Request reply received!"); - } - - if (!err) { - err = cci_check_error(RpcMgmtIsServerListening(CLIENT_REQUEST_RPC_HANDLE)); - } - - if (!err && server_died) { - err = cci_check_error (ccErrServerUnavailable); - } -#if 0 - if (err == BOOTSTRAP_UNKNOWN_SERVICE && !in_launch_server) { - err = ccNoError; /* If the server is not running just return an empty stream. */ - } -#endif - - if (!err) { - *out_reply_stream = tspdata_getStream(ptspdata); - } - - cci_debug_printf(" payload:<%s>", cci_stream_data(*out_reply_stream)); - - return cci_check_error (err); - } - - - -static DWORD handle_exception(DWORD code) { - cci_debug_printf("%s code %u; ccs_request_IfHandle:0x%X", __FUNCTION__, code, ccs_request_IfHandle); - if ( (code == RPC_S_SERVER_UNAVAILABLE) || (code == RPC_S_INVALID_BINDING) ) { - Client::Reconnect(0); - } - return 4; - } - - -/* Establish a CCAPI connection with the server. - * The connect logic here is identical to the logic in the send request code. - * TODO: merge this connect code with that request code. - */ -cc_int32 ccapi_connect(const struct tspdata* tsp) { - BOOL bListen = TRUE; - char* endpoint = NULL; - HANDLE replyEvent = 0; - RPC_STATUS status = FALSE; - char* uuid = NULL; - - /* Start listening to our uuid before establishing the connection, - * so that when the server tries to call ccapi_listen, we will be ready. - */ - - /* Build complete RPC uuid using previous CCAPI implementation: */ - replyEvent = tspdata_getReplyEvent(tsp); - uuid = tspdata_getUUID(tsp); - endpoint = clientEndpoint(uuid); - cci_debug_printf("%s Registering endpoint %s", __FUNCTION__, endpoint); - - opts.cMinCalls = 1; - opts.cMaxCalls = 20; - opts.fDontWait = TRUE; - - if (!status) { - status = RpcServerUseProtseqEp((RPC_CSTR)"ncalrpc", - opts.cMaxCalls, - (RPC_CSTR)endpoint, - sa.lpSecurityDescriptor); // SD - cci_check_error(status); - } - - if (!status) { - status = RpcServerRegisterAuthInfo(0, // server principal - RPC_C_AUTHN_WINNT, - 0, - 0 ); - cci_check_error(status); - } - - cci_debug_printf("%s is listening ...", __FUNCTION__); - - if (!status) { - if (!isNT()) { - status = RpcServerRegisterIf(ccs_reply_ServerIfHandle, // interface - NULL, // MgrTypeUuid - NULL); // MgrEpv; null means use default - } - else { - status = RpcServerRegisterIfEx(ccs_reply_ServerIfHandle,// interface - NULL, // MgrTypeUuid - NULL, // MgrEpv; 0 means default - RPC_IF_ALLOW_SECURE_ONLY, - opts.cMaxCalls, - NULL); // No security callback. - } - - cci_check_error(status); - - if (!status) { - status = RpcServerListen(opts.cMinCalls, - opts.cMaxCalls, - TRUE); - cci_check_error(status); - } - } - - // Clear replyEvent so we can detect when a reply to our connect request has been received: - ResetEvent(replyEvent); - - // We use the old CCAPI implementation to try to talk to the server. - // It has all the code to make the uuid, (re)connect and (re)start the server. - WaitForSingleObject( hCCAPIv2Mutex, INFINITE ); - SecureClient* s = 0; - SecureClient::Start(s); - CcAutoLock* a = 0; - CcAutoLock::Start(a, Client::sLock); - - // Initialize old CCAPI if necessary: - if (!status) if (!Init:: Initialized()) status = Init:: Initialize( ); - if (!status) if (!Client::Initialized()) status = Client::Initialize(0); - - // New code using new RPC procedures for sending the data and receiving a reply: - if (!status) { - RpcTryExcept { - ccs_rpc_connect( /* make call with user message: */ - CCMSG_CONNECT, /* Message type */ - (unsigned char*)&tsp, /* Our tspdata* will be sent back to the reply proc. */ - (unsigned char*)uuid, - (long*)(&status) ); /* Return code */ - } - RpcExcept(1) { - cci_check_error(RpcExceptionCode()); - status = ccErrBadInternalMessage; - } - RpcEndExcept; - } - - CcAutoLock::Stop(a); - SecureClient::Stop(s); - ReleaseMutex(hCCAPIv2Mutex); - - if (!status) { - cci_debug_printf("%s Waiting for replyEvent.", __FUNCTION__); - status = WaitForSingleObject(replyEvent, INFINITE);//(SECONDS_TO_WAIT)*1000); - status = cci_check_error(RpcMgmtIsServerListening(CLIENT_REQUEST_RPC_HANDLE)); - cci_debug_printf(" Server %sFOUND!", (status) ? "NOT " : ""); - } - if (status) { - cci_debug_printf(" unexpected error while looking for server... (%u)", status); - } - - cci_debug_printf("%s TODO: check connect reply result.", __FUNCTION__); - cci_debug_printf("%s TODO: merge this connect code with that request code.", __FUNCTION__); - return status; +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +extern "C" { +#include "k5-thread.h" +#include "ccapi_os_ipc.h" +#include "tls.h" +#include "dllmain.h" +#include "ccs_reply.h" +#include "ccs_request.h" +#include "win-utils.h" +#include "ccutils.h" +#include "util.h" + } + +#include "CredentialsCache.h" +#include "secure.hxx" +#include "opts.hxx" +#include "client.h" +#include "autolock.hxx" +#include "cci_debugging.h" + +#define SECONDS_TO_WAIT 10 +#define CLIENT_REQUEST_RPC_HANDLE ccs_request_IfHandle + +extern HANDLE hCCAPIv2Mutex; +ParseOpts::Opts opts = { 0 }; +PSECURITY_ATTRIBUTES psa = 0; +SECURITY_ATTRIBUTES sa = { 0 }; + +/* The layout of the rest of this module: + + The entrypoints defined in ccs_os_ipc.h: + cci_os_ipc_thread_init + cci_os_ipc + + Other routines needed by those four. + cci_os_connect + handle_exception + */ + +cc_int32 ccapi_connect(const struct tspdata* tsp); +static DWORD handle_exception(DWORD code); + +extern "C" { +cc_int32 cci_os_ipc_msg( cc_int32 in_launch_server, + cci_stream_t in_request_stream, + cc_int32 in_msg, + cci_stream_t* out_reply_stream); + } + +/* ------------------------------------------------------------------------ */ + +extern "C" cc_int32 cci_os_ipc_thread_init (void) { + cc_int32 err = ccNoError; + struct tspdata* ptspdata; + HANDLE replyEvent; + UUID __RPC_FAR uuid; + unsigned char __RPC_FAR* uuidString = NULL; + + if (!GetTspData(&ptspdata)) return ccErrNoMem; + + opts.cMinCalls = 1; + opts.cMaxCalls = 20; + opts.fDontWait = TRUE; + + err = cci_check_error(UuidCreate(&uuid)); // Get a UUID + if (err == RPC_S_OK) { // Convert to string + err = UuidToString(&uuid, &uuidString); + } + if (!err) { // Save in thread local storage + tspdata_setUUID(ptspdata, uuidString); + } + cci_debug_printf("%s UUID:<%s>", __FUNCTION__, tspdata_getUUID(ptspdata)); + + // Initialize old CCAPI if necessary: + if (!err) if (!Init:: Initialized()) err = Init:: Initialize( ); + if (!err) if (!Client::Initialized()) err = Client::Initialize(0); + + if (!err) { + /* Whenever a reply to an RPC request is received, the RPC caller needs to + know when the reply has been received. It does that by waiting for a + client-specific event to be set. Define the event name to be _reply: */ + replyEvent = createThreadEvent((char*)uuidString, REPLY_SUFFIX); + } + + if (replyEvent) tspdata_setReplyEvent(ptspdata, replyEvent); + else err = cci_check_error(GetLastError()); + + if (uuidString) RpcStringFree(&uuidString); + + return cci_check_error(err); + } + + +/* ------------------------------------------------------------------------ */ + +cc_int32 cci_os_ipc (cc_int32 in_launch_server, + cci_stream_t in_request_stream, + cci_stream_t* out_reply_stream) { + return cci_os_ipc_msg( in_launch_server, + in_request_stream, + CCMSG_REQUEST, + out_reply_stream); + } + +extern "C" cc_int32 cci_os_ipc_msg( cc_int32 in_launch_server, + cci_stream_t in_request_stream, + cc_int32 in_msg, + cci_stream_t* out_reply_stream) { + + cc_int32 err = ccNoError; + cc_int32 done = FALSE; + cc_int32 try_count = 0; + cc_int32 server_died = FALSE; + TCHAR* pszStringBinding= NULL; + struct tspdata* ptspdata = NULL; + char* uuid = NULL; + int lenUUID = 0; + unsigned int trycount = 0; + time_t sst = 0; + STARTUPINFO si = { 0 }; + PROCESS_INFORMATION pi = { 0 }; + HANDLE replyEvent = 0; + BOOL bCCAPI_Connected= FALSE; + + if (!in_request_stream) { err = cci_check_error (ccErrBadParam); } + if (!out_reply_stream ) { err = cci_check_error (ccErrBadParam); } + + if (!GetTspData(&ptspdata)) {return ccErrBadParam;} + bCCAPI_Connected = tspdata_getConnected (ptspdata); + replyEvent = tspdata_getReplyEvent (ptspdata); + sst = tspdata_getSST (ptspdata); + uuid = tspdata_getUUID(ptspdata); + + // The lazy connection to the server has been put off as long as possible! + // ccapi_connect starts listening for replies as an RPC server and then + // calls ccs_rpc_connect. + if (!bCCAPI_Connected) { + err = cci_check_error(ccapi_connect(ptspdata)); + bCCAPI_Connected = !err; + tspdata_setConnected(ptspdata, bCCAPI_Connected); + } + + // Clear replyEvent so we can detect when a reply to our request has been received: + ResetEvent(replyEvent); + + //++ Use the old CCAPI implementation to try to talk to the server: + // It has all the code to use the RPC in a thread-safe way, make the endpoint, + // (re)connect and (re)start the server. + // Note: the old implementation wrapped the thread-safety stuff in a macro. + // Here it is expanded and thus duplicated for each RPC call. The new code has + // a very limited number of RPC calls, unlike the older code. + WaitForSingleObject( hCCAPIv2Mutex, INFINITE ); + SecureClient* s = 0; + SecureClient::Start(s); + CcAutoLock* a = 0; + CcAutoLock::Start(a, Client::sLock); + + // Initialize old CCAPI if necessary: + if (!err) if (!Init:: Initialized()) err = cci_check_error(Init:: Initialize( )); + if (!err) if (!Client::Initialized()) err = cci_check_error(Client::Initialize(0)); + + // New code using new RPC procedures for sending the data and receiving a reply: + if (!err) { + RpcTryExcept { + if (!GetTspData(&ptspdata)) {return ccErrBadParam;} + uuid = tspdata_getUUID(ptspdata); + lenUUID = 1 + strlen(uuid); /* 1+ includes terminating \0. */ + cci_debug_printf("%s calling remote ccs_rpc_request tsp*:0x%X", __FUNCTION__, ptspdata); + cci_debug_printf(" rpcmsg:%d; UUID[%d]:<%s> SST:%ld", in_msg, lenUUID, uuid, sst); + + ccs_rpc_request( /* make call with user message: */ + in_msg, /* Message type */ + (unsigned char*)&ptspdata, /* Our tspdata* will be sent back to the reply proc. */ + (unsigned char*)uuid, + cci_stream_size(in_request_stream), + (unsigned char*)cci_stream_data(in_request_stream), /* Data buffer */ + sst, /* session start time */ + (long*)(&err) ); /* Return code */ + } + RpcExcept(1) { + handle_exception(RpcExceptionCode()); + } + RpcEndExcept; + } + + cci_check_error(err); + CcAutoLock::Stop(a); + SecureClient::Stop(s); + ReleaseMutex(hCCAPIv2Mutex); + //-- Use the old CCAPI implementation to try to talk to the server. + + // Wait for reply handler to set event: + if (!err) { + cci_debug_printf(" Waiting for request reply."); + err = cci_check_error(WaitForSingleObject(replyEvent, INFINITE));//(SECONDS_TO_WAIT)*1000)); + cci_debug_printf(" Request reply received!"); + } + + if (!err) { + err = cci_check_error(RpcMgmtIsServerListening(CLIENT_REQUEST_RPC_HANDLE)); + } + + if (!err && server_died) { + err = cci_check_error (ccErrServerUnavailable); + } +#if 0 + if (err == BOOTSTRAP_UNKNOWN_SERVICE && !in_launch_server) { + err = ccNoError; /* If the server is not running just return an empty stream. */ + } +#endif + + if (!err) { + *out_reply_stream = tspdata_getStream(ptspdata); + } + + cci_debug_printf(" payload:<%s>", cci_stream_data(*out_reply_stream)); + + return cci_check_error (err); + } + + + +static DWORD handle_exception(DWORD code) { + cci_debug_printf("%s code %u; ccs_request_IfHandle:0x%X", __FUNCTION__, code, ccs_request_IfHandle); + if ( (code == RPC_S_SERVER_UNAVAILABLE) || (code == RPC_S_INVALID_BINDING) ) { + Client::Reconnect(0); + } + return 4; + } + + +/* Establish a CCAPI connection with the server. + * The connect logic here is identical to the logic in the send request code. + * TODO: merge this connect code with that request code. + */ +cc_int32 ccapi_connect(const struct tspdata* tsp) { + BOOL bListen = TRUE; + char* endpoint = NULL; + HANDLE replyEvent = 0; + RPC_STATUS status = FALSE; + char* uuid = NULL; + + /* Start listening to our uuid before establishing the connection, + * so that when the server tries to call ccapi_listen, we will be ready. + */ + + /* Build complete RPC uuid using previous CCAPI implementation: */ + replyEvent = tspdata_getReplyEvent(tsp); + uuid = tspdata_getUUID(tsp); + endpoint = clientEndpoint(uuid); + cci_debug_printf("%s Registering endpoint %s", __FUNCTION__, endpoint); + + opts.cMinCalls = 1; + opts.cMaxCalls = 20; + opts.fDontWait = TRUE; + + if (!status) { + status = RpcServerUseProtseqEp((RPC_CSTR)"ncalrpc", + opts.cMaxCalls, + (RPC_CSTR)endpoint, + sa.lpSecurityDescriptor); // SD + cci_check_error(status); + } + + if (!status) { + status = RpcServerRegisterAuthInfo(0, // server principal + RPC_C_AUTHN_WINNT, + 0, + 0 ); + cci_check_error(status); + } + + cci_debug_printf("%s is listening ...", __FUNCTION__); + + if (!status) { + if (!isNT()) { + status = RpcServerRegisterIf(ccs_reply_ServerIfHandle, // interface + NULL, // MgrTypeUuid + NULL); // MgrEpv; null means use default + } + else { + status = RpcServerRegisterIfEx(ccs_reply_ServerIfHandle,// interface + NULL, // MgrTypeUuid + NULL, // MgrEpv; 0 means default + RPC_IF_ALLOW_SECURE_ONLY, + opts.cMaxCalls, + NULL); // No security callback. + } + + cci_check_error(status); + + if (!status) { + status = RpcServerListen(opts.cMinCalls, + opts.cMaxCalls, + TRUE); + cci_check_error(status); + } + } + + // Clear replyEvent so we can detect when a reply to our connect request has been received: + ResetEvent(replyEvent); + + // We use the old CCAPI implementation to try to talk to the server. + // It has all the code to make the uuid, (re)connect and (re)start the server. + WaitForSingleObject( hCCAPIv2Mutex, INFINITE ); + SecureClient* s = 0; + SecureClient::Start(s); + CcAutoLock* a = 0; + CcAutoLock::Start(a, Client::sLock); + + // Initialize old CCAPI if necessary: + if (!status) if (!Init:: Initialized()) status = Init:: Initialize( ); + if (!status) if (!Client::Initialized()) status = Client::Initialize(0); + + // New code using new RPC procedures for sending the data and receiving a reply: + if (!status) { + RpcTryExcept { + ccs_rpc_connect( /* make call with user message: */ + CCMSG_CONNECT, /* Message type */ + (unsigned char*)&tsp, /* Our tspdata* will be sent back to the reply proc. */ + (unsigned char*)uuid, + (long*)(&status) ); /* Return code */ + } + RpcExcept(1) { + cci_check_error(RpcExceptionCode()); + status = ccErrBadInternalMessage; + } + RpcEndExcept; + } + + CcAutoLock::Stop(a); + SecureClient::Stop(s); + ReleaseMutex(hCCAPIv2Mutex); + + if (!status) { + cci_debug_printf("%s Waiting for replyEvent.", __FUNCTION__); + status = WaitForSingleObject(replyEvent, INFINITE);//(SECONDS_TO_WAIT)*1000); + status = cci_check_error(RpcMgmtIsServerListening(CLIENT_REQUEST_RPC_HANDLE)); + cci_debug_printf(" Server %sFOUND!", (status) ? "NOT " : ""); + } + if (status) { + cci_debug_printf(" unexpected error while looking for server... (%u)", status); + } + + cci_debug_printf("%s TODO: check connect reply result.", __FUNCTION__); + cci_debug_printf("%s TODO: merge this connect code with that request code.", __FUNCTION__); + return status; } \ No newline at end of file diff --git a/src/ccapi/lib/win/dllmain.cxx b/src/ccapi/lib/win/dllmain.cxx index 7000e1418..dafbab28c 100644 --- a/src/ccapi/lib/win/dllmain.cxx +++ b/src/ccapi/lib/win/dllmain.cxx @@ -1,279 +1,279 @@ -/* - * $Header$ - * - * Copyright 2008 Massachusetts Institute of Technology. - * All Rights Reserved. - * - * Export of this software from the United States of America may - * require a specific license from the United States Government. - * It is the responsibility of any person or organization contemplating - * export to obtain such a license before exporting. - * - * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and - * distribute this software and its documentation for any purpose and - * without fee is hereby granted, provided that the above copyright - * notice appear in all copies and that both that copyright notice and - * this permission notice appear in supporting documentation, and that - * the name of M.I.T. not be used in advertising or publicity pertaining - * to distribution of the software without specific, written prior - * permission. Furthermore if you modify this software you must label - * your software as modified software and not distribute it in such a - * fashion that it might be confused with the original M.I.T. software. - * M.I.T. makes no representations about the suitability of - * this software for any purpose. It is provided "as is" without express - * or implied warranty. - */ - -#include -#include - -extern "C" { -#include "dllmain.h" -#include "tls.h" -#include "cci_debugging.h" -#include "ccapi_context.h" -#include "client.h" - -//void cci_thread_init__auxinit(); - } - -#define CCAPI_V2_MUTEX_NAME TEXT("MIT_CCAPI_V4_MUTEX") - -// Process-specific data: -static DWORD dwTlsIndex; -static char _user[UNLEN+1]; // Username is used as part of the server and client endpoints. -static HANDLE sessionToken; -static char* ep_prefices[] = {"CCS", "CCAPI"}; -HANDLE hCCAPIv2Mutex = NULL; -DWORD firstThreadID = 0; - -// These data structures are used by the old CCAPI implementation -// to keep track of the state of the RPC connection. All data is static. -static Init init; -static Client client; - -// DllMain() is the entry-point function for this DLL. -BOOL WINAPI DllMain(HINSTANCE hinstDLL, // DLL module handle - DWORD fdwReason, // reason called - LPVOID lpvReserved) { // reserved - - struct tspdata* ptspdata; - BOOL fIgnore; - BOOL bStatus; - DWORD status = 0; // 0 is success. - DWORD maxUN = sizeof(_user); - unsigned int i = 0; - unsigned int j = 0; - - switch (fdwReason) { - // The DLL is loading due to process initialization or a call to LoadLibrary: - case DLL_PROCESS_ATTACH: - cci_debug_printf("%s DLL_PROCESS_ATTACH", __FUNCTION__); - // Process-wide mutex used to allow only one thread at a time into the RPC code: - hCCAPIv2Mutex = CreateMutex(NULL, FALSE, CCAPI_V2_MUTEX_NAME); - - // Figure out our username; it's process-wide: - bStatus = GetUserName(_user, &maxUN); - if (!bStatus) return bStatus; - - // Remove any characters that aren't valid endpoint characters: - while (_user[j] != 0) { - if (isalnum(_user[j])) _user[i++] = _user[j]; - j++; - } - _user[i] = '\0'; - - // Our logon session is determined in client.cxx, old CCAPI code carried - // over to this implementation. - - // Allocate a TLS index: - if ((dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES) return FALSE; - - // Initialize CCAPI once per DLL load: - firstThreadID = GetCurrentThreadId(); - - // Don't break; fallthrough: Initialize the TLS index for first thread. - - // The attached process creates a new thread: - case DLL_THREAD_ATTACH: - // Initialize the TLS index for this thread: - ptspdata = (struct tspdata*) LocalAlloc(LPTR, sizeof(struct tspdata)); - cci_debug_printf("%s DLL_THREAD_ATTACH; tsp*:0x%X", __FUNCTION__, ptspdata); - if (ptspdata == NULL) return FALSE; - fIgnore = TlsSetValue(dwTlsIndex, ptspdata); - - memset(ptspdata, 0, sizeof(struct tspdata)); - - // Initialize CCAPI once per DLL load: - if (GetCurrentThreadId() == firstThreadID) cci_thread_init__auxinit(); - - break; - - // The thread of the attached process terminates: - case DLL_THREAD_DETACH: - cci_debug_printf("%s DLL_THREAD_DETACH", __FUNCTION__); - // Release the allocated memory for this thread: - ptspdata = (struct tspdata*)TlsGetValue(dwTlsIndex); - if (ptspdata != NULL) { - LocalFree((HLOCAL) ptspdata); - TlsSetValue(dwTlsIndex, NULL); - } - break; - - // DLL unload due to process termination or FreeLibrary: - case DLL_PROCESS_DETACH: - cci_debug_printf("%s DLL_PROCESS_DETACH", __FUNCTION__); - //++ Copied from previous implementation: - // Process Teardown "Problem" - // - // There are two problems that occur during process teardown: - // - // 1) Windows (NT/9x/2000) does not keep track of load/unload - // ordering dependencies for use in process teardown. - // - // 2) The RPC exception handling in the RPC calls do not work - // during process shutdown in Win9x. - // - // When a process is being torn down in Windows, the krbcc DLL - // may get a DLL_PROCESS_DETACH before other DLLs are done - // with it. Thus, it may disconnect from the RPC server - // before the last shutdown RPC call. - // - // On NT/2000, this is ok because the RPC call will fail and just - // return an error. - // - // On Win9x/Me, the RPC exception will not be caught. - // However, Win9x ignores exceptions during process shutdown, - // so the exception will never be seen unless a debugger is - // attached to the proccess. - // - // A good potential woraround would be to have a global - // variable that denotes whether the DLL is attached to the - // process. If it is not, all entrypoints into the DLL should - // return failure. - // - // A not as good workaround is below but ifdefed out. - // - // However, we can safely ignore this problem since it can - // only affects people running debuggers under 9x/Me who are - // using multiple DLLs that use this DLL. - // - WaitForSingleObject( hCCAPIv2Mutex, INFINITE ); -#if 0 - bool process_teardown_workaround = false; - if (lpvReserved) { - Init::InitInfo info; - status = Init::Info(info); - if (status) break; - if (!info.isNT) process_teardown_workaround = true; - } - if (process_teardown_workaround) - break; -#endif - // return value is ignored, so we set status for debugging purposes - status = Client::Cleanup(); - status = Init::Cleanup(); - ReleaseMutex( hCCAPIv2Mutex ); - CloseHandle( hCCAPIv2Mutex ); - //-- Copied from previous implementation. - - // Release the allocated memory for this thread: - ptspdata = (struct tspdata*)TlsGetValue(dwTlsIndex); - if (ptspdata != NULL) LocalFree((HLOCAL) ptspdata); - TlsFree(dwTlsIndex); // Release the TLS index. - break; - - default: break; - } - - UNREFERENCED_PARAMETER(hinstDLL); // no whining! - UNREFERENCED_PARAMETER(lpvReserved); - return status ? FALSE : TRUE; -} - - -#ifdef __cplusplus // If used by C++ code, -extern "C" { // we need to export the C interface -#endif - -__declspec(dllexport) -BOOL WINAPI PutTspData(struct tspdata* dw) { - LPVOID lpvData; - struct tspdata** pData; // The stored memory pointer - - // Retrieve a data pointer for the current thread: - lpvData = TlsGetValue(dwTlsIndex); - - // If NULL, allocate memory for the TLS slot for this thread: - if (lpvData == NULL) { - lpvData = (LPVOID) LocalAlloc(LPTR, sizeof(struct tspdata)); - if (lpvData == NULL) return FALSE; - if (!TlsSetValue(dwTlsIndex, lpvData)) return FALSE; - } - - pData = (struct tspdata**) lpvData; // Cast to my data type. - // In this example, it is only a pointer to a DWORD - // but it can be a structure pointer to contain more complicated data. - - (*pData) = dw; - return TRUE; - } - -__declspec(dllexport) -BOOL WINAPI GetTspData(struct tspdata** pdw) { - struct tspdata* pData; // The stored memory pointer - - pData = (struct tspdata*)TlsGetValue(dwTlsIndex); - if (pData == NULL) return FALSE; - (*pdw) = pData; - return TRUE; - } - -#if 0 // replaced by clientEndpoint / serverEndpoint. -__declspec(dllexport) -char* WINAPI getEndpoint(enum EndpointType ep) { - // The server endpoint is of the form CCS_ - // The client endpoint is of the form CCAPI_ - // Each client thread can have its own connection. - // - // NB: Caller must free the data the returned char* points to. - struct tspdata* pData; - char* s; - char* uuid; - unsigned int len; - - switch (ep) { - case EPT_SERVER: - s = (char*)malloc(32); // Length of CCS_ - sprintf(s, "%s_%ld", ep_prefices[EPT_SERVER], sessionToken); - break; - case EPT_CLIENT: - GetTspData(&pData); - uuid = tspdata_getUUID(pData); - len = 4 + strlen(ep_prefices[ep]) + strlen(_user) + strlen(uuid); - s = (char*)malloc(len); - sprintf(s, "%s_%s_%s", ep_prefices[EPT_CLIENT], _user, uuid); - break; - default:; - } - cci_debug_printf("%s(%d) returning %s", __FUNCTION__, ep, s); - - return s; - } -#endif - -#ifdef __cplusplus -} -#endif - -/*********************************************************************/ -/* MIDL allocate and free */ -/*********************************************************************/ - -void __RPC_FAR * __RPC_USER midl_user_allocate(size_t len) { - return(malloc(len)); - } - -void __RPC_USER midl_user_free(void __RPC_FAR * ptr) { - free(ptr); - } +/* + * $Header$ + * + * Copyright 2008 Massachusetts Institute of Technology. + * All Rights Reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#include +#include + +extern "C" { +#include "dllmain.h" +#include "tls.h" +#include "cci_debugging.h" +#include "ccapi_context.h" +#include "client.h" + +//void cci_thread_init__auxinit(); + } + +#define CCAPI_V2_MUTEX_NAME TEXT("MIT_CCAPI_V4_MUTEX") + +// Process-specific data: +static DWORD dwTlsIndex; +static char _user[UNLEN+1]; // Username is used as part of the server and client endpoints. +static HANDLE sessionToken; +static char* ep_prefices[] = {"CCS", "CCAPI"}; +HANDLE hCCAPIv2Mutex = NULL; +DWORD firstThreadID = 0; + +// These data structures are used by the old CCAPI implementation +// to keep track of the state of the RPC connection. All data is static. +static Init init; +static Client client; + +// DllMain() is the entry-point function for this DLL. +BOOL WINAPI DllMain(HINSTANCE hinstDLL, // DLL module handle + DWORD fdwReason, // reason called + LPVOID lpvReserved) { // reserved + + struct tspdata* ptspdata; + BOOL fIgnore; + BOOL bStatus; + DWORD status = 0; // 0 is success. + DWORD maxUN = sizeof(_user); + unsigned int i = 0; + unsigned int j = 0; + + switch (fdwReason) { + // The DLL is loading due to process initialization or a call to LoadLibrary: + case DLL_PROCESS_ATTACH: + cci_debug_printf("%s DLL_PROCESS_ATTACH", __FUNCTION__); + // Process-wide mutex used to allow only one thread at a time into the RPC code: + hCCAPIv2Mutex = CreateMutex(NULL, FALSE, CCAPI_V2_MUTEX_NAME); + + // Figure out our username; it's process-wide: + bStatus = GetUserName(_user, &maxUN); + if (!bStatus) return bStatus; + + // Remove any characters that aren't valid endpoint characters: + while (_user[j] != 0) { + if (isalnum(_user[j])) _user[i++] = _user[j]; + j++; + } + _user[i] = '\0'; + + // Our logon session is determined in client.cxx, old CCAPI code carried + // over to this implementation. + + // Allocate a TLS index: + if ((dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES) return FALSE; + + // Initialize CCAPI once per DLL load: + firstThreadID = GetCurrentThreadId(); + + // Don't break; fallthrough: Initialize the TLS index for first thread. + + // The attached process creates a new thread: + case DLL_THREAD_ATTACH: + // Initialize the TLS index for this thread: + ptspdata = (struct tspdata*) LocalAlloc(LPTR, sizeof(struct tspdata)); + cci_debug_printf("%s DLL_THREAD_ATTACH; tsp*:0x%X", __FUNCTION__, ptspdata); + if (ptspdata == NULL) return FALSE; + fIgnore = TlsSetValue(dwTlsIndex, ptspdata); + + memset(ptspdata, 0, sizeof(struct tspdata)); + + // Initialize CCAPI once per DLL load: + if (GetCurrentThreadId() == firstThreadID) cci_thread_init__auxinit(); + + break; + + // The thread of the attached process terminates: + case DLL_THREAD_DETACH: + cci_debug_printf("%s DLL_THREAD_DETACH", __FUNCTION__); + // Release the allocated memory for this thread: + ptspdata = (struct tspdata*)TlsGetValue(dwTlsIndex); + if (ptspdata != NULL) { + LocalFree((HLOCAL) ptspdata); + TlsSetValue(dwTlsIndex, NULL); + } + break; + + // DLL unload due to process termination or FreeLibrary: + case DLL_PROCESS_DETACH: + cci_debug_printf("%s DLL_PROCESS_DETACH", __FUNCTION__); + //++ Copied from previous implementation: + // Process Teardown "Problem" + // + // There are two problems that occur during process teardown: + // + // 1) Windows (NT/9x/2000) does not keep track of load/unload + // ordering dependencies for use in process teardown. + // + // 2) The RPC exception handling in the RPC calls do not work + // during process shutdown in Win9x. + // + // When a process is being torn down in Windows, the krbcc DLL + // may get a DLL_PROCESS_DETACH before other DLLs are done + // with it. Thus, it may disconnect from the RPC server + // before the last shutdown RPC call. + // + // On NT/2000, this is ok because the RPC call will fail and just + // return an error. + // + // On Win9x/Me, the RPC exception will not be caught. + // However, Win9x ignores exceptions during process shutdown, + // so the exception will never be seen unless a debugger is + // attached to the proccess. + // + // A good potential woraround would be to have a global + // variable that denotes whether the DLL is attached to the + // process. If it is not, all entrypoints into the DLL should + // return failure. + // + // A not as good workaround is below but ifdefed out. + // + // However, we can safely ignore this problem since it can + // only affects people running debuggers under 9x/Me who are + // using multiple DLLs that use this DLL. + // + WaitForSingleObject( hCCAPIv2Mutex, INFINITE ); +#if 0 + bool process_teardown_workaround = false; + if (lpvReserved) { + Init::InitInfo info; + status = Init::Info(info); + if (status) break; + if (!info.isNT) process_teardown_workaround = true; + } + if (process_teardown_workaround) + break; +#endif + // return value is ignored, so we set status for debugging purposes + status = Client::Cleanup(); + status = Init::Cleanup(); + ReleaseMutex( hCCAPIv2Mutex ); + CloseHandle( hCCAPIv2Mutex ); + //-- Copied from previous implementation. + + // Release the allocated memory for this thread: + ptspdata = (struct tspdata*)TlsGetValue(dwTlsIndex); + if (ptspdata != NULL) LocalFree((HLOCAL) ptspdata); + TlsFree(dwTlsIndex); // Release the TLS index. + break; + + default: break; + } + + UNREFERENCED_PARAMETER(hinstDLL); // no whining! + UNREFERENCED_PARAMETER(lpvReserved); + return status ? FALSE : TRUE; +} + + +#ifdef __cplusplus // If used by C++ code, +extern "C" { // we need to export the C interface +#endif + +__declspec(dllexport) +BOOL WINAPI PutTspData(struct tspdata* dw) { + LPVOID lpvData; + struct tspdata** pData; // The stored memory pointer + + // Retrieve a data pointer for the current thread: + lpvData = TlsGetValue(dwTlsIndex); + + // If NULL, allocate memory for the TLS slot for this thread: + if (lpvData == NULL) { + lpvData = (LPVOID) LocalAlloc(LPTR, sizeof(struct tspdata)); + if (lpvData == NULL) return FALSE; + if (!TlsSetValue(dwTlsIndex, lpvData)) return FALSE; + } + + pData = (struct tspdata**) lpvData; // Cast to my data type. + // In this example, it is only a pointer to a DWORD + // but it can be a structure pointer to contain more complicated data. + + (*pData) = dw; + return TRUE; + } + +__declspec(dllexport) +BOOL WINAPI GetTspData(struct tspdata** pdw) { + struct tspdata* pData; // The stored memory pointer + + pData = (struct tspdata*)TlsGetValue(dwTlsIndex); + if (pData == NULL) return FALSE; + (*pdw) = pData; + return TRUE; + } + +#if 0 // replaced by clientEndpoint / serverEndpoint. +__declspec(dllexport) +char* WINAPI getEndpoint(enum EndpointType ep) { + // The server endpoint is of the form CCS_ + // The client endpoint is of the form CCAPI_ + // Each client thread can have its own connection. + // + // NB: Caller must free the data the returned char* points to. + struct tspdata* pData; + char* s; + char* uuid; + unsigned int len; + + switch (ep) { + case EPT_SERVER: + s = (char*)malloc(32); // Length of CCS_ + sprintf(s, "%s_%ld", ep_prefices[EPT_SERVER], sessionToken); + break; + case EPT_CLIENT: + GetTspData(&pData); + uuid = tspdata_getUUID(pData); + len = 4 + strlen(ep_prefices[ep]) + strlen(_user) + strlen(uuid); + s = (char*)malloc(len); + sprintf(s, "%s_%s_%s", ep_prefices[EPT_CLIENT], _user, uuid); + break; + default:; + } + cci_debug_printf("%s(%d) returning %s", __FUNCTION__, ep, s); + + return s; + } +#endif + +#ifdef __cplusplus +} +#endif + +/*********************************************************************/ +/* MIDL allocate and free */ +/*********************************************************************/ + +void __RPC_FAR * __RPC_USER midl_user_allocate(size_t len) { + return(malloc(len)); + } + +void __RPC_USER midl_user_free(void __RPC_FAR * ptr) { + free(ptr); + } diff --git a/src/ccapi/test/Makefile.w32 b/src/ccapi/test/Makefile.w32 index c6e1c535d..8c3da9515 100644 --- a/src/ccapi/test/Makefile.w32 +++ b/src/ccapi/test/Makefile.w32 @@ -1,75 +1,75 @@ -# . is ccapi/test. -CO = ..\common -COWIN = $(CO)\win -LIBDIR = ..\lib -LIBWIN = $(LIBDIR)\win -SRV = ..\server -SRVWIN = ..\server\win - -!include - -INC = -I..\..\include -I..\..\util\et -I$(CO) -I$(COWIN) -I$(LIBDIR) -I$(LIBWIN) - -!if "$(CPU)" == "i386" -cflags = $(cflags) /EHsc /MTd -D_CRTAPI1=_cdecl -D_CRTAPI2=_cdecl -DWINVER=0x0501 -D_WIN32_WINNT=0x0501 \ -$(INC) -!else -cflags = $(cflags) /W3 -D_CRTAPI1= -D_CRTAPI2= $(INC) -!endif -LIBS = $(LIBWIN)\ccapi.lib - -DSTROOT = . -SRC = $(DSTROOT) -#OBJDIR = $(DSTROOT)\obj -OBJDIR = . -OBJEXT = obj -TESTDIR = $(DSTROOT)\tests -TESTEXT = exe -DSTDIR = $(DSTROOT)\ccapi_tests - -PINGOBJS = pingtest.obj -SIMPLEOBJS = simple_lock_test.obj - -comobjs = cci_debugging.obj cci_stream.obj -cowobjs = cci_os_debugging.obj -libobjs = ccs_request_c.obj - -#all: build-base simple_lock_test pingtest -all: build-base pingtest - -# compile base files used by all tests -build-base: $(comobjs) $(libobjs) $(srvobjs) - @echo "Base objects built." - -# rule to compile src files -.c.obj: - $(cc) $(cdebug) $(cflags) /Fo$(OBJDIR)\$(*B).$(OBJEXT) $(SRC)\$(*B).c - -$(comobjs) : $(CO)\$(*B).c - $(cc) $(cdebug) $(cflags) $(CO)\$(*B).c - -$(cowobjs) : $(COWIN)\$(*B).c - $(cc) $(cdebug) $(cflags) $(COWIN)\$(*B).c - -$(libobjs) : $(LIBWIN)\$(*B).c - $(cc) $(cdebug) $(cflags) $(LIBWIN)\$(*B).c - -#$(srvobjs) : $(SRVWIN)\$*.c -# $(cc) $(cdebug) $(cflags) $(SRVWIN)\$*.c - -simple_lock_test: simple_lock_test.obj $(OBJS) - @echo R3+ Build $(*B) in $(TESTDIR) - $(cc) $(cdebug) $(cflags) $(*B).c - $(link) $(linkdebug) $(conflags) -out:$(TESTDIR)\$(*B).exe $(*B).obj \ - $(LIBS) rpcrt4.lib - @echo R3- Built $(*B) in $(TESTDIR) - -pingtest: pingtest.obj - @echo R4+ Build $(*B) in $(TESTDIR) - $(cc) $(cdebug) $(cflags) $(*B).c - $(link) $(linkdebug) $(conflags) -out:$(*B).exe $(PINGOBJS) $(libobjs) $(srvobjs) \ - $(LIBS) rpcrt4.lib - @echo R4- Built $(*B) in $(TESTDIR) - -clean: +# . is ccapi/test. +CO = ..\common +COWIN = $(CO)\win +LIBDIR = ..\lib +LIBWIN = $(LIBDIR)\win +SRV = ..\server +SRVWIN = ..\server\win + +!include + +INC = -I..\..\include -I..\..\util\et -I$(CO) -I$(COWIN) -I$(LIBDIR) -I$(LIBWIN) + +!if "$(CPU)" == "i386" +cflags = $(cflags) /EHsc /MTd -D_CRTAPI1=_cdecl -D_CRTAPI2=_cdecl -DWINVER=0x0501 -D_WIN32_WINNT=0x0501 \ +$(INC) +!else +cflags = $(cflags) /W3 -D_CRTAPI1= -D_CRTAPI2= $(INC) +!endif +LIBS = $(LIBWIN)\ccapi.lib + +DSTROOT = . +SRC = $(DSTROOT) +#OBJDIR = $(DSTROOT)\obj +OBJDIR = . +OBJEXT = obj +TESTDIR = $(DSTROOT)\tests +TESTEXT = exe +DSTDIR = $(DSTROOT)\ccapi_tests + +PINGOBJS = pingtest.obj +SIMPLEOBJS = simple_lock_test.obj + +comobjs = cci_debugging.obj cci_stream.obj +cowobjs = cci_os_debugging.obj +libobjs = ccs_request_c.obj + +#all: build-base simple_lock_test pingtest +all: build-base pingtest + +# compile base files used by all tests +build-base: $(comobjs) $(libobjs) $(srvobjs) + @echo "Base objects built." + +# rule to compile src files +.c.obj: + $(cc) $(cdebug) $(cflags) /Fo$(OBJDIR)\$(*B).$(OBJEXT) $(SRC)\$(*B).c + +$(comobjs) : $(CO)\$(*B).c + $(cc) $(cdebug) $(cflags) $(CO)\$(*B).c + +$(cowobjs) : $(COWIN)\$(*B).c + $(cc) $(cdebug) $(cflags) $(COWIN)\$(*B).c + +$(libobjs) : $(LIBWIN)\$(*B).c + $(cc) $(cdebug) $(cflags) $(LIBWIN)\$(*B).c + +#$(srvobjs) : $(SRVWIN)\$*.c +# $(cc) $(cdebug) $(cflags) $(SRVWIN)\$*.c + +simple_lock_test: simple_lock_test.obj $(OBJS) + @echo R3+ Build $(*B) in $(TESTDIR) + $(cc) $(cdebug) $(cflags) $(*B).c + $(link) $(linkdebug) $(conflags) -out:$(TESTDIR)\$(*B).exe $(*B).obj \ + $(LIBS) rpcrt4.lib + @echo R3- Built $(*B) in $(TESTDIR) + +pingtest: pingtest.obj + @echo R4+ Build $(*B) in $(TESTDIR) + $(cc) $(cdebug) $(cflags) $(*B).c + $(link) $(linkdebug) $(conflags) -out:$(*B).exe $(PINGOBJS) $(libobjs) $(srvobjs) \ + $(LIBS) rpcrt4.lib + @echo R4- Built $(*B) in $(TESTDIR) + +clean: DEL *.$(OBJEXT) \ No newline at end of file -- 2.26.2