From 788d0135df29f77a6aedc4973e17017784721769 Mon Sep 17 00:00:00 2001 From: Eli de Faria Junior Date: Mon, 18 Aug 2014 11:43:29 -0300 Subject: [PATCH] Primeiros passos para o cacic daemon. --- cacic-teste/cacic-teste.pro | 13 +++++++++++-- cacic-teste/testcacic.cpp | 2 +- cacic/cacic.pro | 34 ---------------------------------- cacic/main.cpp | 8 -------- cacicD/cacicD.pro | 38 ++++++++++++++++++++++++++++++++++++++ cacicD/cacicd.cpp | 5 +++++ cacicD/cacicd.h | 10 ++++++++++ cacicD/main.cpp | 25 +++++++++++++++++++++++++ src/cacic_computer.h | 2 +- src/ccacic.h | 6 +++--- src/ccoleta.h | 2 +- src/operatingsystem.h | 4 ++-- src/qtservice/src/qtservice.cpp | 1112 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/qtservice/src/qtservice.h | 192 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/qtservice/src/qtservice_p.h | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/qtservice/src/qtservice_unix.cpp | 474 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/qtservice/src/qtservice_win.cpp | 945 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/qtservice/src/qtunixserversocket.cpp | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/qtservice/src/qtunixserversocket.h | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/qtservice/src/qtunixsocket.cpp | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/qtservice/src/qtunixsocket.h | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 21 files changed, 3193 insertions(+), 52 deletions(-) delete mode 100644 cacic/cacic.pro delete mode 100644 cacic/main.cpp create mode 100644 cacicD/cacicD.pro create mode 100644 cacicD/cacicd.cpp create mode 100644 cacicD/cacicd.h create mode 100644 cacicD/main.cpp create mode 100644 src/qtservice/src/qtservice.cpp create mode 100644 src/qtservice/src/qtservice.h create mode 100644 src/qtservice/src/qtservice_p.h create mode 100644 src/qtservice/src/qtservice_unix.cpp create mode 100644 src/qtservice/src/qtservice_win.cpp create mode 100644 src/qtservice/src/qtunixserversocket.cpp create mode 100644 src/qtservice/src/qtunixserversocket.h create mode 100644 src/qtservice/src/qtunixsocket.cpp create mode 100644 src/qtservice/src/qtunixsocket.h diff --git a/cacic-teste/cacic-teste.pro b/cacic-teste/cacic-teste.pro index 91c45ee..87c677e 100644 --- a/cacic-teste/cacic-teste.pro +++ b/cacic-teste/cacic-teste.pro @@ -21,7 +21,12 @@ SOURCES += \ testcacic.cpp \ ../src/ccacic.cpp \ ../src/cacic_computer.cpp \ - ../src/operatingsystem.cpp + ../src/operatingsystem.cpp \ + ../src/qtservice/src/qtservice.cpp \ + ../src/qtservice/src/qtservice_unix.cpp \ + ../src/qtservice/src/qtservice_win.cpp \ + ../src/qtservice/src/qtunixserversocket.cpp \ + ../src/qtservice/src/qtunixsocket.cpp HEADERS += \ @@ -30,7 +35,11 @@ HEADERS += \ ../src/cacic_computer.h \ ../src/cacic_comm.h \ ../src/console.h \ - ../src/operatingsystem.h + ../src/operatingsystem.h \ + ../src/qtservice/src/qtservice.h \ + ../src/qtservice/src/qtservice_p.h \ + ../src/qtservice/src/qtunixserversocket.h \ + ../src/qtservice/src/qtunixsocket.h INCLUDEPATH += ../src \ ../src/crypto++/include/ diff --git a/cacic-teste/testcacic.cpp b/cacic-teste/testcacic.cpp index 190d343..916dae1 100644 --- a/cacic-teste/testcacic.cpp +++ b/cacic-teste/testcacic.cpp @@ -204,7 +204,7 @@ void CTestCacic::testStartService() #ifdef Q_OS_WIN exitStatus = OCacic.startProcess("../../install-cacic/debug/install-cacic.exe", true, &ok); #else - exitStatus = OCacic.startProcess("../../install-cacic/debug/install-cacic", &ok); + exitStatus = OCacic.startProcess("../../install-cacic/debug/install-cacic", true, &ok); #endif QVERIFY(ok); } diff --git a/cacic/cacic.pro b/cacic/cacic.pro deleted file mode 100644 index e0c8496..0000000 --- a/cacic/cacic.pro +++ /dev/null @@ -1,34 +0,0 @@ -#------------------------------------------------- -# -# Project created by QtCreator 2014-08-13T13:33:32 -# -#------------------------------------------------- - -QT += core -QT -= gui - -TARGET = cacic -CONFIG += console -CONFIG -= app_bundle - -win32 { - LIBS += -LE:\LightBase\cacic-agente-project\cacic-agente\src\crypto++\lib -lcryptopp -} else { - LIBS += -L/usr/lib -lcryptopp -} - -TEMPLATE = app - -SOURCES += \ - main.cpp \ - ../src/ccacic.cpp \ - ../src/cacic_computer.cpp - - -HEADERS += \ - ../src/ccacic.h \ - ../src/cacic_computer.h \ - ../src/cacic_comm.h - -INCLUDEPATH += ../src \ - ../src/crypto++/include/ diff --git a/cacic/main.cpp b/cacic/main.cpp deleted file mode 100644 index 470a030..0000000 --- a/cacic/main.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include - -int main(int argc, char *argv[]) -{ - QCoreApplication a(argc, argv); - - return a.exec(); -} diff --git a/cacicD/cacicD.pro b/cacicD/cacicD.pro new file mode 100644 index 0000000..f52ef61 --- /dev/null +++ b/cacicD/cacicD.pro @@ -0,0 +1,38 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2014-08-18T11:06:08 +# +#------------------------------------------------- + +QT += core + +QT -= gui + +TARGET = cacicD +CONFIG += console +CONFIG -= app_bundle +win32 { + LIBS += -LE:\LightBase\cacic-agente-project\cacic-agente\src\crypto++\lib -lcryptopp +} else { + LIBS += -L/usr/lib -lcryptopp +} +TEMPLATE = app + + +SOURCES += main.cpp \ + ../src/cacic_computer.cpp \ + ../src/ccacic.cpp \ + ../src/ccoleta.cpp \ + ../src/operatingsystem.cpp \ + cacicd.cpp + +HEADERS += \ + ../src/cacic_comm.h \ + ../src/cacic_computer.h \ + ../src/ccacic.h \ + ../src/ccoleta.h \ + ../src/console.h \ + ../src/operatingsystem.h \ + cacicd.h + +include(../src/qtservice/src/qtservice.pri) diff --git a/cacicD/cacicd.cpp b/cacicD/cacicd.cpp new file mode 100644 index 0000000..cbe41b8 --- /dev/null +++ b/cacicD/cacicd.cpp @@ -0,0 +1,5 @@ +#include "cacicd.h" + +cacicD::cacicD() +{ +} diff --git a/cacicD/cacicd.h b/cacicD/cacicd.h new file mode 100644 index 0000000..a9c388f --- /dev/null +++ b/cacicD/cacicd.h @@ -0,0 +1,10 @@ +#ifndef CACICD_H +#define CACICD_H + +class cacicD +{ +public: + cacicD(); +}; + +#endif // CACICD_H diff --git a/cacicD/main.cpp b/cacicD/main.cpp new file mode 100644 index 0000000..dc6550f --- /dev/null +++ b/cacicD/main.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include "../src/qtservice/src/qtservice.h" + +int main(int argc, char **argv) +{ +#if !defined(Q_OS_WIN) + QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath()); + qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData()); +#endif + //int result = processArgs(argc, argv); + if (QString::fromLocal8Bit(argv[argc-1]) == QLatin1String("-w") || + QString::fromLocal8Bit(argv[argc-1]) == QLatin1String("-wait")) { + printf("\nPress Enter to continue..."); + QFile input; + input.open(stdin, QIODevice::ReadOnly); + input.readLine(); + printf("\n"); + } + //return result; +} + + diff --git a/src/cacic_computer.h b/src/cacic_computer.h index 56471bc..06bf21a 100644 --- a/src/cacic_computer.h +++ b/src/cacic_computer.h @@ -7,7 +7,7 @@ #include #include #include -#include +#include "operatingsystem.h" class CACIC_Computer { diff --git a/src/ccacic.h b/src/ccacic.h index 8c7ee1c..57e7fa7 100644 --- a/src/ccacic.h +++ b/src/ccacic.h @@ -11,9 +11,9 @@ #include #include #include -#include -#include -#include +#include "../src/crypto++/include/aes.h" +#include "../src/crypto++/include/base64.h" +#include "../src/crypto++/include/modes.h" //#include //#include //#include diff --git a/src/ccoleta.h b/src/ccoleta.h index 9fa6ef6..f925904 100644 --- a/src/ccoleta.h +++ b/src/ccoleta.h @@ -1,6 +1,6 @@ #ifndef CCOLETA_H #define CCOLETA_H -#include +#include "cacic_computer.h" class CColeta { diff --git a/src/operatingsystem.h b/src/operatingsystem.h index 96ef2e0..d72f047 100644 --- a/src/operatingsystem.h +++ b/src/operatingsystem.h @@ -6,8 +6,8 @@ #include #include -#include -#include +#include "ccacic.h" +#include "console.h" class OperatingSystem { diff --git a/src/qtservice/src/qtservice.cpp b/src/qtservice/src/qtservice.cpp new file mode 100644 index 0000000..5ecaa67 --- /dev/null +++ b/src/qtservice/src/qtservice.cpp @@ -0,0 +1,1112 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qtservice.h" +#include "qtservice_p.h" +#include +#include +#include +#include +#include + +#if defined(QTSERVICE_DEBUG) +#include +#include +#include +#include +#if defined(Q_OS_WIN32) +#include +#else +#include +#include +#endif + +static QFile* f = 0; + +static void qtServiceCloseDebugLog() +{ + if (!f) + return; + QString ps(QTime::currentTime().toString("HH:mm:ss.zzz ") + QLatin1String("--- DEBUG LOG CLOSED ---\n\n")); + f->write(ps.toAscii()); + f->flush(); + f->close(); + delete f; + f = 0; +} + +void qtServiceLogDebug(QtMsgType type, const char* msg) +{ + static QMutex mutex; + QMutexLocker locker(&mutex); + QString s(QTime::currentTime().toString("HH:mm:ss.zzz ")); + s += QString("[%1] ").arg( +#if defined(Q_OS_WIN32) + GetCurrentProcessId()); +#else + getpid()); +#endif + + if (!f) { +#if defined(Q_OS_WIN32) + f = new QFile("c:/service-debuglog.txt"); +#else + f = new QFile("/tmp/service-debuglog.txt"); +#endif + if (!f->open(QIODevice::WriteOnly | QIODevice::Append)) { + delete f; + f = 0; + return; + } + QString ps(QLatin1String("\n") + s + QLatin1String("--- DEBUG LOG OPENED ---\n")); + f->write(ps.toAscii()); + } + + switch (type) { + case QtWarningMsg: + s += QLatin1String("WARNING: "); + break; + case QtCriticalMsg: + s += QLatin1String("CRITICAL: "); + break; + case QtFatalMsg: + s+= QLatin1String("FATAL: "); + break; + case QtDebugMsg: + s += QLatin1String("DEBUG: "); + break; + default: + // Nothing + break; + } + + s += msg; + s += QLatin1String("\n"); + + f->write(s.toAscii()); + f->flush(); + + if (type == QtFatalMsg) { + qtServiceCloseDebugLog(); + exit(1); + } +} + +#endif + +/*! + \class QtServiceController + + \brief The QtServiceController class allows you to control + services from separate applications. + + QtServiceController provides a collection of functions that lets + you install and run a service controlling its execution, as well + as query its status. + + In order to run a service, the service must be installed in the + system's service database using the install() function. The system + will start the service depending on the specified StartupType; it + can either be started during system startup, or when a process + starts it manually. + + Once a service is installed, the service can be run and controlled + manually using the start(), stop(), pause(), resume() or + sendCommand() functions. You can at any time query for the + service's status using the isInstalled() and isRunning() + functions, or you can query its properties using the + serviceDescription(), serviceFilePath(), serviceName() and + startupType() functions. For example: + + \code + MyService service; \\ which inherits QtService + QString serviceFilePath; + + QtServiceController controller(service.serviceName()); + + if (controller.install(serviceFilePath)) + controller.start() + + if (controller.isRunning()) + QMessageBox::information(this, tr("Service Status"), + tr("The %1 service is started").arg(controller.serviceName())); + + ... + + controller.stop(); + controller.uninstall(); + } + \endcode + + An instance of the service controller can only control one single + service. To control several services within one application, you + must create en equal number of service controllers. + + The QtServiceController destructor neither stops nor uninstalls + the associated service. To stop a service the stop() function must + be called explicitly. To uninstall a service, you can use the + uninstall() function. + + \sa QtServiceBase, QtService +*/ + +/*! + \enum QtServiceController::StartupType + This enum describes when a service should be started. + + \value AutoStartup The service is started during system startup. + \value ManualStartup The service must be started manually by a process. + + \warning The \a StartupType enum is ignored under UNIX-like + systems. A service, or daemon, can only be started manually on such + systems with current implementation. + + \sa startupType() +*/ + + +/*! + Creates a controller object for the service with the given + \a name. +*/ +QtServiceController::QtServiceController(const QString &name) + : d_ptr(new QtServiceControllerPrivate()) +{ + Q_D(QtServiceController); + d->q_ptr = this; + d->serviceName = name; +} +/*! + Destroys the service controller. This neither stops nor uninstalls + the controlled service. + + To stop a service the stop() function must be called + explicitly. To uninstall a service, you can use the uninstall() + function. + + \sa stop(), QtServiceController::uninstall() +*/ +QtServiceController::~QtServiceController() +{ + delete d_ptr; +} +/*! + \fn bool QtServiceController::isInstalled() const + + Returns true if the service is installed; otherwise returns false. + + On Windows it uses the system's service control manager. + + On Unix it checks configuration written to QSettings::SystemScope + using "QtSoftware" as organization name. + + \sa install() +*/ + +/*! + \fn bool QtServiceController::isRunning() const + + Returns true if the service is running; otherwise returns false. A + service must be installed before it can be run using a controller. + + \sa start(), isInstalled() +*/ + +/*! + Returns the name of the controlled service. + + \sa QtServiceController(), serviceDescription() +*/ +QString QtServiceController::serviceName() const +{ + Q_D(const QtServiceController); + return d->serviceName; +} +/*! + \fn QString QtServiceController::serviceDescription() const + + Returns the description of the controlled service. + + \sa install(), serviceName() +*/ + +/*! + \fn QtServiceController::StartupType QtServiceController::startupType() const + + Returns the startup type of the controlled service. + + \sa install(), serviceName() +*/ + +/*! + \fn QString QtServiceController::serviceFilePath() const + + Returns the file path to the controlled service. + + \sa install(), serviceName() +*/ + +/*! + Installs the service with the given \a serviceFilePath + and returns true if the service is installed + successfully; otherwise returns false. + + On Windows service is installed in the system's service control manager with the given + \a account and \a password. + + On Unix service configuration is written to QSettings::SystemScope + using "QtSoftware" as organization name. \a account and \a password + arguments are ignored. + + \warning Due to the different implementations of how services (daemons) + are installed on various UNIX-like systems, this method doesn't + integrate the service into the system's startup scripts. + + \sa uninstall(), start() +*/ +bool QtServiceController::install(const QString &serviceFilePath, const QString &account, + const QString &password) +{ + QStringList arguments; + arguments << QLatin1String("-i"); + arguments << account; + arguments << password; + return (QProcess::execute(serviceFilePath, arguments) == 0); +} + + +/*! + \fn bool QtServiceController::uninstall() + + Uninstalls the service and returns true if successful; otherwise returns false. + + On Windows service is uninstalled using the system's service control manager. + + On Unix service configuration is cleared using QSettings::SystemScope + with "QtSoftware" as organization name. + + + \sa install() +*/ + +/*! + \fn bool QtServiceController::start(const QStringList &arguments) + + Starts the installed service passing the given \a arguments to the + service. A service must be installed before a controller can run it. + + Returns true if the service could be started; otherwise returns + false. + + \sa install(), stop() +*/ + +/*! + \overload + + Starts the installed service without passing any arguments to the service. +*/ +bool QtServiceController::start() +{ + return start(QStringList()); +} + +/*! + \fn bool QtServiceController::stop() + + Requests the running service to stop. The service will call the + QtServiceBase::stop() implementation unless the service's state + is QtServiceBase::CannotBeStopped. This function does nothing if + the service is not running. + + Returns true if a running service was successfully stopped; + otherwise false. + + \sa start(), QtServiceBase::stop(), QtServiceBase::ServiceFlags +*/ + +/*! + \fn bool QtServiceController::pause() + + Requests the running service to pause. If the service's state is + QtServiceBase::CanBeSuspended, the service will call the + QtServiceBase::pause() implementation. The function does nothing + if the service is not running. + + Returns true if a running service was successfully paused; + otherwise returns false. + + \sa resume(), QtServiceBase::pause(), QtServiceBase::ServiceFlags +*/ + +/*! + \fn bool QtServiceController::resume() + + Requests the running service to continue. If the service's state + is QtServiceBase::CanBeSuspended, the service will call the + QtServiceBase::resume() implementation. This function does nothing + if the service is not running. + + Returns true if a running service was successfully resumed; + otherwise returns false. + + \sa pause(), QtServiceBase::resume(), QtServiceBase::ServiceFlags +*/ + +/*! + \fn bool QtServiceController::sendCommand(int code) + + Sends the user command \a code to the service. The service will + call the QtServiceBase::processCommand() implementation. This + function does nothing if the service is not running. + + Returns true if the request was sent to a running service; + otherwise returns false. + + \sa QtServiceBase::processCommand() +*/ + +class QtServiceStarter : public QObject +{ + Q_OBJECT +public: + QtServiceStarter(QtServiceBasePrivate *service) + : QObject(), d_ptr(service) {} +public slots: + void slotStart() + { + d_ptr->startService(); + } +private: + QtServiceBasePrivate *d_ptr; +}; +#include "qtservice.moc" + +QtServiceBase *QtServiceBasePrivate::instance = 0; + +QtServiceBasePrivate::QtServiceBasePrivate(const QString &name) + : startupType(QtServiceController::ManualStartup), serviceFlags(0), controller(name) +{ + +} + +QtServiceBasePrivate::~QtServiceBasePrivate() +{ + +} + +void QtServiceBasePrivate::startService() +{ + q_ptr->start(); +} + +int QtServiceBasePrivate::run(bool asService, const QStringList &argList) +{ + int argc = argList.size(); + QVector argv(argc); + QList argvData; + for (int i = 0; i < argc; ++i) + argvData.append(argList.at(i).toLocal8Bit()); + for (int i = 0; i < argc; ++i) + argv[i] = argvData[i].data(); + + if (asService && !sysInit()) + return -1; + + q_ptr->createApplication(argc, argv.data()); + QCoreApplication *app = QCoreApplication::instance(); + if (!app) + return -1; + + if (asService) + sysSetPath(); + + QtServiceStarter starter(this); + QTimer::singleShot(0, &starter, SLOT(slotStart())); + int res = q_ptr->executeApplication(); + delete app; + + if (asService) + sysCleanup(); + return res; +} + + +/*! + \class QtServiceBase + + \brief The QtServiceBase class provides an API for implementing + Windows services and Unix daemons. + + A Windows service or Unix daemon (a "service"), is a program that + runs "in the background" independently of whether a user is logged + in or not. A service is often set up to start when the machine + boots up, and will typically run continuously as long as the + machine is on. + + Services are usually non-interactive console applications. User + interaction, if required, is usually implemented in a separate, + normal GUI application that communicates with the service through + an IPC channel. For simple communication, + QtServiceController::sendCommand() and QtService::processCommand() + may be used, possibly in combination with a shared settings + file. For more complex, interactive communication, a custom IPC + channel should be used, e.g. based on Qt's networking classes. (In + certain circumstances, a service may provide a GUI itself, + ref. the "interactive" example documentation). + + Typically, you will create a service by subclassing the QtService + template class which inherits QtServiceBase and allows you to + create a service for a particular application type. + + The Windows implementation uses the NT Service Control Manager, + and the application can be controlled through the system + administration tools. Services are usually launched using the + system account, which requires that all DLLs that the service + executable depends on (i.e. Qt), are located in the same directory + as the service, or in a system path. + + On Unix a service is implemented as a daemon. + + You can retrieve the service's description, state, and startup + type using the serviceDescription(), serviceFlags() and + startupType() functions respectively. The service's state is + decribed by the ServiceFlag enum. The mentioned properites can + also be set using the corresponding set functions. In addition you + can retrieve the service's name using the serviceName() function. + + Several of QtServiceBase's protected functions are called on + requests from the QtServiceController class: + + \list + \o start() + \o pause() + \o processCommand() + \o resume() + \o stop() + \endlist + + You can control any given service using an instance of the + QtServiceController class which also allows you to control + services from separate applications. The mentioned functions are + all virtual and won't do anything unless they are + reimplemented. You can reimplement these functions to pause and + resume the service's execution, as well as process user commands + and perform additional clean-ups before shutting down. + + QtServiceBase also provides the static instance() function which + returns a pointer to an application's QtServiceBase instance. In + addition, a service can report events to the system's event log + using the logMessage() function. The MessageType enum describes + the different types of messages a service reports. + + The implementation of a service application's main function + typically creates an service object derived by subclassing the + QtService template class. Then the main function will call this + service's exec() function, and return the result of that call. For + example: + + \code + int main(int argc, char **argv) + { + MyService service(argc, argv); + return service.exec(); + } + \endcode + + When the exec() function is called, it will parse the service + specific arguments passed in \c argv, perform the required + actions, and return. + + \target serviceSpecificArguments + + The following arguments are recognized as service specific: + + \table + \header \i Short \i Long \i Explanation + \row \i -i \i -install \i Install the service. + \row \i -u \i -uninstall \i Uninstall the service. + \row \i -e \i -exec + \i Execute the service as a standalone application (useful for debug purposes). + This is a blocking call, the service will be executed like a normal application. + In this mode you will not be able to communicate with the service from the contoller. + \row \i -t \i -terminate \i Stop the service. + \row \i -p \i -pause \i Pause the service. + \row \i -r \i -resume \i Resume a paused service. + \row \i -c \e{cmd} \i -command \e{cmd} + \i Send the user defined command code \e{cmd} to the service application. + \row \i -v \i -version \i Display version and status information. + \endtable + + If \e none of the arguments is recognized as service specific, + exec() will first call the createApplication() function, then + executeApplication() and finally the start() function. In the end, + exec() returns while the service continues in its own process + waiting for commands from the service controller. + + \sa QtService, QtServiceController +*/ + +/*! + \enum QtServiceBase::MessageType + + This enum describes the different types of messages a service + reports to the system log. + + \value Success An operation has succeeded, e.g. the service + is started. + \value Error An operation failed, e.g. the service failed to start. + \value Warning An operation caused a warning that might require user + interaction. + \value Information Any type of usually non-critical information. +*/ + +/*! + \enum QtServiceBase::ServiceFlag + + This enum describes the different capabilities of a service. + + \value Default The service can be stopped, but not suspended. + \value CanBeSuspended The service can be suspended. + \value CannotBeStopped The service cannot be stopped. + \value NeedsStopOnShutdown (Windows only) The service will be stopped before the system shuts down. Note that Microsoft recommends this only for services that must absolutely clean up during shutdown, because there is a limited time available for shutdown of services. +*/ + +/*! + Creates a service instance called \a name. The \a argc and \a argv + parameters are parsed after the exec() function has been + called. Then they are passed to the application's constructor. + The application type is determined by the QtService subclass. + + The service is neither installed nor started. The name must not + contain any backslashes or be longer than 255 characters. In + addition, the name must be unique in the system's service + database. + + \sa exec(), start(), QtServiceController::install() +*/ +QtServiceBase::QtServiceBase(int argc, char **argv, const QString &name) +{ +#if defined(QTSERVICE_DEBUG) + qInstallMsgHandler(qtServiceLogDebug); + qAddPostRoutine(qtServiceCloseDebugLog); +#endif + + Q_ASSERT(!QtServiceBasePrivate::instance); + QtServiceBasePrivate::instance = this; + + QString nm(name); + if (nm.length() > 255) { + qWarning("QtService: 'name' is longer than 255 characters."); + nm.truncate(255); + } + if (nm.contains('\\')) { + qWarning("QtService: 'name' contains backslashes '\\'."); + nm.replace((QChar)'\\', (QChar)'\0'); + } + + d_ptr = new QtServiceBasePrivate(nm); + d_ptr->q_ptr = this; + + d_ptr->serviceFlags = 0; + d_ptr->sysd = 0; + for (int i = 0; i < argc; ++i) + d_ptr->args.append(QString::fromLocal8Bit(argv[i])); +} + +/*! + Destroys the service object. This neither stops nor uninstalls the + service. + + To stop a service the stop() function must be called + explicitly. To uninstall a service, you can use the + QtServiceController::uninstall() function. + + \sa stop(), QtServiceController::uninstall() +*/ +QtServiceBase::~QtServiceBase() +{ + delete d_ptr; + QtServiceBasePrivate::instance = 0; +} + +/*! + Returns the name of the service. + + \sa QtServiceBase(), serviceDescription() +*/ +QString QtServiceBase::serviceName() const +{ + return d_ptr->controller.serviceName(); +} + +/*! + Returns the description of the service. + + \sa setServiceDescription(), serviceName() +*/ +QString QtServiceBase::serviceDescription() const +{ + return d_ptr->serviceDescription; +} + +/*! + Sets the description of the service to the given \a description. + + \sa serviceDescription() +*/ +void QtServiceBase::setServiceDescription(const QString &description) +{ + d_ptr->serviceDescription = description; +} + +/*! + Returns the service's startup type. + + \sa QtServiceController::StartupType, setStartupType() +*/ +QtServiceController::StartupType QtServiceBase::startupType() const +{ + return d_ptr->startupType; +} + +/*! + Sets the service's startup type to the given \a type. + + \sa QtServiceController::StartupType, startupType() +*/ +void QtServiceBase::setStartupType(QtServiceController::StartupType type) +{ + d_ptr->startupType = type; +} + +/*! + Returns the service's state which is decribed using the + ServiceFlag enum. + + \sa ServiceFlags, setServiceFlags() +*/ +QtServiceBase::ServiceFlags QtServiceBase::serviceFlags() const +{ + return d_ptr->serviceFlags; +} + +/*! + \fn void QtServiceBase::setServiceFlags(ServiceFlags flags) + + Sets the service's state to the state described by the given \a + flags. + + \sa ServiceFlags, serviceFlags() +*/ + +/*! + Executes the service. + + When the exec() function is called, it will parse the \l + {serviceSpecificArguments} {service specific arguments} passed in + \c argv, perform the required actions, and exit. + + If none of the arguments is recognized as service specific, exec() + will first call the createApplication() function, then executeApplication() and + finally the start() function. In the end, exec() + returns while the service continues in its own process waiting for + commands from the service controller. + + \sa QtServiceController +*/ +int QtServiceBase::exec() +{ + if (d_ptr->args.size() > 1) { + QString a = d_ptr->args.at(1); + if (a == QLatin1String("-i") || a == QLatin1String("-install")) { + if (!d_ptr->controller.isInstalled()) { + QString account; + QString password; + if (d_ptr->args.size() > 2) + account = d_ptr->args.at(2); + if (d_ptr->args.size() > 3) + password = d_ptr->args.at(3); + if (!d_ptr->install(account, password)) { + fprintf(stderr, "The service %s could not be installed\n", serviceName().toLatin1().constData()); + return -1; + } else { + printf("The service %s has been installed under: %s\n", + serviceName().toLatin1().constData(), d_ptr->filePath().toLatin1().constData()); + } + } else { + fprintf(stderr, "The service %s is already installed\n", serviceName().toLatin1().constData()); + } + return 0; + } else if (a == QLatin1String("-u") || a == QLatin1String("-uninstall")) { + if (d_ptr->controller.isInstalled()) { + if (!d_ptr->controller.uninstall()) { + fprintf(stderr, "The service %s could not be uninstalled\n", serviceName().toLatin1().constData()); + return -1; + } else { + printf("The service %s has been uninstalled.\n", + serviceName().toLatin1().constData()); + } + } else { + fprintf(stderr, "The service %s is not installed\n", serviceName().toLatin1().constData()); + } + return 0; + } else if (a == QLatin1String("-v") || a == QLatin1String("-version")) { + printf("The service\n" + "\t%s\n\t%s\n\n", serviceName().toLatin1().constData(), d_ptr->args.at(0).toLatin1().constData()); + printf("is %s", (d_ptr->controller.isInstalled() ? "installed" : "not installed")); + printf(" and %s\n\n", (d_ptr->controller.isRunning() ? "running" : "not running")); + return 0; + } else if (a == QLatin1String("-e") || a == QLatin1String("-exec")) { + d_ptr->args.removeAt(1); + int ec = d_ptr->run(false, d_ptr->args); + if (ec == -1) + qErrnoWarning("The service could not be executed."); + return ec; + } else if (a == QLatin1String("-t") || a == QLatin1String("-terminate")) { + if (!d_ptr->controller.stop()) + qErrnoWarning("The service could not be stopped."); + return 0; + } else if (a == QLatin1String("-p") || a == QLatin1String("-pause")) { + d_ptr->controller.pause(); + return 0; + } else if (a == QLatin1String("-r") || a == QLatin1String("-resume")) { + d_ptr->controller.resume(); + return 0; + } else if (a == QLatin1String("-c") || a == QLatin1String("-command")) { + int code = 0; + if (d_ptr->args.size() > 2) + code = d_ptr->args.at(2).toInt(); + d_ptr->controller.sendCommand(code); + return 0; + } else if (a == QLatin1String("-h") || a == QLatin1String("-help")) { + printf("\n%s -[i|u|e|s|v|h]\n" + "\t-i(nstall) [account] [password]\t: Install the service, optionally using given account and password\n" + "\t-u(ninstall)\t: Uninstall the service.\n" + "\t-e(xec)\t\t: Run as a regular application. Useful for debugging.\n" + "\t-t(erminate)\t: Stop the service.\n" + "\t-c(ommand) num\t: Send command code num to the service.\n" + "\t-v(ersion)\t: Print version and status information.\n" + "\t-h(elp) \t: Show this help\n" + "\tNo arguments\t: Start the service.\n", + d_ptr->args.at(0).toLatin1().constData()); + return 0; + } + } +#if defined(Q_OS_UNIX) + if (::getenv("QTSERVICE_RUN")) { + // Means we're the detached, real service process. + int ec = d_ptr->run(true, d_ptr->args); + if (ec == -1) + qErrnoWarning("The service failed to run."); + return ec; + } +#endif + if (!d_ptr->start()) { + fprintf(stderr, "The service %s could not start\n", serviceName().toLatin1().constData()); + return -4; + } + return 0; +} + +/*! + \fn void QtServiceBase::logMessage(const QString &message, MessageType type, + int id, uint category, const QByteArray &data) + + Reports a message of the given \a type with the given \a message + to the local system event log. The message identifier \a id and + the message \a category are user defined values. The \a data + parameter can contain arbitrary binary data. + + Message strings for \a id and \a category must be provided by a + message file, which must be registered in the system registry. + Refer to the MSDN for more information about how to do this on + Windows. + + \sa MessageType +*/ + +/*! + Returns a pointer to the current application's QtServiceBase + instance. +*/ +QtServiceBase *QtServiceBase::instance() +{ + return QtServiceBasePrivate::instance; +} + +/*! + \fn void QtServiceBase::start() + + This function must be implemented in QtServiceBase subclasses in + order to perform the service's work. Usually you create some main + object on the heap which is the heart of your service. + + The function is only called when no service specific arguments + were passed to the service constructor, and is called by exec() + after it has called the executeApplication() function. + + Note that you \e don't need to create an application object or + call its exec() function explicitly. + + \sa exec(), stop(), QtServiceController::start() +*/ + +/*! + Reimplement this function to perform additional cleanups before + shutting down (for example deleting a main object if it was + created in the start() function). + + This function is called in reply to controller requests. The + default implementation does nothing. + + \sa start(), QtServiceController::stop() +*/ +void QtServiceBase::stop() +{ +} + +/*! + Reimplement this function to pause the service's execution (for + example to stop a polling timer, or to ignore socket notifiers). + + This function is called in reply to controller requests. The + default implementation does nothing. + + \sa resume(), QtServiceController::pause() +*/ +void QtServiceBase::pause() +{ +} + +/*! + Reimplement this function to continue the service after a call to + pause(). + + This function is called in reply to controller requests. The + default implementation does nothing. + + \sa pause(), QtServiceController::resume() +*/ +void QtServiceBase::resume() +{ +} + +/*! + Reimplement this function to process the user command \a code. + + + This function is called in reply to controller requests. The + default implementation does nothing. + + \sa QtServiceController::sendCommand() +*/ +void QtServiceBase::processCommand(int /*code*/) +{ +} + +/*! + \fn void QtServiceBase::createApplication(int &argc, char **argv) + + Creates the application object using the \a argc and \a argv + parameters. + + This function is only called when no \l + {serviceSpecificArguments}{service specific arguments} were + passed to the service constructor, and is called by exec() before + it calls the executeApplication() and start() functions. + + The createApplication() function is implemented in QtService, but + you might want to reimplement it, for example, if the chosen + application type's constructor needs additional arguments. + + \sa exec(), QtService +*/ + +/*! + \fn int QtServiceBase::executeApplication() + + Executes the application previously created with the + createApplication() function. + + This function is only called when no \l + {serviceSpecificArguments}{service specific arguments} were + passed to the service constructor, and is called by exec() after + it has called the createApplication() function and before start() function. + + This function is implemented in QtService. + + \sa exec(), createApplication() +*/ + +/*! + \class QtService + + \brief The QtService is a convenient template class that allows + you to create a service for a particular application type. + + A Windows service or Unix daemon (a "service"), is a program that + runs "in the background" independently of whether a user is logged + in or not. A service is often set up to start when the machine + boots up, and will typically run continuously as long as the + machine is on. + + Services are usually non-interactive console applications. User + interaction, if required, is usually implemented in a separate, + normal GUI application that communicates with the service through + an IPC channel. For simple communication, + QtServiceController::sendCommand() and QtService::processCommand() + may be used, possibly in combination with a shared settings file. For + more complex, interactive communication, a custom IPC channel + should be used, e.g. based on Qt's networking classes. (In certain + circumstances, a service may provide a GUI itself, ref. the + "interactive" example documentation). + + \bold{Note:} On Unix systems, this class relies on facilities + provided by the QtNetwork module, provided as part of the + \l{Qt Open Source Edition} and certain \l{Qt Commercial Editions}. + + The QtService class functionality is inherited from QtServiceBase, + but in addition the QtService class binds an instance of + QtServiceBase with an application type. + + Typically, you will create a service by subclassing the QtService + template class. For example: + + \code + class MyService : public QtService + { + public: + MyService(int argc, char **argv); + ~MyService(); + + protected: + void start(); + void stop(); + void pause(); + void resume(); + void processCommand(int code); + }; + \endcode + + The application type can be QCoreApplication for services without + GUI, QApplication for services with GUI or you can use your own + custom application type. + + You must reimplement the QtServiceBase::start() function to + perform the service's work. Usually you create some main object on + the heap which is the heart of your service. + + In addition, you might want to reimplement the + QtServiceBase::pause(), QtServiceBase::processCommand(), + QtServiceBase::resume() and QtServiceBase::stop() to intervene the + service's process on controller requests. You can control any + given service using an instance of the QtServiceController class + which also allows you to control services from separate + applications. The mentioned functions are all virtual and won't do + anything unless they are reimplemented. + + Your custom service is typically instantiated in the application's + main function. Then the main function will call your service's + exec() function, and return the result of that call. For example: + + \code + int main(int argc, char **argv) + { + MyService service(argc, argv); + return service.exec(); + } + \endcode + + When the exec() function is called, it will parse the \l + {serviceSpecificArguments} {service specific arguments} passed in + \c argv, perform the required actions, and exit. + + If none of the arguments is recognized as service specific, exec() + will first call the createApplication() function, then executeApplication() and + finally the start() function. In the end, exec() + returns while the service continues in its own process waiting for + commands from the service controller. + + \sa QtServiceBase, QtServiceController +*/ + +/*! + \fn QtService::QtService(int argc, char **argv, const QString &name) + + Constructs a QtService object called \a name. The \a argc and \a + argv parameters are parsed after the exec() function has been + called. Then they are passed to the application's constructor. + + There can only be one QtService object in a process. + + \sa QtServiceBase() +*/ + +/*! + \fn QtService::~QtService() + + Destroys the service object. +*/ + +/*! + \fn Application *QtService::application() const + + Returns a pointer to the application object. +*/ + +/*! + \fn void QtService::createApplication(int &argc, char **argv) + + Creates application object of type Application passing \a argc and + \a argv to its constructor. + + \reimp + +*/ + +/*! + \fn int QtService::executeApplication() + + \reimp +*/ + + + diff --git a/src/qtservice/src/qtservice.h b/src/qtservice/src/qtservice.h new file mode 100644 index 0000000..01d5b07 --- /dev/null +++ b/src/qtservice/src/qtservice.h @@ -0,0 +1,192 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTSERVICE_H +#define QTSERVICE_H + +#include + +#if defined(Q_OS_WIN) +# if !defined(QT_QTSERVICE_EXPORT) && !defined(QT_QTSERVICE_IMPORT) +# define QT_QTSERVICE_EXPORT +# elif defined(QT_QTSERVICE_IMPORT) +# if defined(QT_QTSERVICE_EXPORT) +# undef QT_QTSERVICE_EXPORT +# endif +# define QT_QTSERVICE_EXPORT __declspec(dllimport) +# elif defined(QT_QTSERVICE_EXPORT) +# undef QT_QTSERVICE_EXPORT +# define QT_QTSERVICE_EXPORT __declspec(dllexport) +# endif +#else +# define QT_QTSERVICE_EXPORT +#endif + +class QStringList; +class QtServiceControllerPrivate; + +class QT_QTSERVICE_EXPORT QtServiceController +{ + Q_DECLARE_PRIVATE(QtServiceController) +public: + enum StartupType + { + AutoStartup = 0, ManualStartup + }; + + QtServiceController(const QString &name); + virtual ~QtServiceController(); + + bool isInstalled() const; + bool isRunning() const; + + QString serviceName() const; + QString serviceDescription() const; + StartupType startupType() const; + QString serviceFilePath() const; + + static bool install(const QString &serviceFilePath, const QString &account = QString(), + const QString &password = QString()); + bool uninstall(); + + bool start(const QStringList &arguments); + bool start(); + bool stop(); + bool pause(); + bool resume(); + bool sendCommand(int code); + +private: + QtServiceControllerPrivate *d_ptr; +}; + +class QtServiceBasePrivate; + +class QT_QTSERVICE_EXPORT QtServiceBase +{ + Q_DECLARE_PRIVATE(QtServiceBase) +public: + + enum MessageType + { + Success = 0, Error, Warning, Information + }; + + enum ServiceFlag + { + Default = 0x00, + CanBeSuspended = 0x01, + CannotBeStopped = 0x02, + NeedsStopOnShutdown = 0x04 + }; + + Q_DECLARE_FLAGS(ServiceFlags, ServiceFlag) + + QtServiceBase(int argc, char **argv, const QString &name); + virtual ~QtServiceBase(); + + QString serviceName() const; + + QString serviceDescription() const; + void setServiceDescription(const QString &description); + + QtServiceController::StartupType startupType() const; + void setStartupType(QtServiceController::StartupType startupType); + + ServiceFlags serviceFlags() const; + void setServiceFlags(ServiceFlags flags); + + int exec(); + + void logMessage(const QString &message, MessageType type = Success, + int id = 0, uint category = 0, const QByteArray &data = QByteArray()); + + static QtServiceBase *instance(); + +protected: + + virtual void start() = 0; + virtual void stop(); + virtual void pause(); + virtual void resume(); + virtual void processCommand(int code); + + virtual void createApplication(int &argc, char **argv) = 0; + + virtual int executeApplication() = 0; + +private: + + friend class QtServiceSysPrivate; + QtServiceBasePrivate *d_ptr; +}; + +template +class QtService : public QtServiceBase +{ +public: + QtService(int argc, char **argv, const QString &name) + : QtServiceBase(argc, argv, name), app(0) + { } + ~QtService() + { + } + +protected: + Application *application() const + { return app; } + + virtual void createApplication(int &argc, char **argv) + { + app = new Application(argc, argv); + QCoreApplication *a = app; + Q_UNUSED(a); + } + + virtual int executeApplication() + { return Application::exec(); } + +private: + Application *app; +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(QtServiceBase::ServiceFlags) + +#endif // QTSERVICE_H diff --git a/src/qtservice/src/qtservice_p.h b/src/qtservice/src/qtservice_p.h new file mode 100644 index 0000000..a88992c --- /dev/null +++ b/src/qtservice/src/qtservice_p.h @@ -0,0 +1,87 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTSERVICE_P_H +#define QTSERVICE_P_H + +#include +#include "qtservice.h" + +class QtServiceControllerPrivate +{ + Q_DECLARE_PUBLIC(QtServiceController) +public: + QString serviceName; + QtServiceController *q_ptr; +}; + +class QtServiceBasePrivate +{ + Q_DECLARE_PUBLIC(QtServiceBase) +public: + + QtServiceBasePrivate(const QString &name); + ~QtServiceBasePrivate(); + + QtServiceBase *q_ptr; + + QString serviceDescription; + QtServiceController::StartupType startupType; + QtServiceBase::ServiceFlags serviceFlags; + QStringList args; + + static class QtServiceBase *instance; + + QtServiceController controller; + + void startService(); + int run(bool asService, const QStringList &argList); + bool install(const QString &account, const QString &password); + + bool start(); + + QString filePath() const; + bool sysInit(); + void sysSetPath(); + void sysCleanup(); + class QtServiceSysPrivate *sysd; +}; + +#endif diff --git a/src/qtservice/src/qtservice_unix.cpp b/src/qtservice/src/qtservice_unix.cpp new file mode 100644 index 0000000..40d75c1 --- /dev/null +++ b/src/qtservice/src/qtservice_unix.cpp @@ -0,0 +1,474 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qtservice.h" +#include "qtservice_p.h" +#include "qtunixsocket.h" +#include "qtunixserversocket.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static QString encodeName(const QString &name, bool allowUpper = false) +{ + QString n = name.toLower(); + QString legal = QLatin1String("abcdefghijklmnopqrstuvwxyz1234567890"); + if (allowUpper) + legal += QLatin1String("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + int pos = 0; + while (pos < n.size()) { + if (legal.indexOf(n[pos]) == -1) + n.remove(pos, 1); + else + ++pos; + } + return n; +} + +static QString login() +{ + QString l; + uid_t uid = getuid(); + passwd *pw = getpwuid(uid); + if (pw) + l = QString(pw->pw_name); + return l; +} + +static QString socketPath(const QString &serviceName) +{ + QString sn = encodeName(serviceName); + return QString(QLatin1String("/var/tmp/") + sn + QLatin1String(".") + login()); +} + +static bool sendCmd(const QString &serviceName, const QString &cmd) +{ + bool retValue = false; + QtUnixSocket sock; + if (sock.connectTo(socketPath(serviceName))) { + sock.write(QString(cmd+"\r\n").toLatin1().constData()); + sock.flush(); + sock.waitForReadyRead(-1); + QString reply = sock.readAll(); + if (reply == QLatin1String("true")) + retValue = true; + sock.close(); + } + return retValue; +} + +static QString absPath(const QString &path) +{ + QString ret; + if (path[0] != QChar('/')) { // Not an absolute path + int slashpos; + if ((slashpos = path.lastIndexOf('/')) != -1) { // Relative path + QDir dir = QDir::current(); + dir.cd(path.left(slashpos)); + ret = dir.absolutePath(); + } else { // Need to search $PATH + char *envPath = ::getenv("PATH"); + if (envPath) { + QStringList envPaths = QString::fromLocal8Bit(envPath).split(':'); + for (int i = 0; i < envPaths.size(); ++i) { + if (QFile::exists(envPaths.at(i) + QLatin1String("/") + QString(path))) { + QDir dir(envPaths.at(i)); + ret = dir.absolutePath(); + break; + } + } + } + } + } else { + QFileInfo fi(path); + ret = fi.absolutePath(); + } + return ret; +} + +QString QtServiceBasePrivate::filePath() const +{ + QString ret; + if (args.isEmpty()) + return ret; + QFileInfo fi(args[0]); + QDir dir(absPath(args[0])); + return dir.absoluteFilePath(fi.fileName()); +} + + +QString QtServiceController::serviceDescription() const +{ + QSettings settings(QSettings::SystemScope, "QtSoftware"); + settings.beginGroup("services"); + settings.beginGroup(serviceName()); + + QString desc = settings.value("description").toString(); + + settings.endGroup(); + settings.endGroup(); + + return desc; +} + +QtServiceController::StartupType QtServiceController::startupType() const +{ + QSettings settings(QSettings::SystemScope, "QtSoftware"); + settings.beginGroup("services"); + settings.beginGroup(serviceName()); + + StartupType startupType = (StartupType)settings.value("startupType").toInt(); + + settings.endGroup(); + settings.endGroup(); + + return startupType; +} + +QString QtServiceController::serviceFilePath() const +{ + QSettings settings(QSettings::SystemScope, "QtSoftware"); + settings.beginGroup("services"); + settings.beginGroup(serviceName()); + + QString path = settings.value("path").toString(); + + settings.endGroup(); + settings.endGroup(); + + return path; +} + +bool QtServiceController::uninstall() +{ + QSettings settings(QSettings::SystemScope, "QtSoftware"); + settings.beginGroup("services"); + + settings.remove(serviceName()); + + settings.endGroup(); + settings.sync(); + + QSettings::Status ret = settings.status(); + if (ret == QSettings::AccessError) { + fprintf(stderr, "Cannot uninstall \"%s\". Cannot write to: %s. Check permissions.\n", + serviceName().toLatin1().constData(), + settings.fileName().toLatin1().constData()); + } + return (ret == QSettings::NoError); +} + + +bool QtServiceController::start(const QStringList &arguments) +{ + if (!isInstalled()) + return false; + if (isRunning()) + return false; + return QProcess::startDetached(serviceFilePath(), arguments); +} + +bool QtServiceController::stop() +{ + return sendCmd(serviceName(), QLatin1String("terminate")); +} + +bool QtServiceController::pause() +{ + return sendCmd(serviceName(), QLatin1String("pause")); +} + +bool QtServiceController::resume() +{ + return sendCmd(serviceName(), QLatin1String("resume")); +} + +bool QtServiceController::sendCommand(int code) +{ + return sendCmd(serviceName(), QString(QLatin1String("num:") + QString::number(code))); +} + +bool QtServiceController::isInstalled() const +{ + QSettings settings(QSettings::SystemScope, "QtSoftware"); + settings.beginGroup("services"); + + QStringList list = settings.childGroups(); + + settings.endGroup(); + + QStringListIterator it(list); + while (it.hasNext()) { + if (it.next() == serviceName()) + return true; + } + + return false; +} + +bool QtServiceController::isRunning() const +{ + QtUnixSocket sock; + if (sock.connectTo(socketPath(serviceName()))) + return true; + return false; +} + + + + +/////////////////////////////////// + +class QtServiceSysPrivate : public QtUnixServerSocket +{ + Q_OBJECT +public: + QtServiceSysPrivate(); + ~QtServiceSysPrivate(); + + char *ident; + + QtServiceBase::ServiceFlags serviceFlags; + +protected: + void incomingConnection(int socketDescriptor); + +private slots: + void slotReady(); + void slotClosed(); + +private: + QString getCommand(const QTcpSocket *socket); + QMap cache; +}; + +QtServiceSysPrivate::QtServiceSysPrivate() + : QtUnixServerSocket(), ident(0), serviceFlags(0) +{ +} + +QtServiceSysPrivate::~QtServiceSysPrivate() +{ + if (ident) + delete[] ident; +} + +void QtServiceSysPrivate::incomingConnection(int socketDescriptor) +{ + QTcpSocket *s = new QTcpSocket(this); + s->setSocketDescriptor(socketDescriptor); + connect(s, SIGNAL(readyRead()), this, SLOT(slotReady())); + connect(s, SIGNAL(disconnected()), this, SLOT(slotClosed())); +} + +void QtServiceSysPrivate::slotReady() +{ + QTcpSocket *s = (QTcpSocket *)sender(); + cache[s] += QString(s->readAll()); + QString cmd = getCommand(s); + while (!cmd.isEmpty()) { + bool retValue = false; + if (cmd == QLatin1String("terminate")) { + if (!(serviceFlags & QtServiceBase::CannotBeStopped)) { + QtServiceBase::instance()->stop(); + QCoreApplication::instance()->quit(); + retValue = true; + } + } else if (cmd == QLatin1String("pause")) { + if (serviceFlags & QtServiceBase::CanBeSuspended) { + QtServiceBase::instance()->pause(); + retValue = true; + } + } else if (cmd == QLatin1String("resume")) { + if (serviceFlags & QtServiceBase::CanBeSuspended) { + QtServiceBase::instance()->resume(); + retValue = true; + } + } else if (cmd == QLatin1String("alive")) { + retValue = true; + } else if (cmd.length() > 4 && cmd.left(4) == QLatin1String("num:")) { + cmd = cmd.mid(4); + QtServiceBase::instance()->processCommand(cmd.toInt()); + retValue = true; + } + QString retString; + if (retValue) + retString = QLatin1String("true"); + else + retString = QLatin1String("false"); + s->write(retString.toLatin1().constData()); + s->flush(); + cmd = getCommand(s); + } +} + +void QtServiceSysPrivate::slotClosed() +{ + QTcpSocket *s = (QTcpSocket *)sender(); + s->deleteLater(); +} + +QString QtServiceSysPrivate::getCommand(const QTcpSocket *socket) +{ + int pos = cache[socket].indexOf("\r\n"); + if (pos >= 0) { + QString ret = cache[socket].left(pos); + cache[socket].remove(0, pos+2); + return ret; + } + return ""; +} + +#include "qtservice_unix.moc" + +bool QtServiceBasePrivate::sysInit() +{ + sysd = new QtServiceSysPrivate; + sysd->serviceFlags = serviceFlags; + // Restrict permissions on files that are created by the service + ::umask(027); + + return true; +} + +void QtServiceBasePrivate::sysSetPath() +{ + if (sysd) + sysd->setPath(socketPath(controller.serviceName())); +} + +void QtServiceBasePrivate::sysCleanup() +{ + if (sysd) { + sysd->close(); + delete sysd; + sysd = 0; + } +} + +bool QtServiceBasePrivate::start() +{ + if (sendCmd(controller.serviceName(), "alive")) { + // Already running + return false; + } + // Could just call controller.start() here, but that would fail if + // we're not installed. We do not want to strictly require installation. + ::setenv("QTSERVICE_RUN", "1", 1); // Tell the detached process it's it + return QProcess::startDetached(filePath(), args.mid(1), "/"); +} + +bool QtServiceBasePrivate::install(const QString &account, const QString &password) +{ + Q_UNUSED(account) + Q_UNUSED(password) + QSettings settings(QSettings::SystemScope, "QtSoftware"); + + settings.beginGroup("services"); + settings.beginGroup(controller.serviceName()); + + settings.setValue("path", filePath()); + settings.setValue("description", serviceDescription); + settings.setValue("automaticStartup", startupType); + + settings.endGroup(); + settings.endGroup(); + settings.sync(); + + QSettings::Status ret = settings.status(); + if (ret == QSettings::AccessError) { + fprintf(stderr, "Cannot install \"%s\". Cannot write to: %s. Check permissions.\n", + controller.serviceName().toLatin1().constData(), + settings.fileName().toLatin1().constData()); + } + return (ret == QSettings::NoError); +} + +void QtServiceBase::logMessage(const QString &message, QtServiceBase::MessageType type, + int, uint, const QByteArray &) +{ + if (!d_ptr->sysd) + return; + int st; + switch(type) { + case QtServiceBase::Error: + st = LOG_ERR; + break; + case QtServiceBase::Warning: + st = LOG_WARNING; + break; + default: + st = LOG_INFO; + } + if (!d_ptr->sysd->ident) { + QString tmp = encodeName(serviceName(), true); + int len = tmp.toLocal8Bit().size(); + d_ptr->sysd->ident = new char[len+1]; + d_ptr->sysd->ident[len] = '\0'; + ::memcpy(d_ptr->sysd->ident, tmp.toLocal8Bit().constData(), len); + } + openlog(d_ptr->sysd->ident, LOG_PID, LOG_DAEMON); + foreach(QString line, message.split('\n')) + syslog(st, "%s", line.toLocal8Bit().constData()); + closelog(); +} + +void QtServiceBase::setServiceFlags(QtServiceBase::ServiceFlags flags) +{ + if (d_ptr->serviceFlags == flags) + return; + d_ptr->serviceFlags = flags; + if (d_ptr->sysd) + d_ptr->sysd->serviceFlags = flags; +} + diff --git a/src/qtservice/src/qtservice_win.cpp b/src/qtservice/src/qtservice_win.cpp new file mode 100644 index 0000000..f4b8cc9 --- /dev/null +++ b/src/qtservice/src/qtservice_win.cpp @@ -0,0 +1,945 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qtservice.h" +#include "qtservice_p.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if QT_VERSION >= 0x050000 +# include +#endif +#include +#if defined(QTSERVICE_DEBUG) +#include +#endif + +typedef SERVICE_STATUS_HANDLE(WINAPI*PRegisterServiceCtrlHandler)(const wchar_t*,LPHANDLER_FUNCTION); +static PRegisterServiceCtrlHandler pRegisterServiceCtrlHandler = 0; +typedef BOOL(WINAPI*PSetServiceStatus)(SERVICE_STATUS_HANDLE,LPSERVICE_STATUS); +static PSetServiceStatus pSetServiceStatus = 0; +typedef BOOL(WINAPI*PChangeServiceConfig2)(SC_HANDLE,DWORD,LPVOID); +static PChangeServiceConfig2 pChangeServiceConfig2 = 0; +typedef BOOL(WINAPI*PCloseServiceHandle)(SC_HANDLE); +static PCloseServiceHandle pCloseServiceHandle = 0; +typedef SC_HANDLE(WINAPI*PCreateService)(SC_HANDLE,LPCTSTR,LPCTSTR,DWORD,DWORD,DWORD,DWORD,LPCTSTR,LPCTSTR,LPDWORD,LPCTSTR,LPCTSTR,LPCTSTR); +static PCreateService pCreateService = 0; +typedef SC_HANDLE(WINAPI*POpenSCManager)(LPCTSTR,LPCTSTR,DWORD); +static POpenSCManager pOpenSCManager = 0; +typedef BOOL(WINAPI*PDeleteService)(SC_HANDLE); +static PDeleteService pDeleteService = 0; +typedef SC_HANDLE(WINAPI*POpenService)(SC_HANDLE,LPCTSTR,DWORD); +static POpenService pOpenService = 0; +typedef BOOL(WINAPI*PQueryServiceStatus)(SC_HANDLE,LPSERVICE_STATUS); +static PQueryServiceStatus pQueryServiceStatus = 0; +typedef BOOL(WINAPI*PStartServiceCtrlDispatcher)(CONST SERVICE_TABLE_ENTRY*); +static PStartServiceCtrlDispatcher pStartServiceCtrlDispatcher = 0; +typedef BOOL(WINAPI*PStartService)(SC_HANDLE,DWORD,const wchar_t**); +static PStartService pStartService = 0; +typedef BOOL(WINAPI*PControlService)(SC_HANDLE,DWORD,LPSERVICE_STATUS); +static PControlService pControlService = 0; +typedef HANDLE(WINAPI*PDeregisterEventSource)(HANDLE); +static PDeregisterEventSource pDeregisterEventSource = 0; +typedef BOOL(WINAPI*PReportEvent)(HANDLE,WORD,WORD,DWORD,PSID,WORD,DWORD,LPCTSTR*,LPVOID); +static PReportEvent pReportEvent = 0; +typedef HANDLE(WINAPI*PRegisterEventSource)(LPCTSTR,LPCTSTR); +static PRegisterEventSource pRegisterEventSource = 0; +typedef DWORD(WINAPI*PRegisterServiceProcess)(DWORD,DWORD); +static PRegisterServiceProcess pRegisterServiceProcess = 0; +typedef BOOL(WINAPI*PQueryServiceConfig)(SC_HANDLE,LPQUERY_SERVICE_CONFIG,DWORD,LPDWORD); +static PQueryServiceConfig pQueryServiceConfig = 0; +typedef BOOL(WINAPI*PQueryServiceConfig2)(SC_HANDLE,DWORD,LPBYTE,DWORD,LPDWORD); +static PQueryServiceConfig2 pQueryServiceConfig2 = 0; + + +#define RESOLVE(name) p##name = (P##name)lib.resolve(#name); +#define RESOLVEA(name) p##name = (P##name)lib.resolve(#name"A"); +#define RESOLVEW(name) p##name = (P##name)lib.resolve(#name"W"); + +static bool winServiceInit() +{ + if (!pOpenSCManager) { + QLibrary lib("advapi32"); + + // only resolve unicode versions + RESOLVEW(RegisterServiceCtrlHandler); + RESOLVE(SetServiceStatus); + RESOLVEW(ChangeServiceConfig2); + RESOLVE(CloseServiceHandle); + RESOLVEW(CreateService); + RESOLVEW(OpenSCManager); + RESOLVE(DeleteService); + RESOLVEW(OpenService); + RESOLVE(QueryServiceStatus); + RESOLVEW(StartServiceCtrlDispatcher); + RESOLVEW(StartService); // need only Ansi version + RESOLVE(ControlService); + RESOLVE(DeregisterEventSource); + RESOLVEW(ReportEvent); + RESOLVEW(RegisterEventSource); + RESOLVEW(QueryServiceConfig); + RESOLVEW(QueryServiceConfig2); + } + return pOpenSCManager != 0; +} + +bool QtServiceController::isInstalled() const +{ + Q_D(const QtServiceController); + bool result = false; + if (!winServiceInit()) + return result; + + // Open the Service Control Manager + SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); + if (hSCM) { + // Try to open the service + SC_HANDLE hService = pOpenService(hSCM, (wchar_t*)d->serviceName.utf16(), + SERVICE_QUERY_CONFIG); + + if (hService) { + result = true; + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +bool QtServiceController::isRunning() const +{ + Q_D(const QtServiceController); + bool result = false; + if (!winServiceInit()) + return result; + + // Open the Service Control Manager + SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); + if (hSCM) { + // Try to open the service + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), + SERVICE_QUERY_STATUS); + if (hService) { + SERVICE_STATUS info; + int res = pQueryServiceStatus(hService, &info); + if (res) + result = info.dwCurrentState != SERVICE_STOPPED; + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + + +QString QtServiceController::serviceFilePath() const +{ + Q_D(const QtServiceController); + QString result; + if (!winServiceInit()) + return result; + + // Open the Service Control Manager + SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); + if (hSCM) { + // Try to open the service + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), + SERVICE_QUERY_CONFIG); + if (hService) { + DWORD sizeNeeded = 0; + char data[8 * 1024]; + if (pQueryServiceConfig(hService, (LPQUERY_SERVICE_CONFIG)data, 8 * 1024, &sizeNeeded)) { + LPQUERY_SERVICE_CONFIG config = (LPQUERY_SERVICE_CONFIG)data; + result = QString::fromUtf16((const ushort*)config->lpBinaryPathName); + } + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +QString QtServiceController::serviceDescription() const +{ + Q_D(const QtServiceController); + QString result; + if (!winServiceInit()) + return result; + + // Open the Service Control Manager + SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); + if (hSCM) { + // Try to open the service + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), + SERVICE_QUERY_CONFIG); + if (hService) { + DWORD dwBytesNeeded; + char data[8 * 1024]; + if (pQueryServiceConfig2( + hService, + SERVICE_CONFIG_DESCRIPTION, + (unsigned char *)data, + 8096, + &dwBytesNeeded)) { + LPSERVICE_DESCRIPTION desc = (LPSERVICE_DESCRIPTION)data; + if (desc->lpDescription) + result = QString::fromUtf16((const ushort*)desc->lpDescription); + } + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +QtServiceController::StartupType QtServiceController::startupType() const +{ + Q_D(const QtServiceController); + StartupType result = ManualStartup; + if (!winServiceInit()) + return result; + + // Open the Service Control Manager + SC_HANDLE hSCM = pOpenSCManager(0, 0, 0); + if (hSCM) { + // Try to open the service + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), + SERVICE_QUERY_CONFIG); + if (hService) { + DWORD sizeNeeded = 0; + char data[8 * 1024]; + if (pQueryServiceConfig(hService, (QUERY_SERVICE_CONFIG *)data, 8 * 1024, &sizeNeeded)) { + QUERY_SERVICE_CONFIG *config = (QUERY_SERVICE_CONFIG *)data; + result = config->dwStartType == SERVICE_DEMAND_START ? ManualStartup : AutoStartup; + } + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +bool QtServiceController::uninstall() +{ + Q_D(QtServiceController); + bool result = false; + if (!winServiceInit()) + return result; + + // Open the Service Control Manager + SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS); + if (hSCM) { + // Try to open the service + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), DELETE); + if (hService) { + if (pDeleteService(hService)) + result = true; + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +bool QtServiceController::start(const QStringList &args) +{ + Q_D(QtServiceController); + bool result = false; + if (!winServiceInit()) + return result; + + // Open the Service Control Manager + SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); + if (hSCM) { + // Try to open the service + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_START); + if (hService) { + QVector argv(args.size()); + for (int i = 0; i < args.size(); ++i) + argv[i] = (const wchar_t*)args.at(i).utf16(); + + if (pStartService(hService, args.size(), argv.data())) + result = true; + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +bool QtServiceController::stop() +{ + Q_D(QtServiceController); + bool result = false; + if (!winServiceInit()) + return result; + + SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); + if (hSCM) { + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), SERVICE_STOP|SERVICE_QUERY_STATUS); + if (hService) { + SERVICE_STATUS status; + if (pControlService(hService, SERVICE_CONTROL_STOP, &status)) { + bool stopped = status.dwCurrentState == SERVICE_STOPPED; + int i = 0; + while(!stopped && i < 10) { + Sleep(200); + if (!pQueryServiceStatus(hService, &status)) + break; + stopped = status.dwCurrentState == SERVICE_STOPPED; + ++i; + } + result = stopped; + } else { + qErrnoWarning(GetLastError(), "stopping"); + } + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +bool QtServiceController::pause() +{ + Q_D(QtServiceController); + bool result = false; + if (!winServiceInit()) + return result; + + SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); + if (hSCM) { + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), + SERVICE_PAUSE_CONTINUE); + if (hService) { + SERVICE_STATUS status; + if (pControlService(hService, SERVICE_CONTROL_PAUSE, &status)) + result = true; + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +bool QtServiceController::resume() +{ + Q_D(QtServiceController); + bool result = false; + if (!winServiceInit()) + return result; + + SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); + if (hSCM) { + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), + SERVICE_PAUSE_CONTINUE); + if (hService) { + SERVICE_STATUS status; + if (pControlService(hService, SERVICE_CONTROL_CONTINUE, &status)) + result = true; + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +bool QtServiceController::sendCommand(int code) +{ + Q_D(QtServiceController); + bool result = false; + if (!winServiceInit()) + return result; + + if (code < 0 || code > 127 || !isRunning()) + return result; + + SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_CONNECT); + if (hSCM) { + SC_HANDLE hService = pOpenService(hSCM, (wchar_t *)d->serviceName.utf16(), + SERVICE_USER_DEFINED_CONTROL); + if (hService) { + SERVICE_STATUS status; + if (pControlService(hService, 128 + code, &status)) + result = true; + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +#if defined(QTSERVICE_DEBUG) +extern void qtServiceLogDebug(QtMsgType type, const char* msg); +#endif + +void QtServiceBase::logMessage(const QString &message, MessageType type, + int id, uint category, const QByteArray &data) +{ +#if defined(QTSERVICE_DEBUG) + QByteArray dbgMsg("[LOGGED "); + switch (type) { + case Error: dbgMsg += "Error] " ; break; + case Warning: dbgMsg += "Warning] "; break; + case Success: dbgMsg += "Success] "; break; + case Information: //fall through + default: dbgMsg += "Information] "; break; + } + dbgMsg += message.toAscii(); + qtServiceLogDebug((QtMsgType)-1, dbgMsg.constData()); +#endif + + Q_D(QtServiceBase); + if (!winServiceInit()) + return; + WORD wType; + switch (type) { + case Error: wType = EVENTLOG_ERROR_TYPE; break; + case Warning: wType = EVENTLOG_WARNING_TYPE; break; + case Information: wType = EVENTLOG_INFORMATION_TYPE; break; + default: wType = EVENTLOG_SUCCESS; break; + } + HANDLE h = pRegisterEventSource(0, (wchar_t *)d->controller.serviceName().utf16()); + if (h) { + const wchar_t *msg = (wchar_t*)message.utf16(); + const char *bindata = data.size() ? data.constData() : 0; + pReportEvent(h, wType, category, id, 0, 1, data.size(),(const wchar_t **)&msg, + const_cast(bindata)); + pDeregisterEventSource(h); + } +} + +class QtServiceControllerHandler : public QObject +{ + Q_OBJECT +public: + QtServiceControllerHandler(QtServiceSysPrivate *sys); + +protected: + void customEvent(QEvent *e); + +private: + QtServiceSysPrivate *d_sys; +}; + +class QtServiceSysPrivate +{ +public: + enum { + QTSERVICE_STARTUP = 256 + }; + QtServiceSysPrivate(); + + void setStatus( DWORD dwState ); + void setServiceFlags(QtServiceBase::ServiceFlags flags); + DWORD serviceFlags(QtServiceBase::ServiceFlags flags) const; + inline bool available() const; + static void WINAPI serviceMain( DWORD dwArgc, wchar_t** lpszArgv ); + static void WINAPI handler( DWORD dwOpcode ); + + SERVICE_STATUS status; + SERVICE_STATUS_HANDLE serviceStatus; + QStringList serviceArgs; + + static QtServiceSysPrivate *instance; +#if QT_VERSION < 0x050000 + static QCoreApplication::EventFilter nextFilter; +#endif + + QWaitCondition condition; + QMutex mutex; + QSemaphore startSemaphore; + QSemaphore startSemaphore2; + + QtServiceControllerHandler *controllerHandler; + + void handleCustomEvent(QEvent *e); +}; + +QtServiceControllerHandler::QtServiceControllerHandler(QtServiceSysPrivate *sys) + : QObject(), d_sys(sys) +{ + +} + +void QtServiceControllerHandler::customEvent(QEvent *e) +{ + d_sys->handleCustomEvent(e); +} + + +QtServiceSysPrivate *QtServiceSysPrivate::instance = 0; +#if QT_VERSION < 0x050000 +QCoreApplication::EventFilter QtServiceSysPrivate::nextFilter = 0; +#endif + +QtServiceSysPrivate::QtServiceSysPrivate() +{ + instance = this; +} + +inline bool QtServiceSysPrivate::available() const +{ + return 0 != pOpenSCManager; +} + +void WINAPI QtServiceSysPrivate::serviceMain(DWORD dwArgc, wchar_t** lpszArgv) +{ + if (!instance || !QtServiceBase::instance()) + return; + + // Windows spins off a random thread to call this function on + // startup, so here we just signal to the QApplication event loop + // in the main thread to go ahead with start()'ing the service. + + for (DWORD i = 0; i < dwArgc; i++) + instance->serviceArgs.append(QString::fromUtf16((unsigned short*)lpszArgv[i])); + + instance->startSemaphore.release(); // let the qapp creation start + instance->startSemaphore2.acquire(); // wait until its done + // Register the control request handler + instance->serviceStatus = pRegisterServiceCtrlHandler((TCHAR*)QtServiceBase::instance()->serviceName().utf16(), handler); + + if (!instance->serviceStatus) // cannot happen - something is utterly wrong + return; + + handler(QTSERVICE_STARTUP); // Signal startup to the application - + // causes QtServiceBase::start() to be called in the main thread + + // The MSDN doc says that this thread should just exit - the service is + // running in the main thread (here, via callbacks in the handler thread). +} + + +// The handler() is called from the thread that called +// StartServiceCtrlDispatcher, i.e. our HandlerThread, and +// not from the main thread that runs the event loop, so we +// have to post an event to ourselves, and use a QWaitCondition +// and a QMutex to synchronize. +void QtServiceSysPrivate::handleCustomEvent(QEvent *e) +{ + int code = e->type() - QEvent::User; + + switch(code) { + case QTSERVICE_STARTUP: // Startup + QtServiceBase::instance()->start(); + break; + case SERVICE_CONTROL_STOP: + QtServiceBase::instance()->stop(); + QCoreApplication::instance()->quit(); + break; + case SERVICE_CONTROL_PAUSE: + QtServiceBase::instance()->pause(); + break; + case SERVICE_CONTROL_CONTINUE: + QtServiceBase::instance()->resume(); + break; + default: + if (code >= 128 && code <= 255) + QtServiceBase::instance()->processCommand(code - 128); + break; + } + + mutex.lock(); + condition.wakeAll(); + mutex.unlock(); +} + +void WINAPI QtServiceSysPrivate::handler( DWORD code ) +{ + if (!instance) + return; + + instance->mutex.lock(); + switch (code) { + case QTSERVICE_STARTUP: // QtService startup (called from WinMain when started) + instance->setStatus(SERVICE_START_PENDING); + QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); + instance->condition.wait(&instance->mutex); + instance->setStatus(SERVICE_RUNNING); + break; + case SERVICE_CONTROL_STOP: // 1 + instance->setStatus(SERVICE_STOP_PENDING); + QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); + instance->condition.wait(&instance->mutex); + // status will be reported as stopped by start() when qapp::exec returns + break; + + case SERVICE_CONTROL_PAUSE: // 2 + instance->setStatus(SERVICE_PAUSE_PENDING); + QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); + instance->condition.wait(&instance->mutex); + instance->setStatus(SERVICE_PAUSED); + break; + + case SERVICE_CONTROL_CONTINUE: // 3 + instance->setStatus(SERVICE_CONTINUE_PENDING); + QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); + instance->condition.wait(&instance->mutex); + instance->setStatus(SERVICE_RUNNING); + break; + + case SERVICE_CONTROL_INTERROGATE: // 4 + break; + + case SERVICE_CONTROL_SHUTDOWN: // 5 + // Don't waste time with reporting stop pending, just do it + QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + SERVICE_CONTROL_STOP))); + instance->condition.wait(&instance->mutex); + // status will be reported as stopped by start() when qapp::exec returns + break; + + default: + if ( code >= 128 && code <= 255 ) { + QCoreApplication::postEvent(instance->controllerHandler, new QEvent(QEvent::Type(QEvent::User + code))); + instance->condition.wait(&instance->mutex); + } + break; + } + + instance->mutex.unlock(); + + // Report current status + if (instance->available() && instance->status.dwCurrentState != SERVICE_STOPPED) + pSetServiceStatus(instance->serviceStatus, &instance->status); +} + +void QtServiceSysPrivate::setStatus(DWORD state) +{ + if (!available()) + return; + status.dwCurrentState = state; + pSetServiceStatus(serviceStatus, &status); +} + +void QtServiceSysPrivate::setServiceFlags(QtServiceBase::ServiceFlags flags) +{ + if (!available()) + return; + status.dwControlsAccepted = serviceFlags(flags); + pSetServiceStatus(serviceStatus, &status); +} + +DWORD QtServiceSysPrivate::serviceFlags(QtServiceBase::ServiceFlags flags) const +{ + DWORD control = 0; + if (flags & QtServiceBase::CanBeSuspended) + control |= SERVICE_ACCEPT_PAUSE_CONTINUE; + if (!(flags & QtServiceBase::CannotBeStopped)) + control |= SERVICE_ACCEPT_STOP; + if (flags & QtServiceBase::NeedsStopOnShutdown) + control |= SERVICE_ACCEPT_SHUTDOWN; + + return control; +} + +#include "qtservice_win.moc" + + +class HandlerThread : public QThread +{ +public: + HandlerThread() + : success(true), console(false), QThread() + {} + + bool calledOk() { return success; } + bool runningAsConsole() { return console; } + +protected: + bool success, console; + void run() + { + SERVICE_TABLE_ENTRYW st [2]; + st[0].lpServiceName = (wchar_t*)QtServiceBase::instance()->serviceName().utf16(); + st[0].lpServiceProc = QtServiceSysPrivate::serviceMain; + st[1].lpServiceName = 0; + st[1].lpServiceProc = 0; + + success = (pStartServiceCtrlDispatcher(st) != 0); // should block + + if (!success) { + if (GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) { + // Means we're started from console, not from service mgr + // start() will ask the mgr to start another instance of us as a service instead + console = true; + } + else { + QtServiceBase::instance()->logMessage(QString("The Service failed to start [%1]").arg(qt_error_string(GetLastError())), QtServiceBase::Error); + } + QtServiceSysPrivate::instance->startSemaphore.release(); // let start() continue, since serviceMain won't be doing it + } + } +}; + +/* + Ignore WM_ENDSESSION system events, since they make the Qt kernel quit +*/ + +#if QT_VERSION >= 0x050000 + +class QtServiceAppEventFilter : public QAbstractNativeEventFilter +{ +public: + QtServiceAppEventFilter() {} + bool nativeEventFilter(const QByteArray &eventType, void *message, long *result); +}; + +bool QtServiceAppEventFilter::nativeEventFilter(const QByteArray &, void *message, long *result) +{ + MSG *winMessage = (MSG*)message; + if (winMessage->message == WM_ENDSESSION && (winMessage->lParam & ENDSESSION_LOGOFF)) { + *result = TRUE; + return true; + } + return false; +} + +Q_GLOBAL_STATIC(QtServiceAppEventFilter, qtServiceAppEventFilter) + +#else + +bool myEventFilter(void* message, long* result) +{ + MSG* msg = reinterpret_cast(message); + if (!msg || (msg->message != WM_ENDSESSION) || !(msg->lParam & ENDSESSION_LOGOFF)) + return QtServiceSysPrivate::nextFilter ? QtServiceSysPrivate::nextFilter(message, result) : false; + + if (QtServiceSysPrivate::nextFilter) + QtServiceSysPrivate::nextFilter(message, result); + if (result) + *result = TRUE; + return true; +} + +#endif + +/* There are three ways we can be started: + + - By a service controller (e.g. the Services control panel), with + no (service-specific) arguments. ServiceBase::exec() will then call + start() below, and the service will start. + + - From the console, but with no (service-specific) arguments. This + means we should ask a controller to start the service (i.e. another + instance of this executable), and then just terminate. We discover + this case (as different from the above) by the fact that + StartServiceCtrlDispatcher will return an error, instead of blocking. + + - From the console, with -e(xec) argument. ServiceBase::exec() will + then call ServiceBasePrivate::exec(), which calls + ServiceBasePrivate::run(), which runs the application as a normal + program. +*/ + +bool QtServiceBasePrivate::start() +{ + sysInit(); + if (!winServiceInit()) + return false; + + // Since StartServiceCtrlDispatcher() blocks waiting for service + // control events, we need to call it in another thread, so that + // the main thread can run the QApplication event loop. + HandlerThread* ht = new HandlerThread(); + ht->start(); + + QtServiceSysPrivate* sys = QtServiceSysPrivate::instance; + + // Wait until service args have been received by serviceMain. + // If Windows doesn't call serviceMain (or + // StartServiceControlDispatcher doesn't return an error) within + // a timeout of 20 secs, something is very wrong; give up + if (!sys->startSemaphore.tryAcquire(1, 20000)) + return false; + + if (!ht->calledOk()) { + if (ht->runningAsConsole()) + return controller.start(args.mid(1)); + else + return false; + } + + int argc = sys->serviceArgs.size(); + QVector argv(argc); + QList argvData; + for (int i = 0; i < argc; ++i) + argvData.append(sys->serviceArgs.at(i).toLocal8Bit()); + for (int i = 0; i < argc; ++i) + argv[i] = argvData[i].data(); + + q_ptr->createApplication(argc, argv.data()); + QCoreApplication *app = QCoreApplication::instance(); + if (!app) + return false; + +#if QT_VERSION >= 0x050000 + QAbstractEventDispatcher::instance()->installNativeEventFilter(qtServiceAppEventFilter()); +#else + QtServiceSysPrivate::nextFilter = app->setEventFilter(myEventFilter); +#endif + + sys->controllerHandler = new QtServiceControllerHandler(sys); + + sys->startSemaphore2.release(); // let serviceMain continue (and end) + + sys->status.dwWin32ExitCode = q_ptr->executeApplication(); + sys->setStatus(SERVICE_STOPPED); + + if (ht->isRunning()) + ht->wait(1000); // let the handler thread finish + delete sys->controllerHandler; + sys->controllerHandler = 0; + if (ht->isFinished()) + delete ht; + delete app; + sysCleanup(); + return true; +} + +bool QtServiceBasePrivate::install(const QString &account, const QString &password) +{ + bool result = false; + if (!winServiceInit()) + return result; + + // Open the Service Control Manager + SC_HANDLE hSCM = pOpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS); + if (hSCM) { + QString acc = account; + DWORD dwStartType = startupType == QtServiceController::AutoStartup ? SERVICE_AUTO_START : SERVICE_DEMAND_START; + DWORD dwServiceType = SERVICE_WIN32_OWN_PROCESS; + wchar_t *act = 0; + wchar_t *pwd = 0; + if (!acc.isEmpty()) { + // The act string must contain a string of the format "Domain\UserName", + // so if only a username was specified without a domain, default to the local machine domain. + if (!acc.contains(QChar('\\'))) { + acc.prepend(QLatin1String(".\\")); + } + if (!acc.endsWith(QLatin1String("\\LocalSystem"))) + act = (wchar_t*)acc.utf16(); + } + if (!password.isEmpty() && act) { + pwd = (wchar_t*)password.utf16(); + } + + // Only set INTERACTIVE if act is LocalSystem. (and act should be 0 if it is LocalSystem). + if (!act) dwServiceType |= SERVICE_INTERACTIVE_PROCESS; + + // Create the service + SC_HANDLE hService = pCreateService(hSCM, (wchar_t *)controller.serviceName().utf16(), + (wchar_t *)controller.serviceName().utf16(), + SERVICE_ALL_ACCESS, + dwServiceType, // QObject::inherits ( const char * className ) for no inter active ???? + dwStartType, SERVICE_ERROR_NORMAL, (wchar_t *)filePath().utf16(), + 0, 0, 0, + act, pwd); + if (hService) { + result = true; + if (!serviceDescription.isEmpty()) { + SERVICE_DESCRIPTION sdesc; + sdesc.lpDescription = (wchar_t *)serviceDescription.utf16(); + pChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sdesc); + } + pCloseServiceHandle(hService); + } + pCloseServiceHandle(hSCM); + } + return result; +} + +QString QtServiceBasePrivate::filePath() const +{ + wchar_t path[_MAX_PATH]; + ::GetModuleFileNameW( 0, path, sizeof(path) ); + return QString::fromUtf16((unsigned short*)path); +} + +bool QtServiceBasePrivate::sysInit() +{ + sysd = new QtServiceSysPrivate(); + + sysd->serviceStatus = 0; + sysd->status.dwServiceType = SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS; + sysd->status.dwCurrentState = SERVICE_STOPPED; + sysd->status.dwControlsAccepted = sysd->serviceFlags(serviceFlags); + sysd->status.dwWin32ExitCode = NO_ERROR; + sysd->status.dwServiceSpecificExitCode = 0; + sysd->status.dwCheckPoint = 0; + sysd->status.dwWaitHint = 0; + + return true; +} + +void QtServiceBasePrivate::sysSetPath() +{ + +} + +void QtServiceBasePrivate::sysCleanup() +{ + if (sysd) { + delete sysd; + sysd = 0; + } +} + +void QtServiceBase::setServiceFlags(QtServiceBase::ServiceFlags flags) +{ + if (d_ptr->serviceFlags == flags) + return; + d_ptr->serviceFlags = flags; + if (d_ptr->sysd) + d_ptr->sysd->setServiceFlags(flags); +} + + diff --git a/src/qtservice/src/qtunixserversocket.cpp b/src/qtservice/src/qtunixserversocket.cpp new file mode 100644 index 0000000..0ad9134 --- /dev/null +++ b/src/qtservice/src/qtunixserversocket.cpp @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qtunixserversocket.h" +#include +#include +#include +#include +#include + +#ifndef SUN_LEN +#define SUN_LEN(ptr) ((size_t)(((struct sockaddr_un *) 0)->sun_path) \ + +strlen ((ptr)->sun_path)) +#endif + +QtUnixServerSocket::QtUnixServerSocket(const QString &path, QObject *parent) + : QTcpServer(parent) +{ + setPath(path); +} + +QtUnixServerSocket::QtUnixServerSocket(QObject *parent) + : QTcpServer(parent) +{ +} + +void QtUnixServerSocket::setPath(const QString &path) +{ + path_.clear(); + + int sock = ::socket(PF_UNIX, SOCK_STREAM, 0); + if (sock != -1) { + struct sockaddr_un addr; + ::memset(&addr, 0, sizeof(struct sockaddr_un)); + addr.sun_family = AF_UNIX; + ::unlink(path.toLatin1().constData()); // ### This might need to be changed + unsigned int pathlen = strlen(path.toLatin1().constData()); + if (pathlen > sizeof(addr.sun_path)) pathlen = sizeof(addr.sun_path); + ::memcpy(addr.sun_path, path.toLatin1().constData(), pathlen); + if ((::bind(sock, (struct sockaddr *)&addr, SUN_LEN(&addr)) != -1) && + (::listen(sock, 5) != -1)) { + setSocketDescriptor(sock); + path_ = path; + } + } +} + +void QtUnixServerSocket::close() +{ + QTcpServer::close(); + if (!path_.isEmpty()) { + ::unlink(path_.toLatin1().constData()); + path_.clear(); + } +} diff --git a/src/qtservice/src/qtunixserversocket.h b/src/qtservice/src/qtunixserversocket.h new file mode 100644 index 0000000..1fc8b70 --- /dev/null +++ b/src/qtservice/src/qtunixserversocket.h @@ -0,0 +1,61 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTUNIXSERVERSOCKET_H +#define QTUNIXSERVERSOCKET_H + +#include + +class QtUnixServerSocket : public QTcpServer +{ + Q_OBJECT +public: + QtUnixServerSocket(const QString &path, QObject *parent = 0); + QtUnixServerSocket(QObject *parent = 0); + + void setPath(const QString &path); + void close(); + +private: + QString path_; +}; + + +#endif diff --git a/src/qtservice/src/qtunixsocket.cpp b/src/qtservice/src/qtunixsocket.cpp new file mode 100644 index 0000000..f6d4c97 --- /dev/null +++ b/src/qtservice/src/qtunixsocket.cpp @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qtunixsocket.h" +#include +#include +#include +#include +#include + +#ifndef SUN_LEN +#define SUN_LEN(ptr) ((size_t)(((struct sockaddr_un *) 0)->sun_path) \ + +strlen ((ptr)->sun_path)) +#endif + +QtUnixSocket::QtUnixSocket(QObject *parent) + : QTcpSocket(parent) +{ +} + +bool QtUnixSocket::connectTo(const QString &path) +{ + bool ret = false; + int sock = ::socket(PF_UNIX, SOCK_STREAM, 0); + if (sock != -1) { + struct sockaddr_un addr; + ::memset(&addr, 0, sizeof(struct sockaddr_un)); + addr.sun_family = AF_UNIX; + size_t pathlen = strlen(path.toLatin1().constData()); + pathlen = qMin(pathlen, sizeof(addr.sun_path)); + ::memcpy(addr.sun_path, path.toLatin1().constData(), pathlen); + int err = ::connect(sock, (struct sockaddr *)&addr, SUN_LEN(&addr)); + if (err != -1) { + setSocketDescriptor(sock); + ret = true; + } else { + ::close(sock); + } + } + return ret; +} diff --git a/src/qtservice/src/qtunixsocket.h b/src/qtservice/src/qtunixsocket.h new file mode 100644 index 0000000..1d34fba --- /dev/null +++ b/src/qtservice/src/qtunixsocket.h @@ -0,0 +1,55 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTUNIXSOCKET_H +#define QTUNIXSOCKET_H + +#include + +class QtUnixSocket : public QTcpSocket +{ + Q_OBJECT +public: + QtUnixSocket(QObject *parent = 0); + + bool connectTo(const QString &path); +}; + +#endif -- libgit2 0.21.2