win32 changes. changed names of binaries. added support for

running as (and installing/installing) a service.  added
support for multiple desktops (NT only, 95 doesn't support
multiple desktops).
This commit is contained in:
crs
2002-06-08 21:48:00 +00:00
parent 5709d8ddef
commit 4b28ffc5b2
36 changed files with 2948 additions and 855 deletions

View File

@@ -152,6 +152,38 @@ void CMSWindowsScreen::getScreenSize(
*h = m_h;
}
HDESK CMSWindowsScreen::openInputDesktop() const
{
return OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, TRUE,
DESKTOP_CREATEWINDOW |
DESKTOP_HOOKCONTROL |
GENERIC_WRITE);
}
CString CMSWindowsScreen::getDesktopName(
HDESK desk) const
{
if (desk == NULL) {
return CString();
}
else {
DWORD size;
GetUserObjectInformation(desk, UOI_NAME, NULL, 0, &size);
TCHAR* name = new TCHAR[size / sizeof(TCHAR) + 1];
GetUserObjectInformation(desk, UOI_NAME, name, size, &size);
CString result(name);
delete[] name;
return result;
}
}
bool CMSWindowsScreen::isCurrentDesktop(
HDESK desk) const
{
return CStringUtil::CaselessCmp::equal(getDesktopName(desk),
getCurrentDesktopName());
}
void CMSWindowsScreen::getEvent(MSG* msg) const
{
// wait for an event in a cancellable way

View File

@@ -18,6 +18,11 @@ public:
static void init(HINSTANCE);
// accessors
// get the application instance handle
static HINSTANCE getInstance();
protected:
// runs an event loop and returns when WM_QUIT is received
void doRun();
@@ -35,9 +40,7 @@ protected:
// is closed.
void closeDisplay();
// get the application instance handle and the registered window
// class atom
static HINSTANCE getInstance();
// get the registered window class atom
ATOM getClass() const;
// update screen size cache
@@ -46,6 +49,17 @@ protected:
// get the size of the screen
void getScreenSize(SInt32* w, SInt32* h) const;
// get the input desktop. caller must CloseDesktop() the result.
// do not call under windows 95/98/me.
HDESK openInputDesktop() const;
// get the desktop's name. do not call under windows 95/98/me.
CString getDesktopName(HDESK) const;
// returns true iff desk is the current desk. do not call under
// windows 95/98/me.
bool isCurrentDesktop(HDESK desk) const;
// wait for and get the next message. cancellable.
void getEvent(MSG*) const;
@@ -62,6 +76,9 @@ protected:
// called by closeDisplay() to
virtual void onCloseDisplay() = 0;
// called by isCurrentDesktop() to get the current desktop name
virtual CString getCurrentDesktopName() const = 0;
private:
static LRESULT CALLBACK wndProc(HWND, UINT, WPARAM, LPARAM);

View File

@@ -5,9 +5,11 @@
#include <pwd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <syslog.h>
//
// CUnixPlatform
//
@@ -22,26 +24,31 @@ CUnixPlatform::~CUnixPlatform()
// do nothing
}
bool CUnixPlatform::installDaemon(/* FIXME */)
bool CUnixPlatform::installDaemon(
const char*,
const char*,
const char*,
const char*)
{
// daemons don't require special installation
return true;
}
bool CUnixPlatform::uninstallDaemon(/* FIXME */)
bool CUnixPlatform::uninstallDaemon(const char*)
{
// daemons don't require special installation
return true;
}
bool CUnixPlatform::daemonize(const char* name)
int CUnixPlatform::daemonize(
const char* name, DaemonFunc func)
{
// fork so shell thinks we're done and so we're not a process
// group leader
switch (fork()) {
case -1:
// failed
return false;
return -1;
case 0:
// child
@@ -75,7 +82,44 @@ bool CUnixPlatform::daemonize(const char* name)
// hook up logger
setDaemonLogger(name);
return true;
// invoke function
return func(this, 1, &name);
}
int CUnixPlatform::restart(
RestartFunc func, int minErrorCode)
{
for (;;) {
switch (fork()) {
default: {
// parent process. wait for child to exit.
int status;
if (wait(&status) == -1) {
// wait failed. this is unexpected so bail.
log((CLOG_CRIT "wait() failed"));
return minErrorCode;
}
// what happened? if the child exited normally with a
// status less than 16 then the child was deliberately
// terminated so we also terminate. otherwise, we
// loop.
if (WIFEXITED(status) && WEXITSTATUS(status) < minErrorCode) {
return WEXITSTATUS(status);
}
break;
}
case -1:
// fork() failed. log the error and proceed as a child
log((CLOG_WARN "fork() failed; cannot automatically restart on error"));
// fall through
case 0:
// child process
return func();
}
}
}
const char* CUnixPlatform::getBasename(const char* pathname) const
@@ -117,7 +161,9 @@ CString CUnixPlatform::addPathComponent(
CString path;
path.reserve(prefix.size() + 1 + suffix.size());
path += prefix;
path += '/';
if (path.size() == 0 || path[path.size() - 1] != '/') {
path += '/';
}
path += suffix;
return path;
}
@@ -128,7 +174,7 @@ void CUnixPlatform::setDaemonLogger(const char* name)
CLog::setOutputter(&CUnixPlatform::deamonLogger);
}
void CUnixPlatform::deamonLogger(
bool CUnixPlatform::deamonLogger(
int priority, const char* msg)
{
// convert priority
@@ -157,4 +203,5 @@ void CUnixPlatform::deamonLogger(
// log it
syslog(priority, "%s", msg);
return true;
}

View File

@@ -9,9 +9,13 @@ public:
virtual ~CUnixPlatform();
// IPlatform overrides
virtual bool installDaemon(/* FIXME */);
virtual bool uninstallDaemon(/* FIXME */);
virtual bool daemonize(const char* name);
virtual bool installDaemon(const char* name,
const char* description,
const char* pathname,
const char* commandLine);
virtual bool uninstallDaemon(const char* name);
virtual int daemonize(const char* name, DaemonFunc);
virtual int restart(RestartFunc, int minErrorCode);
virtual const char* getBasename(const char* pathname) const;
virtual CString getUserDirectory() const;
virtual CString getSystemDirectory() const;
@@ -23,7 +27,7 @@ protected:
virtual void setDaemonLogger(const char* name);
private:
static void deamonLogger(int, const char*);
static bool deamonLogger(int, const char*);
};
#endif

View File

@@ -1,12 +1,20 @@
#include "CWin32Platform.h"
#include "CLock.h"
#include "CThread.h"
#include "CLog.h"
#include "stdvector.h"
#include <string.h>
#include <windows.h>
#include <shlobj.h>
#include <tchar.h>
#include <assert.h>
//
// CWin32Platform
//
HANDLE CWin32Platform::s_eventLog = NULL;
CWin32Platform* CWin32Platform::s_daemonPlatform = NULL;
CWin32Platform::CWin32Platform()
{
// do nothing
@@ -17,22 +25,282 @@ CWin32Platform::~CWin32Platform()
// do nothing
}
bool CWin32Platform::installDaemon(/* FIXME */)
bool CWin32Platform::isWindows95Family()
{
// FIXME
return false;
OSVERSIONINFO version;
version.dwOSVersionInfoSize = sizeof(version);
if (GetVersionEx(&version) == 0) {
log((CLOG_WARN "cannot determine OS: %d", GetLastError()));
return true;
}
return (version.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
}
bool CWin32Platform::uninstallDaemon(/* FIXME */)
void CWin32Platform::setStatus(
SERVICE_STATUS_HANDLE handle,
DWORD state)
{
// FIXME
return false;
setStatus(handle, state, 0, 0);
}
bool CWin32Platform::daemonize(const char* name)
void CWin32Platform::setStatus(
SERVICE_STATUS_HANDLE handle,
DWORD state, DWORD step, DWORD waitHint)
{
// FIXME
return false;
SERVICE_STATUS status;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS |
SERVICE_INTERACTIVE_PROCESS;
status.dwCurrentState = state;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_PAUSE_CONTINUE |
SERVICE_ACCEPT_SHUTDOWN;
status.dwWin32ExitCode = NO_ERROR;
status.dwServiceSpecificExitCode = 0;
status.dwCheckPoint = step;
status.dwWaitHint = waitHint;
SetServiceStatus(handle, &status);
}
void CWin32Platform::setStatusError(
SERVICE_STATUS_HANDLE handle,
DWORD error)
{
SERVICE_STATUS status;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS |
SERVICE_INTERACTIVE_PROCESS;
status.dwCurrentState = SERVICE_STOPPED;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_PAUSE_CONTINUE |
SERVICE_ACCEPT_SHUTDOWN;
status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
status.dwServiceSpecificExitCode = error;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
SetServiceStatus(handle, &status);
}
bool CWin32Platform::installDaemon(
const char* name,
const char* description,
const char* pathname,
const char* commandLine)
{
// windows 95 family services
if (isWindows95Family()) {
// open registry
HKEY key = open95ServicesKey();
if (key == NULL) {
log((CLOG_ERR "cannot open RunServices registry key", GetLastError()));
return false;
}
// construct entry
CString value;
value += "\"";
value += pathname;
value += "\" ";
value += commandLine;
// install entry
setValue(key, name, value);
// clean up
closeKey(key);
return true;
}
// windows NT family services
else {
// open service manager
SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_WRITE);
if (mgr == NULL) {
log((CLOG_ERR "OpenSCManager failed with %d", GetLastError()));
return false;
}
// create the servie
SC_HANDLE service = CreateService(mgr,
name,
name,
0,
SERVICE_WIN32_OWN_PROCESS |
SERVICE_INTERACTIVE_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
pathname,
NULL,
NULL,
NULL,
NULL,
NULL);
// done with service and manager
if (service != NULL) {
CloseServiceHandle(service);
CloseServiceHandle(mgr);
}
else {
log((CLOG_ERR "CreateService failed with %d", GetLastError()));
CloseServiceHandle(mgr);
return false;
}
// open the registry key for this service
HKEY key = openNTServicesKey();
key = openKey(key, name);
if (key == NULL) {
// can't open key
uninstallDaemon(name);
return false;
}
// set the description
setValue(key, "Description", description);
// set command line
key = openKey(key, "Parameters");
if (key == NULL) {
// can't open key
uninstallDaemon(name);
return false;
}
setValue(key, "CommandLine", commandLine);
// done with registry
closeKey(key);
return true;
}
}
bool CWin32Platform::uninstallDaemon(const char* name)
{
// windows 95 family services
if (isWindows95Family()) {
// open registry
HKEY key = open95ServicesKey();
if (key == NULL) {
log((CLOG_ERR "cannot open RunServices registry key", GetLastError()));
return false;
}
// remove entry
deleteValue(key, name);
// clean up
closeKey(key);
return true;
}
// windows NT family services
else {
// remove parameters for this service
HKEY key = openNTServicesKey();
key = openKey(key, name);
if (key != NULL) {
deleteKey(key, "Parameters");
closeKey(key);
}
// open service manager
SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_WRITE);
if (mgr == NULL) {
log((CLOG_ERR "OpenSCManager failed with %d", GetLastError()));
return false;
}
// open the service. oddly, you must open a service to delete it.
bool success;
SC_HANDLE service = OpenService(mgr, name, DELETE);
if (service == NULL) {
log((CLOG_ERR "OpenService failed with %d", GetLastError()));
success = false;
}
else {
success = (DeleteService(service) != 0);
CloseServiceHandle(service);
}
// close the manager
CloseServiceHandle(mgr);
return success;
}
}
int CWin32Platform::daemonize(
const char* name,
DaemonFunc func)
{
assert(name != NULL);
assert(func != NULL);
// windows 95 family services
if (isWindows95Family()) {
typedef DWORD (WINAPI *RegisterServiceProcessT)(DWORD, DWORD);
// mark this process as a service so it's not killed when the
// user logs off.
HINSTANCE kernel = LoadLibrary("kernel32.dll");
if (kernel == NULL) {
log((CLOG_ERR "LoadLibrary failed with %d", GetLastError()));
return -1;
}
RegisterServiceProcessT RegisterServiceProcess =
reinterpret_cast<RegisterServiceProcessT>(
GetProcAddress(kernel,
_T("RegisterServiceProcess")));
if (RegisterServiceProcess == NULL) {
log((CLOG_ERR "can't lookup RegisterServiceProcess: %d", GetLastError()));
FreeLibrary(kernel);
return -1;
}
if (RegisterServiceProcess(NULL, 1) == 0) {
log((CLOG_ERR "RegisterServiceProcess failed with %d", GetLastError()));
FreeLibrary(kernel);
return -1;
}
FreeLibrary(kernel);
// now simply call the daemon function
return func(this, 1, &name);
}
// windows NT family services
else {
// save daemon function
m_daemonFunc = func;
// construct the service entry
SERVICE_TABLE_ENTRY entry[2];
entry[0].lpServiceName = const_cast<char*>(name);
entry[0].lpServiceProc = &CWin32Platform::serviceMainEntry;
entry[1].lpServiceName = NULL;
entry[1].lpServiceProc = NULL;
// hook us up to the service control manager. this won't return
// (if successful) until the processes have terminated.
s_daemonPlatform = this;
if (StartServiceCtrlDispatcher(entry)) {
s_daemonPlatform = NULL;
return m_daemonResult;
}
log((CLOG_ERR "StartServiceCtrlDispatcher failed with %d", GetLastError()));
s_daemonPlatform = NULL;
return -1;
}
}
int CWin32Platform::restart(
RestartFunc func, int /*minErrorCode*/)
{
// FIXME -- start in separate process or thread. note that this
// isn't too critical as win32 doesn't force us to terminate for
// any reason so we should never have to restart.
return func();
}
const char* CWin32Platform::getBasename(const char* pathname) const
@@ -61,14 +329,58 @@ const char* CWin32Platform::getBasename(const char* pathname) const
CString CWin32Platform::getUserDirectory() const
{
// FIXME
return CString();
// try %HOMEPATH%
TCHAR dir[MAX_PATH];
DWORD size = sizeof(dir) / sizeof(TCHAR);
DWORD result = GetEnvironmentVariable(_T("HOMEPATH"), dir, size);
if (result != 0 && result <= size) {
// sanity check -- if dir doesn't appear to start with a
// drive letter and isn't a UNC name then don't use it
// FIXME -- allow UNC names
if (dir[0] != '\0' && (dir[1] == ':' ||
((dir[0] == '\\' || dir[0] == '/') &&
(dir[1] == '\\' || dir[1] == '/')))) {
return dir;
}
}
// get the location of the personal files. that's as close to
// a home directory as we're likely to find.
ITEMIDLIST* idl;
if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL, &idl))) {
TCHAR* path = NULL;
if (SHGetPathFromIDList(idl, dir)) {
DWORD attr = GetFileAttributes(dir);
if (attr != 0xffffffff && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
path = dir;
}
IMalloc* shalloc;
if (SUCCEEDED(SHGetMalloc(&shalloc))) {
shalloc->Free(idl);
shalloc->Release();
}
if (path != NULL) {
return path;
}
}
// use root of C drive as a default
return "C:";
}
CString CWin32Platform::getSystemDirectory() const
{
// FIXME
return "";
// get windows directory
char dir[MAX_PATH];
if (GetWindowsDirectory(dir, sizeof(dir)) != 0) {
return dir;
}
else {
// can't get it. use C:\ as a default.
return "C:";
}
}
CString CWin32Platform::addPathComponent(
@@ -78,13 +390,453 @@ CString CWin32Platform::addPathComponent(
CString path;
path.reserve(prefix.size() + 1 + suffix.size());
path += prefix;
path += '\\';
if (path.size() == 0 ||
(path[path.size() - 1] != '\\' &&
path[path.size() - 1] != '/')) {
path += '\\';
}
path += suffix;
return path;
}
void CWin32Platform::serviceLogger(
HKEY CWin32Platform::openKey(
HKEY key, const char* keyName)
{
// open next key
HKEY newKey;
LONG result = RegOpenKeyEx(key, keyName, 0,
KEY_WRITE | KEY_QUERY_VALUE, &newKey);
if (result != ERROR_SUCCESS) {
DWORD disp;
result = RegCreateKeyEx(key, keyName, 0, _T(""),
0, KEY_WRITE | KEY_QUERY_VALUE,
NULL, &newKey, &disp);
}
if (result != ERROR_SUCCESS) {
RegCloseKey(key);
return NULL;
}
// switch to new key
RegCloseKey(key);
return newKey;
}
HKEY CWin32Platform::openKey(
HKEY key, const char** keyNames)
{
for (UInt32 i = 0; key != NULL && keyNames[i] != NULL; ++i) {
// open next key
key = openKey(key, keyNames[i]);
}
return key;
}
void CWin32Platform::closeKey(HKEY key)
{
assert(key != NULL);
RegCloseKey(key);
}
void CWin32Platform::deleteKey(HKEY key, const char* name)
{
assert(key != NULL);
assert(name != NULL);
RegDeleteKey(key, name);
}
void CWin32Platform::deleteValue(HKEY key, const char* name)
{
assert(key != NULL);
assert(name != NULL);
RegDeleteValue(key, name);
}
void CWin32Platform::setValue(HKEY key,
const char* name, const CString& value)
{
assert(key != NULL);
assert(name != NULL);
RegSetValueEx(key, name, 0, REG_SZ,
reinterpret_cast<const BYTE*>(value.c_str()),
value.size() + 1);
}
CString CWin32Platform::readValueString(HKEY key,
const char* name)
{
// get the size of the string
DWORD type;
DWORD size = 0;
LONG result = RegQueryValueEx(key, name, 0, &type, NULL, &size);
if (result != ERROR_SUCCESS || type != REG_SZ) {
return CString();
}
// allocate space
char* buffer = new char[size];
// read it
result = RegQueryValueEx(key, name, 0, &type,
reinterpret_cast<BYTE*>(buffer), &size);
if (result != ERROR_SUCCESS || type != REG_SZ) {
delete[] buffer;
return CString();
}
// clean up and return value
CString value(buffer);
delete[] buffer;
return value;
}
HKEY CWin32Platform::openNTServicesKey()
{
static const char* s_keyNames[] = {
_T("SYSTEM"),
_T("CurrentControlSet"),
_T("Services"),
NULL
};
return openKey(HKEY_LOCAL_MACHINE, s_keyNames);
}
HKEY CWin32Platform::open95ServicesKey()
{
static const char* s_keyNames[] = {
_T("Software"),
_T("Microsoft"),
_T("Windows"),
_T("CurrentVersion"),
_T("RunServices"),
NULL
};
return openKey(HKEY_LOCAL_MACHINE, s_keyNames);
}
int CWin32Platform::runDaemon(RunFunc run, StopFunc stop)
{
// should only be called from DaemonFunc
assert(m_serviceMutex != NULL);
CLock lock(m_serviceMutex);
try {
int result;
m_stop = stop;
m_serviceHandlerWaiting = false;
m_serviceRunning = false;
for (;;) {
// mark server as running
setStatus(m_statusHandle, SERVICE_RUNNING);
// run callback
m_serviceRunning = true;
result = run(m_serviceMutex);
m_serviceRunning = false;
// notify handler that the server stopped. if handler
// isn't waiting then we stopped unexpectedly and we
// quit.
if (m_serviceHandlerWaiting) {
m_serviceHandlerWaiting = false;
m_serviceState->broadcast();
}
else {
break;
}
// wait until we're told what to do next
while (*m_serviceState != SERVICE_RUNNING &&
*m_serviceState != SERVICE_STOPPED) {
m_serviceState->wait();
}
// exit loop if we've been told to stop
if (*m_serviceState == SERVICE_STOPPED) {
break;
}
}
// prevent daemonHandler from changing state
*m_serviceState = SERVICE_STOPPED;
// tell service control that the service is stopped.
// FIXME -- hopefully this will ensure that our handler won't
// be called again but i can't find documentation that
// verifies that. if it does it'll crash on the mutex that
// we're about to destroy.
setStatus(m_statusHandle, *m_serviceState);
// clean up
m_stop = NULL;
return result;
}
catch (...) {
// FIXME -- report error
// prevent serviceHandler from changing state
*m_serviceState = SERVICE_STOPPED;
// set status
setStatusError(m_statusHandle, 0);
// wake up serviceHandler if it's waiting then wait for it
if (m_serviceHandlerWaiting) {
m_serviceHandlerWaiting = false;
m_serviceState->broadcast();
m_serviceState->wait();
// serviceHandler has exited by now
}
throw;
}
}
void CWin32Platform::serviceMain(
DWORD argc, LPTSTR* argvIn)
{
typedef std::vector<LPCTSTR> ArgList;
typedef std::vector<CString> Arguments;
const char** argv = const_cast<const char**>(argvIn);
// open event log and direct log messages to it
if (s_eventLog == NULL) {
s_eventLog = RegisterEventSource(NULL, argv[0]);
if (s_eventLog != NULL) {
CLog::setOutputter(&CWin32Platform::serviceLogger);
}
}
// create synchronization objects
CThread::init();
m_serviceMutex = new CMutex;
m_serviceState = new CCondVar<DWORD>(m_serviceMutex, SERVICE_RUNNING);
// register our service handler functiom
m_statusHandle = RegisterServiceCtrlHandler(argv[0],
&CWin32Platform::serviceHandlerEntry);
if (m_statusHandle == NULL) {
// cannot start as service
m_daemonResult = -1;
delete m_serviceState;
delete m_serviceMutex;
return;
}
// tell service control manager that we're starting
setStatus(m_statusHandle, SERVICE_START_PENDING, 0, 1000);
// if no arguments supplied then try getting them from the registry.
// the first argument doesn't count because it's the service name.
Arguments args;
ArgList myArgv;
if (argc <= 1) {
// read command line
CString commandLine;
HKEY key = openNTServicesKey();
key = openKey(key, argv[0]);
key = openKey(key, "Parameters");
if (key != NULL) {
commandLine = readValueString(key, "CommandLine");
}
// if the command line isn't empty then parse and use it
if (!commandLine.empty()) {
// parse, honoring double quoted substrings
CString::size_type i = commandLine.find_first_not_of(" \t");
while (i != CString::npos && i != commandLine.size()) {
// find end of string
CString::size_type e;
if (commandLine[i] == '\"') {
// quoted. find closing quote.
++i;
e = commandLine.find("\"", i);
// whitespace must follow closing quote
if (e == CString::npos ||
(e + 1 != commandLine.size() &&
commandLine[e + 1] != ' ' &&
commandLine[e + 1] != '\t')) {
args.clear();
break;
}
// extract
args.push_back(commandLine.substr(i, e - i));
i = e + 1;
}
else {
// unquoted. find next whitespace.
e = commandLine.find_first_of(" \t", i);
if (e == CString::npos) {
e = commandLine.size();
}
// extract
args.push_back(commandLine.substr(i, e - i));
i = e + 1;
}
// next argument
i = commandLine.find_first_not_of(" \t", i);
}
// service name goes first
myArgv.push_back(argv[0]);
// get pointers
for (UInt32 i = 0; i < args.size(); ++i) {
myArgv.push_back(args[i].c_str());
}
// adjust argc/argv
argc = myArgv.size();
argv = &myArgv[0];
}
}
try {
// invoke daemon function
m_daemonResult = m_daemonFunc(this, static_cast<int>(argc), argv);
}
catch (CDaemonFailed& e) {
setStatusError(m_statusHandle, e.m_result);
m_daemonResult = -1;
}
catch (...) {
setStatusError(m_statusHandle, 1);
m_daemonResult = -1;
}
// clean up
delete m_serviceState;
delete m_serviceMutex;
// FIXME -- close event log?
}
void WINAPI CWin32Platform::serviceMainEntry(
DWORD argc, LPTSTR* argv)
{
s_daemonPlatform->serviceMain(argc, argv);
}
void CWin32Platform::serviceHandler(DWORD ctrl)
{
assert(m_serviceMutex != NULL);
assert(m_serviceState != NULL);
CLock lock(m_serviceMutex);
// ignore request if service is already stopped
if (*m_serviceState == SERVICE_STOPPED) {
setStatus(m_statusHandle, *m_serviceState);
return;
}
switch (ctrl) {
case SERVICE_CONTROL_PAUSE:
// update state
*m_serviceState = SERVICE_PAUSE_PENDING;
setStatus(m_statusHandle, *m_serviceState, 0, 1000);
// stop run callback if running and wait for it to finish
if (m_serviceRunning) {
m_serviceHandlerWaiting = true;
m_stop();
m_serviceState->wait();
}
// update state if service hasn't stopped while we were waiting
if (*m_serviceState != SERVICE_STOPPED) {
*m_serviceState = SERVICE_PAUSED;
}
m_serviceState->broadcast();
break;
case SERVICE_CONTROL_CONTINUE:
// required status update
setStatus(m_statusHandle, *m_serviceState);
// update state but let main loop send RUNNING notification
*m_serviceState = SERVICE_RUNNING;
m_serviceState->broadcast();
return;
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
// update state
*m_serviceState = SERVICE_STOP_PENDING;
setStatus(m_statusHandle, *m_serviceState, 0, 1000);
// stop run callback if running and wait for it to finish
if (m_serviceRunning) {
m_serviceHandlerWaiting = true;
m_stop();
m_serviceState->wait();
}
// update state
*m_serviceState = SERVICE_STOPPED;
m_serviceState->broadcast();
break;
default:
log((CLOG_WARN "unknown service command: %d", ctrl));
// fall through
case SERVICE_CONTROL_INTERROGATE:
break;
}
// send update
setStatus(m_statusHandle, *m_serviceState);
}
void WINAPI CWin32Platform::serviceHandlerEntry(DWORD ctrl)
{
s_daemonPlatform->serviceHandler(ctrl);
}
bool CWin32Platform::serviceLogger(
int priority, const char* msg)
{
// FIXME
if (s_eventLog == NULL) {
return false;
}
// convert priority
WORD type;
switch (priority) {
case CLog::kFATAL:
case CLog::kERROR:
type = EVENTLOG_ERROR_TYPE;
break;
case CLog::kWARNING:
type = EVENTLOG_WARNING_TYPE;
break;
default:
type = EVENTLOG_INFORMATION_TYPE;
break;
}
// log it
// FIXME -- win32 wants to use a message table to look up event
// strings. log messages aren't organized that way so we'll
// just dump our string into the raw data section of the event
// so users can at least see the message. note that we use our
// priority as the event category.
ReportEvent(s_eventLog, type, static_cast<WORD>(priority),
0, // event ID
NULL,
0,
strlen(msg + 1), // raw data size
NULL,
const_cast<char*>(msg));// raw data
return true;
}

View File

@@ -2,16 +2,52 @@
#define CWIN32PLATFORM_H
#include "IPlatform.h"
#include "CCondVar.h"
#include "CMutex.h"
#include <windows.h>
class CWin32Platform : public IPlatform {
public:
typedef int (*RunFunc)(CMutex*);
typedef void (*StopFunc)(void);
CWin32Platform();
virtual ~CWin32Platform();
// returns true iff the platform is win95/98/me
static bool isWindows95Family();
// utility for calling SetServiceStatus()
static void setStatus(SERVICE_STATUS_HANDLE, DWORD state);
static void setStatus(SERVICE_STATUS_HANDLE,
DWORD state, DWORD step, DWORD waitHint);
static void setStatusError(SERVICE_STATUS_HANDLE, DWORD error);
// run a service. the RunFunc should unlock the passed in mutex
// (which will be locked on entry) when not initializing or
// shutting down (i.e. when running its loop). StopFunc should
// cause the RunFunc() to return. returns what RunFunc returns.
// RunFunc should throw CDaemonFailed if the service fails.
int runDaemon(RunFunc, StopFunc);
// thrown by RunFunc on service failure. result is the error
// code reported by the service.
class CDaemonFailed {
public:
CDaemonFailed(int result) : m_result(result) { }
public:
int m_result;
};
// IPlatform overrides
virtual bool installDaemon(/* FIXME */);
virtual bool uninstallDaemon(/* FIXME */);
virtual bool daemonize(const char* name);
virtual bool installDaemon(const char* name,
const char* description,
const char* pathname,
const char* commandLine);
virtual bool uninstallDaemon(const char* name);
virtual int daemonize(const char* name, DaemonFunc);
virtual int restart(RestartFunc, int minErrorCode);
virtual const char* getBasename(const char* pathname) const;
virtual CString getUserDirectory() const;
virtual CString getSystemDirectory() const;
@@ -20,7 +56,40 @@ public:
const CString& suffix) const;
private:
static void serviceLogger(int, const char*);
static HKEY openKey(HKEY parent, const char*);
static HKEY openKey(HKEY parent, const char**);
static void closeKey(HKEY);
static void deleteKey(HKEY, const char* name);
static void deleteValue(HKEY, const char* name);
static void setValue(HKEY, const char* name,
const CString& value);
static CString readValueString(HKEY, const char* name);
static HKEY openNTServicesKey();
static HKEY open95ServicesKey();
void serviceMain(DWORD, LPTSTR*);
static void WINAPI serviceMainEntry(DWORD, LPTSTR*);
void serviceHandler(DWORD ctrl);
static void WINAPI serviceHandlerEntry(DWORD ctrl);
static bool serviceLogger(int, const char*);
private:
DaemonFunc m_daemonFunc;
int m_daemonResult;
SERVICE_STATUS_HANDLE m_statusHandle;
CMutex* m_serviceMutex;
CCondVar<DWORD>* m_serviceState;
bool m_serviceHandlerWaiting;
bool m_serviceRunning;
StopFunc m_stop;
static HANDLE s_eventLog;
static CWin32Platform* s_daemonPlatform;
};
#endif

View File

@@ -7,19 +7,48 @@
class IPlatform : public IInterface {
public:
typedef int (*DaemonFunc)(IPlatform*, int argc, const char** argv);
typedef int (*RestartFunc)();
// manipulators
// install/uninstall a daemon.
// install/uninstall a daemon. commandLine should *not*
// include the name of program as the first argument.
// FIXME -- throw on error? will get better error messages that way.
virtual bool installDaemon(/* FIXME */) = 0;
virtual bool uninstallDaemon(/* FIXME */) = 0;
virtual bool installDaemon(const char* name,
const char* description,
const char* pathname,
const char* commandLine) = 0;
virtual bool uninstallDaemon(const char* name) = 0;
// daemonize. this should have the side effect of sending log
// messages to a system message logger since messages can no
// longer go to the console. returns true iff successful.
// the name is the name of the daemon.
// FIXME -- win32 services will require a more complex interface
virtual bool daemonize(const char* name) = 0;
// daemonize. this should have the side effect of sending log
// messages to a system message logger since messages can no
// longer go to the console. name is the name of the daemon.
// once daemonized, func is invoked and daemonize returns when
// and what func does. daemonize() returns -1 on error.
//
// exactly what happens when daemonizing depends on the platform.
// unix:
// detaches from terminal. func gets one argument, the name
// passed to daemonize().
// win32:
// becomes a service. argument 0 is the name of the service
// and the rest are the arguments passed to StartService().
// func is only called when the service is actually started.
// func must behave like a proper ServiceMain() function; in
// particular, it must call RegisterServiceCtrlHandler() and
// SetServiceStatus().
virtual int daemonize(const char* name, DaemonFunc func) = 0;
// continually restart the given function in a separate process
// or thread until it exits normally with a code less than the
// given code then return the code.
virtual int restart(RestartFunc, int minErrorCode) = 0;
// accessors

139
platform/platform.dsp Normal file
View File

@@ -0,0 +1,139 @@
# Microsoft Developer Studio Project File - Name="platform" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Static Library" 0x0104
CFG=platform - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "platform.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "platform.mak" CFG="platform - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "platform - Win32 Release" (based on "Win32 (x86) Static Library")
!MESSAGE "platform - Win32 Debug" (based on "Win32 (x86) Static Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "platform - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
# ADD CPP /nologo /MT /W4 /GX /O2 /I "..\base" /I "..\mt" /I "..\synergy" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FD /c
# SUBTRACT CPP /YX
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo
!ELSEIF "$(CFG)" == "platform - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD CPP /nologo /MTd /W4 /Gm /GX /ZI /Od /I "..\base" /I "..\mt" /I "..\synergy" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FD /GZ /c
# SUBTRACT CPP /YX
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo
!ENDIF
# Begin Target
# Name "platform - Win32 Release"
# Name "platform - Win32 Debug"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=.\CMSWindowsClipboard.cpp
# End Source File
# Begin Source File
SOURCE=.\CMSWindowsScreen.cpp
# End Source File
# Begin Source File
SOURCE=.\CPlatform.cpp
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=.\CMSWindowsClipboard.h
# End Source File
# Begin Source File
SOURCE=.\CMSWindowsScreen.h
# End Source File
# Begin Source File
SOURCE=.\CPlatform.h
# End Source File
# Begin Source File
SOURCE=.\CWin32Platform.h
# End Source File
# Begin Source File
SOURCE=.\IPlatform.h
# End Source File
# End Group
# Begin Group "Resource Files"
# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
# End Group
# Begin Group "Included Files"
# PROP Default_Filter "inc"
# Begin Source File
SOURCE=.\CWin32Platform.cpp
# PROP Exclude_From_Build 1
# End Source File
# End Group
# End Target
# End Project