QtWebApp
qtservice_unix.cpp
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 
63 #if QT_VERSION >= 0x050000
64  typedef qintptr tSocketDescriptor;
65 #else
66  typedef int tSocketDescriptor;
67  #define Q_DECL_OVERRIDE
68 #endif
69 
70 static QString encodeName(const QString &name, bool allowUpper = false)
71 {
72  QString n = name.toLower();
73  QString legal = QLatin1String("abcdefghijklmnopqrstuvwxyz1234567890");
74  if (allowUpper)
75  legal += QLatin1String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
76  int pos = 0;
77  while (pos < n.size()) {
78  if (legal.indexOf(n[pos]) == -1)
79  n.remove(pos, 1);
80  else
81  ++pos;
82  }
83  return n;
84 }
85 
86 static QString login()
87 {
88  QString l;
89  uid_t uid = getuid();
90  passwd *pw = getpwuid(uid);
91  if (pw)
92  l = QString(pw->pw_name);
93  return l;
94 }
95 
96 static QString socketPath(const QString &serviceName)
97 {
98  QString sn = encodeName(serviceName);
99  return QString(QLatin1String("/var/tmp/") + sn + QLatin1String(".") + login());
100 }
101 
102 static bool sendCmd(const QString &serviceName, const QString &cmd)
103 {
104  bool retValue = false;
105  QtUnixSocket sock;
106  if (sock.connectTo(socketPath(serviceName))) {
107  sock.write(QString(cmd+"\r\n").toLatin1().constData());
108  sock.flush();
109  sock.waitForReadyRead(-1);
110  QString reply = sock.readAll();
111  if (reply == QLatin1String("true"))
112  retValue = true;
113  sock.close();
114  }
115  return retValue;
116 }
117 
118 static QString absPath(const QString &path)
119 {
120  QString ret;
121  if (path[0] != QChar('/')) { // Not an absolute path
122  int slashpos;
123  if ((slashpos = path.lastIndexOf('/')) != -1) { // Relative path
124  QDir dir = QDir::current();
125  dir.cd(path.left(slashpos));
126  ret = dir.absolutePath();
127  } else { // Need to search $PATH
128  char *envPath = ::getenv("PATH");
129  if (envPath) {
130  QStringList envPaths = QString::fromLocal8Bit(envPath).split(':');
131  for (int i = 0; i < envPaths.size(); ++i) {
132  if (QFile::exists(envPaths.at(i) + QLatin1String("/") + QString(path))) {
133  QDir dir(envPaths.at(i));
134  ret = dir.absolutePath();
135  break;
136  }
137  }
138  }
139  }
140  } else {
141  QFileInfo fi(path);
142  ret = fi.absolutePath();
143  }
144  return ret;
145 }
146 
147 QString QtServiceBasePrivate::filePath() const
148 {
149  QString ret;
150  if (args.isEmpty())
151  return ret;
152  QFileInfo fi(args[0]);
153  QDir dir(absPath(args[0]));
154  return dir.absoluteFilePath(fi.fileName());
155 }
156 
157 
159 {
160  QSettings settings(QSettings::SystemScope, "QtSoftware");
161  settings.beginGroup("services");
162  settings.beginGroup(serviceName());
163 
164  QString desc = settings.value("description").toString();
165 
166  settings.endGroup();
167  settings.endGroup();
168 
169  return desc;
170 }
171 
173 {
174  QSettings settings(QSettings::SystemScope, "QtSoftware");
175  settings.beginGroup("services");
176  settings.beginGroup(serviceName());
177 
178  StartupType startupType = (StartupType)settings.value("startupType").toInt();
179 
180  settings.endGroup();
181  settings.endGroup();
182 
183  return startupType;
184 }
185 
187 {
188  QSettings settings(QSettings::SystemScope, "QtSoftware");
189  settings.beginGroup("services");
190  settings.beginGroup(serviceName());
191 
192  QString path = settings.value("path").toString();
193 
194  settings.endGroup();
195  settings.endGroup();
196 
197  return path;
198 }
199 
201 {
202  QSettings settings(QSettings::SystemScope, "QtSoftware");
203  settings.beginGroup("services");
204 
205  settings.remove(serviceName());
206 
207  settings.endGroup();
208  settings.sync();
209 
210  QSettings::Status ret = settings.status();
211  if (ret == QSettings::AccessError) {
212  fprintf(stderr, "Cannot uninstall \"%s\". Cannot write to: %s. Check permissions.\n",
213  serviceName().toLatin1().constData(),
214  settings.fileName().toLatin1().constData());
215  }
216  return (ret == QSettings::NoError);
217 }
218 
219 
220 bool QtServiceController::start(const QStringList &arguments)
221 {
222  if (!isInstalled())
223  return false;
224  if (isRunning())
225  return false;
226  return QProcess::startDetached(serviceFilePath(), arguments);
227 }
228 
230 {
231  return sendCmd(serviceName(), QLatin1String("terminate"));
232 }
233 
235 {
236  return sendCmd(serviceName(), QLatin1String("pause"));
237 }
238 
240 {
241  return sendCmd(serviceName(), QLatin1String("resume"));
242 }
243 
245 {
246  return sendCmd(serviceName(), QString(QLatin1String("num:") + QString::number(code)));
247 }
248 
250 {
251  QSettings settings(QSettings::SystemScope, "QtSoftware");
252  settings.beginGroup("services");
253 
254  QStringList list = settings.childGroups();
255 
256  settings.endGroup();
257 
258  QStringListIterator it(list);
259  while (it.hasNext()) {
260  if (it.next() == serviceName())
261  return true;
262  }
263 
264  return false;
265 }
266 
268 {
269  QtUnixSocket sock;
270  if (sock.connectTo(socketPath(serviceName())))
271  return true;
272  return false;
273 }
274 
275 
276 
277 
279 
281 {
282  Q_OBJECT
283 public:
286 
287  char *ident;
288 
289  QtServiceBase::ServiceFlags serviceFlags;
290 
291 protected:
292  void incomingConnection(tSocketDescriptor socketDescriptor) Q_DECL_OVERRIDE;
293 
294 private slots:
295  void slotReady();
296  void slotClosed();
297 
298 private:
299  QString getCommand(const QTcpSocket *socket);
300  QMap<const QTcpSocket *, QString> cache;
301 };
302 
303 QtServiceSysPrivate::QtServiceSysPrivate()
304  : QtUnixServerSocket(), ident(0), serviceFlags(0)
305 {
306 }
307 
308 QtServiceSysPrivate::~QtServiceSysPrivate()
309 {
310  if (ident)
311  delete[] ident;
312 }
313 
314 void QtServiceSysPrivate::incomingConnection(tSocketDescriptor socketDescriptor)
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 
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)) {
332  QCoreApplication::instance()->quit();
333  retValue = true;
334  }
335  } else if (cmd == QLatin1String("pause")) {
336  if (serviceFlags & QtServiceBase::CanBeSuspended) {
338  retValue = true;
339  }
340  } else if (cmd == QLatin1String("resume")) {
341  if (serviceFlags & QtServiceBase::CanBeSuspended) {
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 
363 void QtServiceSysPrivate::slotClosed()
364 {
365  QTcpSocket *s = (QTcpSocket *)sender();
366  s->deleteLater();
367 }
368 
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 
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 
392 void QtServiceBasePrivate::sysSetPath()
393 {
394  if (sysd)
395  sysd->setPath(socketPath(controller.serviceName()));
396 }
397 
398 void QtServiceBasePrivate::sysCleanup()
399 {
400  if (sysd) {
401  sysd->close();
402  delete sysd;
403  sysd = 0;
404  }
405 }
406 
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 
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 
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 
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 
QString serviceDescription() const
QString serviceFilePath() const
virtual void stop()
Definition: qtservice.cpp:902
static QtServiceBase * instance()
Definition: qtservice.cpp:870
StartupType startupType() const
bool sendCommand(int code)
void logMessage(const QString &message, MessageType type=Success, int id=0, uint category=0, const QByteArray &data=QByteArray())
void setServiceFlags(ServiceFlags flags)
virtual void processCommand(int code)
Definition: qtservice.cpp:941
virtual void resume()
Definition: qtservice.cpp:928
virtual void pause()
Definition: qtservice.cpp:915
bool isInstalled() const