File: helper.cpp

package info (click to toggle)
kde-workspace 4:4.11.13-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 67,756 kB
  • ctags: 47,705
  • sloc: cpp: 358,638; ansic: 34,695; xml: 5,231; perl: 1,598; sh: 1,307; ruby: 1,135; python: 651; asm: 566; makefile: 37
file content (275 lines) | stat: -rw-r--r-- 7,783 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
 *  tzone.cpp
 *
 *  Copyright (C) 1998 Luca Montecchiani <m.luca@usa.net>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

/*

 A helper that's run using KAuth and does the system modifications.

*/

#include "helper.h"

#include <config-workspace.h>

#include <sys/time.h>
#include <time.h>
#include <unistd.h>

#include <kcomponentdata.h>
#include <kconfig.h>
#include <kconfiggroup.h>
#include <kstandarddirs.h>
#include <kprocess.h>
#include <QFile>
#include <QDebug>

#if defined(USE_SOLARIS)
#include <ktemporaryfile.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#endif

// We cannot rely on the $PATH environment variable, because D-Bus activation
// clears it. So we have to use a reasonable default.
static const QString exePath = QLatin1String("/usr/sbin:/usr/bin:/sbin:/bin");

static QString findNtpUtility()
{
    foreach(const QString &possible_ntputility, QStringList() << "ntpdate" << "rdate" ) {
        const QString ntpUtility = KStandardDirs::findExe(possible_ntputility, exePath);
        if (!ntpUtility.isEmpty()) {
            return ntpUtility;
        }
    }
    return QString();
}

int ClockHelper::ntp( const QStringList& ntpServers, bool ntpEnabled )
{
  int ret = 0;

  // write to the system config file
  QFile config_file(KDE_DEBIAN_CONFDIR "/kcmclockrc");
  if(!config_file.exists()) {
    config_file.open(QIODevice::WriteOnly);
    config_file.close();
    config_file.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ReadGroup | QFile::ReadOther);
  }
  KConfig _config(config_file.fileName(), KConfig::SimpleConfig);
  KConfigGroup config(&_config, "NTP");
  config.writeEntry("servers", ntpServers );
  config.writeEntry("enabled", ntpEnabled );

  QString ntpUtility(findNtpUtility());

  if ( ntpEnabled && !ntpUtility.isEmpty() ) {
    // NTP Time setting
    QString timeServer = ntpServers.first();
    if( timeServer.indexOf( QRegExp(".*\\(.*\\)$") ) != -1 ) {
      timeServer.replace( QRegExp(".*\\("), "" );
      timeServer.replace( QRegExp("\\).*"), "" );
      // Would this be better?: s/^.*\(([^)]*)\).*$/\1/
    }

    KProcess proc;
    proc << ntpUtility << timeServer;
    if ( proc.execute() != 0 ) {
      ret |= NTPError;
    }
  } else if( ntpEnabled ) {
    ret |= NTPError;
  }

  return ret;
}

int ClockHelper::date( const QString& newdate, const QString& olddate )
{
    struct timeval tv;

    tv.tv_sec = newdate.toULong() - olddate.toULong() + time(0);
    tv.tv_usec = 0;
    if (settimeofday(&tv, 0)) {
        return DateError;
    }

    QString hwclock = KStandardDirs::findExe("hwclock", exePath);
    if (!hwclock.isEmpty()) {
        KProcess::execute(hwclock, QStringList() << "--systohc");
    }
    return 0;
}

