1 /****************************************************************************
2 **
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the Qt Solutions component.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
10 **
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
13 ** met:
14 ** * Redistributions of source code must retain the above copyright
15 ** notice, this list of conditions and the following disclaimer.
16 ** * Redistributions in binary form must reproduce the above copyright
17 ** notice, this list of conditions and the following disclaimer in
18 ** the documentation and/or other materials provided with the
19 ** distribution.
20 ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
21 ** of its contributors may be used to endorse or promote products derived
22 ** from this software without specific prior written permission.
23 **
24 **
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40
41 #include "qtservice.h"
42 #include "qtservice_p.h"
43 #include "qtunixsocket.h"
44 #include "qtunixserversocket.h"
45 #include <QCoreApplication>
46 #include <QStringList>
47 #include <QFile>
48 #include <QTimer>
49 #include <QDir>
50 #include <pwd.h>
51 #include <fcntl.h>
52 #include <unistd.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <syslog.h>
56 #include <signal.h>
57 #include <sys/stat.h>
58 #include <QMap>
59 #include <QSettings>
60 #include <QProcess>
61
encodeName(const QString & name,bool allowUpper=false)62 static QString encodeName(const QString &name, bool allowUpper = false)
63 {
64 QString n = name.toLower();
65 QString legal = QLatin1String("abcdefghijklmnopqrstuvwxyz1234567890");
66 if (allowUpper)
67 legal += QLatin1String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
68 int pos = 0;
69 while (pos < n.size()) {
70 if (legal.indexOf(n[pos]) == -1)
71 n.remove(pos, 1);
72 else
73 ++pos;
74 }
75 return n;
76 }
77
login()78 static QString login()
79 {
80 QString l;
81 uid_t uid = getuid();
82 passwd *pw = getpwuid(uid);
83 if (pw)
84 l = QString(pw->pw_name);
85 return l;
86 }
87
socketPath(const QString & serviceName)88 static QString socketPath(const QString &serviceName)
89 {
90 QString sn = encodeName(serviceName);
91 return QString(QLatin1String("/var/tmp/") + sn + QLatin1String(".") + login());
92 }
93
sendCmd(const QString & serviceName,const QString & cmd)94 static bool sendCmd(const QString &serviceName, const QString &cmd)
95 {
96 bool retValue = false;
97 QtUnixSocket sock;
98 if (sock.connectTo(socketPath(serviceName))) {
99 sock.write(QString(cmd+"\r\n").toLatin1().constData());
100 sock.flush();
101 sock.waitForReadyRead(-1);
102 QString reply = sock.readAll();
103 if (reply == QLatin1String("true"))
104 retValue = true;
105 sock.close();
106 }
107 return retValue;
108 }
109
absPath(const QString & path)110 static QString absPath(const QString &path)
111 {
112 QString ret;
113 if (path[0] != QChar('/')) { // Not an absolute path
114 int slashpos;
115 if ((slashpos = path.lastIndexOf('/')) != -1) { // Relative path
116 QDir dir = QDir::current();
117 dir.cd(path.left(slashpos));
118 ret = dir.absolutePath();
119 } else { // Need to search $PATH
120 char *envPath = ::getenv("PATH");
121 if (envPath) {
122 QStringList envPaths = QString::fromLocal8Bit(envPath).split(':');
123 for (int i = 0; i < envPaths.size(); ++i) {
124 if (QFile::exists(envPaths.at(i) + QLatin1String("/") + QString(path))) {
125 QDir dir(envPaths.at(i));
126 ret = dir.absolutePath();
127 break;
128 }
129 }
130 }
131 }
132 } else {
133 QFileInfo fi(path);
134 ret = fi.absolutePath();
135 }
136 return ret;
137 }
138
filePath() const139 QString QtServiceBasePrivate::filePath() const
140 {
141 QString ret;
142 if (args.isEmpty())
143 return ret;
144 QFileInfo fi(args[0]);
145 QDir dir(absPath(args[0]));
146 return dir.absoluteFilePath(fi.fileName());
147 }
148
149
serviceDescription() const150 QString QtServiceController::serviceDescription() const
151 {
152 QSettings settings(QSettings::SystemScope, "QtSoftware");
153 settings.beginGroup("services");
154 settings.beginGroup(serviceName());
155
156 QString desc = settings.value("description").toString();
157
158 settings.endGroup();
159 settings.endGroup();
160
161 return desc;
162 }
163
startupType() const164 QtServiceController::StartupType QtServiceController::startupType() const
165 {
166 QSettings settings(QSettings::SystemScope, "QtSoftware");
167 settings.beginGroup("services");
168 settings.beginGroup(serviceName());
169
170 StartupType startupType = (StartupType)settings.value("startupType").toInt();
171
172 settings.endGroup();
173 settings.endGroup();
174
175 return startupType;
176 }
177
serviceFilePath() const178 QString QtServiceController::serviceFilePath() const
179 {
180 QSettings settings(QSettings::SystemScope, "QtSoftware");
181 settings.beginGroup("services");
182 settings.beginGroup(serviceName());
183
184 QString path = settings.value("path").toString();
185
186 settings.endGroup();
187 settings.endGroup();
188
189 return path;
190 }
191
uninstall()192 bool QtServiceController::uninstall()
193 {
194 QSettings settings(QSettings::SystemScope, "QtSoftware");
195 settings.beginGroup("services");
196
197 settings.remove(serviceName());
198
199 settings.endGroup();
200 settings.sync();
201
202 QSettings::Status ret = settings.status();
203 if (ret == QSettings::AccessError) {
204 fprintf(stderr, "Cannot uninstall \"%s\". Cannot write to: %s. Check permissions.\n",
205 serviceName().toLatin1().constData(),
206 settings.fileName().toLatin1().constData());
207 }
208 return (ret == QSettings::NoError);
209 }
210
211
start(const QStringList & arguments)212 bool QtServiceController::start(const QStringList &arguments)
213 {
214 if (!isInstalled())
215 return false;
216 if (isRunning())
217 return false;
218 return QProcess::startDetached(serviceFilePath(), arguments);
219 }
220
stop()221 bool QtServiceController::stop()
222 {
223 return sendCmd(serviceName(), QLatin1String("terminate"));
224 }
225
pause()226 bool QtServiceController::pause()
227 {
228 return sendCmd(serviceName(), QLatin1String("pause"));
229 }
230
resume()231 bool QtServiceController::resume()
232 {
233 return sendCmd(serviceName(), QLatin1String("resume"));
234 }
235
sendCommand(int code)236 bool QtServiceController::sendCommand(int code)
237 {
238 return sendCmd(serviceName(), QString(QLatin1String("num:") + QString::number(code)));
239 }
240
isInstalled() const241 bool QtServiceController::isInstalled() const
242 {
243 QSettings settings(QSettings::SystemScope, "QtSoftware");
244 settings.beginGroup("services");
245
246 QStringList list = settings.childGroups();
247
248 settings.endGroup();
249
250 QStringListIterator it(list);
251 while (it.hasNext()) {
252 if (it.next() == serviceName())
253 return true;
254 }
255
256 return false;
257 }
258
isRunning() const259 bool QtServiceController::isRunning() const
260 {
261 QtUnixSocket sock;
262 if (sock.connectTo(socketPath(serviceName())))
263 return true;
264 return false;
265 }
266
267
268
269
270 ///////////////////////////////////
271
272 class QtServiceSysPrivate : public QtUnixServerSocket
273 {
274 Q_OBJECT
275 public:
276 QtServiceSysPrivate();
277 ~QtServiceSysPrivate();
278
279 char *ident;
280
281 QtServiceBase::ServiceFlags serviceFlags;
282
283 protected:
284 #if QT_VERSION >= 0x050000
285 void incomingConnection(qintptr socketDescriptor);
286 #else
287 void incomingConnection(int socketDescriptor);
288 #endif
289
290 private slots:
291 void slotReady();
292 void slotClosed();
293
294 private:
295 QString getCommand(const QTcpSocket *socket);
296 QMap<const QTcpSocket *, QString> cache;
297 };
298
QtServiceSysPrivate()299 QtServiceSysPrivate::QtServiceSysPrivate()
300 : QtUnixServerSocket(), ident(0), serviceFlags(0)
301 {
302 }
303
~QtServiceSysPrivate()304 QtServiceSysPrivate::~QtServiceSysPrivate()
305 {
306 if (ident)
307 delete[] ident;
308 }
309
310 #if QT_VERSION >= 0x050000
incomingConnection(qintptr socketDescriptor)311 void QtServiceSysPrivate::incomingConnection(qintptr socketDescriptor)
312 #else
313 void QtServiceSysPrivate::incomingConnection(int socketDescriptor)
314 #endif
315 {
316 QTcpSocket *s = new QTcpSocket(this);
317 s->setSocketDescriptor(socketDescriptor);
318 connect(s, SIGNAL(readyRead()), this, SLOT(slotReady()));
319 connect(s, SIGNAL(disconnected()), this, SLOT(slotClosed()));
320 }
321
slotReady()322 void QtServiceSysPrivate::slotReady()
323 {
324 QTcpSocket *s = (QTcpSocket *)sender();
325 cache[s] += QString(s->readAll());
326 QString cmd = getCommand(s);
327 while (!cmd.isEmpty()) {
328 bool retValue = false;
329 if (cmd == QLatin1String("terminate")) {
330 if (!(serviceFlags & QtServiceBase::CannotBeStopped)) {
331 QtServiceBase::instance()->stop();
332 QCoreApplication::instance()->quit();
333 retValue = true;
334 }
335 } else if (cmd == QLatin1String("pause")) {
336 if (serviceFlags & QtServiceBase::CanBeSuspended) {
337 QtServiceBase::instance()->pause();
338 retValue = true;
339 }
340 } else if (cmd == QLatin1String("resume")) {
341 if (serviceFlags & QtServiceBase::CanBeSuspended) {
342 QtServiceBase::instance()->resume();
343 retValue = true;
344 }
345 } else if (cmd == QLatin1String("alive")) {
346 retValue = true;
347 } else if (cmd.length() > 4 && cmd.left(4) == QLatin1String("num:")) {
348 cmd = cmd.mid(4);
349 QtServiceBase::instance()->processCommand(cmd.toInt());
350 retValue = true;
351 }
352 QString retString;
353 if (retValue)
354 retString = QLatin1String("true");
355 else
356 retString = QLatin1String("false");
357 s->write(retString.toLatin1().constData());
358 s->flush();
359 cmd = getCommand(s);
360 }
361 }
362
slotClosed()363 void QtServiceSysPrivate::slotClosed()
364 {
365 QTcpSocket *s = (QTcpSocket *)sender();
366 s->deleteLater();
367 }
368
getCommand(const QTcpSocket * socket)369 QString QtServiceSysPrivate::getCommand(const QTcpSocket *socket)
370 {
371 int pos = cache[socket].indexOf("\r\n");
372 if (pos >= 0) {
373 QString ret = cache[socket].left(pos);
374 cache[socket].remove(0, pos+2);
375 return ret;
376 }
377 return "";
378 }
379
380 #include "qtservice_unix.moc"
381
sysInit()382 bool QtServiceBasePrivate::sysInit()
383 {
384 sysd = new QtServiceSysPrivate;
385 sysd->serviceFlags = serviceFlags;
386 // Restrict permissions on files that are created by the service
387 ::umask(027);
388
389 return true;
390 }
391
sysSetPath()392 void QtServiceBasePrivate::sysSetPath()
393 {
394 if (sysd)
395 sysd->setPath(socketPath(controller.serviceName()));
396 }
397
sysCleanup()398 void QtServiceBasePrivate::sysCleanup()
399 {
400 if (sysd) {
401 sysd->close();
402 delete sysd;
403 sysd = 0;
404 }
405 }
406
start()407 bool QtServiceBasePrivate::start()
408 {
409 if (sendCmd(controller.serviceName(), "alive")) {
410 // Already running
411 return false;
412 }
413 // Could just call controller.start() here, but that would fail if
414 // we're not installed. We do not want to strictly require installation.
415 ::setenv("QTSERVICE_RUN", "1", 1); // Tell the detached process it's it
416 return QProcess::startDetached(filePath(), args.mid(1), "/");
417 }
418
install(const QString & account,const QString & password)419 bool QtServiceBasePrivate::install(const QString &account, const QString &password)
420 {
421 Q_UNUSED(account)
422 Q_UNUSED(password)
423 QSettings settings(QSettings::SystemScope, "QtSoftware");
424
425 settings.beginGroup("services");
426 settings.beginGroup(controller.serviceName());
427
428 settings.setValue("path", filePath());
429 settings.setValue("description", serviceDescription);
430 settings.setValue("automaticStartup", startupType);
431
432 settings.endGroup();
433 settings.endGroup();
434 settings.sync();
435
436 QSettings::Status ret = settings.status();
437 if (ret == QSettings::AccessError) {
438 fprintf(stderr, "Cannot install \"%s\". Cannot write to: %s. Check permissions.\n",
439 controller.serviceName().toLatin1().constData(),
440 settings.fileName().toLatin1().constData());
441 }
442 return (ret == QSettings::NoError);
443 }
444
logMessage(const QString & message,QtServiceBase::MessageType type,int,uint,const QByteArray &)445 void QtServiceBase::logMessage(const QString &message, QtServiceBase::MessageType type,
446 int, uint, const QByteArray &)
447 {
448 if (!d_ptr->sysd)
449 return;
450 int st;
451 switch(type) {
452 case QtServiceBase::Error:
453 st = LOG_ERR;
454 break;
455 case QtServiceBase::Warning:
456 st = LOG_WARNING;
457 break;
458 default:
459 st = LOG_INFO;
460 }
461 if (!d_ptr->sysd->ident) {
462 QString tmp = encodeName(serviceName(), true);
463 int len = tmp.toLocal8Bit().size();
464 d_ptr->sysd->ident = new char[len+1];
465 d_ptr->sysd->ident[len] = '\0';
466 ::memcpy(d_ptr->sysd->ident, tmp.toLocal8Bit().constData(), len);
467 }
468 openlog(d_ptr->sysd->ident, LOG_PID, LOG_DAEMON);
469 foreach(QString line, message.split('\n'))
470 syslog(st, "%s", line.toLocal8Bit().constData());
471 closelog();
472 }
473
setServiceFlags(QtServiceBase::ServiceFlags flags)474 void QtServiceBase::setServiceFlags(QtServiceBase::ServiceFlags flags)
475 {
476 if (d_ptr->serviceFlags == flags)
477 return;
478 d_ptr->serviceFlags = flags;
479 if (d_ptr->sysd)
480 d_ptr->sysd->serviceFlags = flags;
481 }
482
483