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 #endif
68 
69 static QString encodeName(const QString &name, bool allowUpper = false)
70 {
71  QString n = name.toLower();
72  QString legal = QLatin1String("abcdefghijklmnopqrstuvwxyz1234567890");
73  if (allowUpper)
74  legal += QLatin1String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
75  int pos = 0;
76  while (pos < n.size()) {
77  if (legal.indexOf(n[pos]) == -1)
78  n.remove(pos, 1);
79  else
80  ++pos;
81  }
82  return n;
83 }
84 
85 static QString login()
86 {
87  QString l;
88  uid_t uid = getuid();
89  passwd *pw = getpwuid(uid);
90  if (pw)
91  l = QString(pw->pw_name);
92  return l;
93 }
94 
95 static QString socketPath(const QString &serviceName)
96 {
97  QString sn = encodeName(serviceName);
98  return QString(QLatin1String("/var/tmp/") + sn + QLatin1String(".") + login());
99 }
100 
101 static bool sendCmd(const QString &serviceName, const QString &cmd)
102 {
103  bool retValue = false;
104  QtUnixSocket sock;
105  if (sock.connectTo(socketPath(serviceName))) {
106  sock.write(QString(cmd+"\r\n").toLatin1().constData());
107  sock.flush();
108  sock.waitForReadyRead(-1);
109  QString reply = sock.readAll();
110  if (reply == QLatin1String("true"))
111  retValue = true;
112  sock.close();
113  }
114  return retValue;
115 }
116 
117 static QString absPath(const QString &path)
118 {
119  QString ret;
120  if (path[0] != QChar('/')) { // Not an absolute path
121  int slashpos;
122  if ((slashpos = path.lastIndexOf('/')) != -1) { // Relative path
123  QDir dir = QDir::current();
124  dir.cd(path.left(slashpos));
125  ret = dir.absolutePath();
126  } else { // Need to search $PATH
127  char *envPath = ::getenv("PATH");
128  if (envPath) {
129  QStringList envPaths = QString::fromLocal8Bit(envPath).split(':');
130  for (int i = 0; i < envPaths.size(); ++i) {
131  if (QFile::exists(envPaths.at(i) + QLatin1String("/") + QString(path))) {
132  QDir dir(envPaths.at(i));
133  ret = dir.absolutePath();
134  break;
135  }
136  }
137  }
138  }
139  } else {
140  QFileInfo fi(path);
141  ret = fi.absolutePath();
142  }
143  return ret;
144 }
145 
146 QString QtServiceBasePrivate::filePath() const
147 {
148  QString ret;
149  if (args.isEmpty())
150  return ret;
151  QFileInfo fi(args[0]);
152  QDir dir(absPath(args[0]));
153  return dir.absoluteFilePath(fi.fileName());
154 }
155 
156 
158 {
159  QSettings settings(QSettings::SystemScope, "QtSoftware");
160  settings.beginGroup("services");
161  settings.beginGroup(serviceName());
162 
163  QString desc = settings.value("description").toString();
164 
165  settings.endGroup();
166  settings.endGroup();
167 
168  return desc;
169 }
170 
172 {
173  QSettings settings(QSettings::SystemScope, "QtSoftware");
174  settings.beginGroup("services");
175  settings.beginGroup(serviceName());
176 
177  StartupType startupType = (StartupType)settings.value("startupType").toInt();
178 
179  settings.endGroup();
180  settings.endGroup();
181 
182  return startupType;
183 }
184 
186 {
187  QSettings settings(QSettings::SystemScope, "QtSoftware");
188  settings.beginGroup("services");
189  settings.beginGroup(serviceName());
190 
191  QString path = settings.value("path").toString();
192 
193  settings.endGroup();
194  settings.endGroup();
195 
196  return path;
197 }
198 
200 {
201  QSettings settings(QSettings::SystemScope, "QtSoftware");
202  settings.beginGroup("services");
203 
204  settings.remove(serviceName());
205 
206  settings.endGroup();
207  settings.sync();
208 
209  QSettings::Status ret = settings.status();
210  if (ret == QSettings::AccessError) {
211  fprintf(stderr, "Cannot uninstall \"%s\". Cannot write to: %s. Check permissions.\n",
212  serviceName().toLatin1().constData(),
213  settings.fileName().toLatin1().constData());
214  }
215  return (ret == QSettings::NoError);
216 }
217 
218 
219 bool QtServiceController::start(const QStringList &arguments)
220 {
221  if (!isInstalled())
222  return false;
223  if (isRunning())
224  return false;
225  return QProcess::startDetached(serviceFilePath(), arguments);
226 }
227 
229 {
230  return sendCmd(serviceName(), QLatin1String("terminate"));
231 }
232 
234 {
235  return sendCmd(serviceName(), QLatin1String("pause"));
236 }
237 
239 {
240  return sendCmd(serviceName(), QLatin1String("resume"));
241 }
242 
244 {
245  return sendCmd(serviceName(), QString(QLatin1String("num:") + QString::number(code)));
246 }
247 
249 {
250  QSettings settings(QSettings::SystemScope, "QtSoftware");
251  settings.beginGroup("services");
252 
253  QStringList list = settings.childGroups();
254 
255  settings.endGroup();
256 
257  QStringListIterator it(list);
258  while (it.hasNext()) {
259  if (it.next() == serviceName())
260  return true;
261  }
262 
263  return false;
264 }
265 
267 {
268  QtUnixSocket sock;
269  if (sock.connectTo(socketPath(serviceName())))
270  return true;
271  return false;
272 }
273 
274 
275 
276 
278 
280 {
281  Q_OBJECT
282 public:
285 
286  char *ident;
287 
288  QtServiceBase::ServiceFlags serviceFlags;
289 
290 protected:
291  void incomingConnection(tSocketDescriptor socketDescriptor) Q_DECL_OVERRIDE;
292 
293 private slots:
294  void slotReady();
295  void slotClosed();
296 
297 private:
298  QString getCommand(const QTcpSocket *socket);
299  QMap<const QTcpSocket *, QString> cache;
300 };
301 
302 QtServiceSysPrivate::QtServiceSysPrivate()
303  : QtUnixServerSocket(), ident(0), serviceFlags(0)
304 {
305 }
306 
307 QtServiceSysPrivate::~QtServiceSysPrivate()
308 {
309  if (ident)
310  delete[] ident;
311 }
312 
313 void QtServiceSysPrivate::incomingConnection(tSocketDescriptor socketDescriptor)
314 {
315  QTcpSocket *s = new QTcpSocket(this);
316  s->setSocketDescriptor(socketDescriptor);
317  connect(s, SIGNAL(readyRead()), this, SLOT(slotReady()));
318  connect(s, SIGNAL(disconnected()), this, SLOT(slotClosed()));
319 }
320 
321 void QtServiceSysPrivate::slotReady()
322 {
323  QTcpSocket *s = (QTcpSocket *)sender();
324  cache[s] += QString(s->readAll());
325  QString cmd = getCommand(s);
326  while (!cmd.isEmpty()) {
327  bool retValue = false;
328  if (cmd == QLatin1String("terminate")) {
329  if (!(serviceFlags & QtServiceBase::CannotBeStopped)) {
331  QCoreApplication::instance()->quit();
332  retValue = true;
333  }
334  } else if (cmd == QLatin1String("pause")) {
335  if (serviceFlags & QtServiceBase::CanBeSuspended) {
337  retValue = true;
338  }
339  } else if (cmd == QLatin1String("resume")) {
340  if (serviceFlags & QtServiceBase::CanBeSuspended) {
342  retValue = true;
343  }
344  } else if (cmd == QLatin1String("alive")) {
345  retValue = true;
346  } else if (cmd.length() > 4 && cmd.left(4) == QLatin1String("num:")) {
347  cmd = cmd.mid(4);
348  QtServiceBase::instance()->processCommand(cmd.toInt());
349  retValue = true;
350  }
351  QString retString;
352  if (retValue)
353  retString = QLatin1String("true");
354  else
355  retString = QLatin1String("false");
356  s->write(retString.toLatin1().constData());
357  s->flush();
358  cmd = getCommand(s);
359  }
360 }
361 
362 void QtServiceSysPrivate::slotClosed()
363 {
364  QTcpSocket *s = (QTcpSocket *)sender();
365  s->deleteLater();
366 }
367 
368 QString QtServiceSysPrivate::getCommand(const QTcpSocket *socket)
369 {
370  int pos = cache[socket].indexOf("\r\n");
371  if (pos >= 0) {
372  QString ret = cache[socket].left(pos);
373  cache[socket].remove(0, pos+2);
374  return ret;
375  }
376  return "";
377 }
378 
379 #include "qtservice_unix.moc"
380 
381 bool QtServiceBasePrivate::sysInit()
382 {
383  sysd = new QtServiceSysPrivate;
384  sysd->serviceFlags = serviceFlags;
385  // Restrict permissions on files that are created by the service
386  ::umask(027);
387 
388  return true;
389 }
390 
391 void QtServiceBasePrivate::sysSetPath()
392 {
393  if (sysd)
394  sysd->setPath(socketPath(controller.serviceName()));
395 }
396 
397 void QtServiceBasePrivate::sysCleanup()
398 {
399  if (sysd) {
400  sysd->close();
401  delete sysd;
402  sysd = 0;
403  }
404 }
405 
406 bool QtServiceBasePrivate::start()
407 {
408  if (sendCmd(controller.serviceName(), "alive")) {
409  // Already running
410  return false;
411  }
412  // Could just call controller.start() here, but that would fail if
413  // we're not installed. We do not want to strictly require installation.
414  ::setenv("QTSERVICE_RUN", "1", 1); // Tell the detached process it's it
415  return QProcess::startDetached(filePath(), args.mid(1), "/");
416 }
417 
418 bool QtServiceBasePrivate::install(const QString &account, const QString &password)
419 {
420  Q_UNUSED(account)
421  Q_UNUSED(password)
422  QSettings settings(QSettings::SystemScope, "QtSoftware");
423 
424  settings.beginGroup("services");
425  settings.beginGroup(controller.serviceName());
426 
427  settings.setValue("path", filePath());
428  settings.setValue("description", serviceDescription);
429  settings.setValue("automaticStartup", startupType);
430 
431  settings.endGroup();
432  settings.endGroup();
433  settings.sync();
434 
435  QSettings::Status ret = settings.status();
436  if (ret == QSettings::AccessError) {
437  fprintf(stderr, "Cannot install \"%s\". Cannot write to: %s. Check permissions.\n",
438  controller.serviceName().toLatin1().constData(),
439  settings.fileName().toLatin1().constData());
440  }
441  return (ret == QSettings::NoError);
442 }
443 
444 void QtServiceBase::logMessage(const QString &message, QtServiceBase::MessageType type,
445  int, uint, const QByteArray &)
446 {
447  if (!d_ptr->sysd)
448  return;
449  int st;
450  switch(type) {
451  case QtServiceBase::Error:
452  st = LOG_ERR;
453  break;
454  case QtServiceBase::Warning:
455  st = LOG_WARNING;
456  break;
457  default:
458  st = LOG_INFO;
459  }
460  if (!d_ptr->sysd->ident) {
461  QString tmp = encodeName(serviceName(), true);
462  int len = tmp.toLocal8Bit().size();
463  d_ptr->sysd->ident = new char[len+1];
464  d_ptr->sysd->ident[len] = '\0';
465  ::memcpy(d_ptr->sysd->ident, tmp.toLocal8Bit().constData(), len);
466  }
467  openlog(d_ptr->sysd->ident, LOG_PID, LOG_DAEMON);
468  foreach(QString line, message.split('\n'))
469  syslog(st, "%s", line.toLocal8Bit().constData());
470  closelog();
471 }
472 
473 void QtServiceBase::setServiceFlags(QtServiceBase::ServiceFlags flags)
474 {
475  if (d_ptr->serviceFlags == flags)
476  return;
477  d_ptr->serviceFlags = flags;
478  if (d_ptr->sysd)
479  d_ptr->sysd->serviceFlags = flags;
480 }
481 
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