// on non-Solaris systems which do not use /etc/timezone?
int ClockHelper::tz( const QString& selectedzone )
{
    int ret = 0;

    //only allow letters, numbers hyphen underscore plus and forward slash
    //allowed pattern taken from time-util.c in systemd
    if (!QRegExp("[a-zA-Z0-9-_+/]*").exactMatch(selectedzone)) {
        return ret;
    }

#if defined(USE_SOLARIS)	// MARCO

        KTemporaryFile tf;
        tf.setPrefix("kde-tzone");
        tf.open();
        QTextStream ts(&tf);

        QFile fTimezoneFile(INITFILE);
        bool updatedFile = false;

        if (fTimezoneFile.open(QIODevice::ReadOnly))
        {
            bool found = false;

            QTextStream is(&fTimezoneFile);

            for (QString line = is.readLine(); !line.isNull();
                 line = is.readLine())
            {
                if (line.find("TZ=") == 0)
                {
                    ts << "TZ=" << selectedzone << endl;
                    found = true;
                }
                else
                {
                    ts << line << endl;
                }
            }

            if (!found)
            {
                ts << "TZ=" << selectedzone << endl;
            }

            updatedFile = true;
            fTimezoneFile.close();
        }

        if (updatedFile)
        {
            ts.device()->reset();
            fTimezoneFile.remove();

            if (fTimezoneFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
            {
                QTextStream os(&fTimezoneFile);

                for (QString line = ts->readLine(); !line.isNull();
                     line = ts->readLine())
                {
                    os << line << endl;
                }

                fchmod(fTimezoneFile.handle(),
                       S_IXUSR | S_IRUSR | S_IRGRP | S_IXGRP |
                       S_IROTH | S_IXOTH);
                fTimezoneFile.close();
            }
        }


        QString val = selectedzone;
#else
        QString tz = "/usr/share/zoneinfo/" + selectedzone;

        // Never check for zic as currently it is defunct on Debian systems.
        // LP: #1212662
        QString zic;
        if (!zic.isEmpty()) {
            KProcess::execute(zic, QStringList() << "-l" << selectedzone);
        } else if (!QFile::remove("/etc/localtime")) {
          ret |= TimezoneError;
        } else if (!QFile::symLinkTarget(tz).isEmpty()) {
          // If the timezone file is a symlink, get its link target and copy
          // that instead as otherwise the symlink may end up being broken.
          // LP: #1206199
          if (!QFile::copy(QFile::symLinkTarget(tz), "/etc/localtime")) {
            ret |= TimezoneError;
          }
        } else if (!QFile::copy(tz, "/etc/localtime")) {
          ret |= TimezoneError;
        }

        QFile fTimezoneFile("/etc/timezone");

        if (fTimezoneFile.exists() && fTimezoneFile.open(QIODevice::WriteOnly | QIODevice::Truncate) ) {
            QTextStream t(&fTimezoneFile);
            t << selectedzone;
            fTimezoneFile.close();
        }

        QString val = ':' + tz;
#endif // !USE_SOLARIS

        setenv("TZ", val.toAscii(), 1);
        tzset();

    return ret;
}

int ClockHelper::tzreset()
{
#if !defined(USE_SOLARIS) // Do not update the System!
        unlink( "/etc/timezone" );
        unlink( "/etc/localtime" );

        setenv("TZ", "", 1);
        tzset();
#endif // !USE SOLARIS
    return 0;
}

ActionReply ClockHelper::save(const QVariantMap &args)
{
  bool _ntp = args.value("ntp").toBool();
  bool _date = args.value("date").toBool();
  bool _tz = args.value("tz").toBool();
  bool _tzreset = args.value("tzreset").toBool();

  KComponentData data( "kcmdatetimehelper" );

  int ret = 0; // error code
//  The order here is important
  if( _ntp )
    ret |= ntp( args.value("ntpServers").toStringList(), args.value("ntpEnabled").toBool());
  if( _date )
    ret |= date( args.value("newdate").toString(), args.value("olddate").toString() );
  if( _tz )
    ret |= tz( args.value("tzone").toString() );
  if( _tzreset )
    ret |= tzreset();

  if (ret == 0) {
    return ActionReply::SuccessReply;
  } else {
    ActionReply reply(ActionReply::HelperError);
    reply.setErrorCode(ret);
    return reply;
  }
}

KDE4_AUTH_HELPER_MAIN("org.kde.kcontrol.kcmclock", ClockHelper)