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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
|
/*
* Copyright (C) 2013-2026 Eugen Wissner <belka@caraus.de>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <sys/timex.h>
#include "timedate.h"
static void slack_method_call(const Glib::RefPtr<Gio::DBus::Connection>& connection, const Glib::ustring& sender,
const Glib::ustring& object_path, const Glib::ustring& interface_name, const Glib::ustring& method_name,
const Glib::VariantContainerBase& parameters, const Glib::RefPtr<Gio::DBus::MethodInvocation>& invocation)
{
// Set time zone
if (method_name == "SetTimezone")
{
Glib::Variant<Glib::ustring> timezone;
Glib::Variant<bool> user_interaction;
parameters.get_child(timezone, 0);
parameters.get_child(user_interaction, 1);
try
{
dlackware::timedate::set_timezone(timezone.get(), user_interaction.get());
invocation->return_value(Glib::VariantContainerBase());
}
catch (const std::filesystem::filesystem_error& filesystem_error)
{
invocation->return_error(Gio::DBus::Error{ Gio::DBus::Error::FAILED, filesystem_error.what() });
}
}
else if (method_name == "SetLocalRTC")
{
Glib::Variant<bool> local_rtc;
Glib::Variant<bool> fix_system;
Glib::Variant<bool> user_interaction;
parameters.get_child(local_rtc, 0);
parameters.get_child(fix_system, 1);
parameters.get_child(user_interaction, 2);
try
{
dlackware::timedate::set_local_rtc(local_rtc.get(), fix_system.get(), user_interaction.get());
invocation->return_value(Glib::VariantContainerBase());
}
catch (const std::system_error& error)
{
invocation->return_error(Gio::DBus::Error{ Gio::DBus::Error::FAILED, error.what() });
}
catch (const Glib::SpawnError& spawn_error)
{
invocation->return_error(Gio::DBus::Error{ Gio::DBus::Error::FAILED, spawn_error.what() });
}
}
else if (method_name == "SetTime")
{
Glib::Variant<gint64> usec_utc;
Glib::Variant<bool> relative;
Glib::Variant<bool> user_interaction;
parameters.get_child(usec_utc, 0);
parameters.get_child(relative, 1);
parameters.get_child(user_interaction, 2);
try
{
dlackware::timedate::set_time(usec_utc.get(), relative.get(), user_interaction.get());
invocation->return_value(Glib::VariantContainerBase());
}
catch (const std::system_error& error)
{
invocation->return_error(Gio::DBus::Error{ Gio::DBus::Error::FAILED, error.what() });
}
}
else if (method_name == "SetNTP")
{
Glib::Variant<bool> use_ntp;
Glib::Variant<bool> user_interaction;
parameters.get_child(use_ntp, 0);
parameters.get_child(user_interaction, 1);
// Enable NTP
try
{
dlackware::timedate::set_ntp(use_ntp.get(), user_interaction.get());
invocation->return_value(Glib::VariantContainerBase());
}
catch (const std::filesystem::filesystem_error& filesystem_error)
{
invocation->return_error(Gio::DBus::Error{ Gio::DBus::Error::FAILED, filesystem_error.what() });
}
}
else if (method_name == "ListTimezones")
{
try
{
auto return_tuple = Glib::VariantContainerBase::create_tuple({
Glib::Variant<std::vector<Glib::ustring>>::create(dlackware::timedate::list_timezones())
});
invocation->return_value(return_tuple);
}
catch (const std::exception& exception)
{
Gio::DBus::Error error{ Gio::DBus::Error::FAILED, exception.what() };
invocation->return_error(error);
}
}
}
static void slack_get_property(Glib::VariantBase& result, const Glib::RefPtr<Gio::DBus::Connection>& connection,
const Glib::ustring& sender, const Glib::ustring& object_path, const Glib::ustring& interface_name,
const Glib::ustring& prop_name)
{
if (prop_name == "Timezone")
{
result = Glib::Variant<Glib::ustring>::create(dlackware::timedate::timezone());
}
else if (prop_name == "LocalRTC")
{
result = Glib::Variant<bool>::create(dlackware::timedate::local_rtc());
}
else if (prop_name == "NTP")
{
result = Glib::Variant<bool>::create(dlackware::timedate::ntp());
}
else if (prop_name == "CanNTP")
{
result = Glib::Variant<bool>::create(dlackware::timedate::can_ntp());
}
else if (prop_name == "NTPSynchronized")
{
result = Glib::Variant<bool>::create(dlackware::timedate::ntp_synchronized());
}
else if (prop_name == "TimeUSec")
{
result = Glib::Variant<std::uint64_t>::create(dlackware::timedate::time_usec());
}
else if (prop_name == "RTCTimeUSec")
{
result = Glib::Variant<std::uint64_t>::create(dlackware::timedate::rtc_time_usec());
}
}
namespace dlackware::timedate
{
timedate1::timedate1()
: interface_vtable{ &slack_method_call, &slack_get_property }
{
}
void timedate1::on_name_lost(const Glib::RefPtr<Gio::DBus::Connection>& connection, const Glib::ustring& name)
{
g_warning("Failed to acquire the service %s.\n", name.data());
exit(1);
}
void timedate1::on_bus_acquired(const Glib::RefPtr<Gio::DBus::Connection>& connection, const Glib::ustring& name)
{
Glib::RefPtr<Gio::DBus::NodeInfo> introspection_data;
try
{
auto introspection_xml = Glib::file_get_contents(
(std::filesystem::path(DATADIR_INTERFACES) / dlackware::timedate::bus_name).concat(".xml")
);
introspection_data = Gio::DBus::NodeInfo::create_for_xml(introspection_xml);
}
catch (Glib::Error& slack_err)
{
g_error("Failed to parse D-Bus introspection XML: %s\n", slack_err.what().data());
}
try
{
guint registration_id = connection->register_object(bus_path,
introspection_data->lookup_interface(), this->interface_vtable);
}
catch (Glib::Error& slack_err)
{
g_critical("Failed to register callbacks for the exported object with the D-Bus interface: %s\n",
slack_err.what().data());
}
}
static void list_timezones(const std::string& prefix, std::vector<Glib::ustring>& accumulator)
{
auto zoneinfo_path = std::filesystem::path(zoneinfo_database) / prefix;
for (auto zoneinfo_entry : std::filesystem::directory_iterator(zoneinfo_path))
{
auto new_prefix = prefix + zoneinfo_entry.path().filename().string();
if (zoneinfo_entry.is_directory())
{
list_timezones(new_prefix + "/", accumulator);
}
else if (zoneinfo_entry.is_regular_file() && !zoneinfo_entry.path().has_extension()
&& zoneinfo_entry.path().filename() != "leapseconds")
{
accumulator.emplace_back(new_prefix);
}
}
}
std::vector<Glib::ustring> list_timezones()
{
std::vector<Glib::ustring> result;
list_timezones("", result);
return result;
}
Glib::ustring timezone()
{
std::unique_ptr<gchar[], decltype(&g_free)> zone_copied_from(
g_file_read_link("/etc/localtime", NULL), &g_free);
if (zone_copied_from == nullptr)
{
return nullptr;
}
return Glib::ustring{ zone_copied_from.get() + zoneinfo_database.size() + 1 };
}
void set_timezone(const Glib::ustring& zone, bool)
{
auto zone_file = std::filesystem::path("/usr/share/zoneinfo") / zone.data();
std::error_code ec{};
if (!std::filesystem::is_regular_file(zone_file, ec))
{
throw std::filesystem::filesystem_error("Zone info is not a regular file", zone_file, ec);
}
std::filesystem::path etc_localtime = "/etc/localtime";
std::filesystem::remove(etc_localtime);
std::filesystem::create_symlink(zone_file, etc_localtime);
}
void set_ntp(bool use_ntp, bool)
{
try
{
std::string service_state = use_ntp ? "-u" : "-d";
const auto command_flags = Glib::SpawnFlags::SPAWN_SEARCH_PATH
| Glib::SpawnFlags::SPAWN_STDERR_TO_DEV_NULL | Glib::SpawnFlags::SPAWN_STDERR_TO_DEV_NULL;
int wait_status{-1};
Glib::spawn_sync("", std::vector<std::string>{ "s6-rc", service_state, "change", "ntpd" },
command_flags, {}, nullptr, nullptr, &wait_status);
if (wait_status == 0 || wait_status == 0x300) // Unknown service name in the arguments.
{
return;
}
}
catch (const Glib::SpawnError& spawn_error)
{
}
std::filesystem::perms rc_mode = std::filesystem::perms::owner_read | std::filesystem::perms::owner_write
| std::filesystem::perms::group_read | std::filesystem::perms::others_read;
if (use_ntp)
{
rc_mode |= std::filesystem::perms::owner_exec
| std::filesystem::perms::group_exec | std::filesystem::perms::others_exec;
}
std::error_code ec;
const std::filesystem::path service_path{ "/etc/rc.d/rc.ntpd" };
if (std::filesystem::is_regular_file(service_path, ec))
{
std::filesystem::permissions("/etc/rc.d/rc.ntpd", rc_mode);
}
else
{
throw std::filesystem::filesystem_error("The NTP daemon isn't installed", service_path, ec);
}
}
void set_time(std::int64_t usec_utc, bool relative, bool)
{
timespec ts;
std::chrono::system_clock::duration current_time_since_epoch;
if (relative)
{
current_time_since_epoch = std::chrono::system_clock::now().time_since_epoch();
current_time_since_epoch += std::chrono::microseconds(usec_utc);
}
else
{
current_time_since_epoch = std::chrono::microseconds(usec_utc);
}
auto seconds_since_epoch = std::chrono::floor<std::chrono::seconds>(current_time_since_epoch);
ts.tv_sec = seconds_since_epoch.count();
ts.tv_nsec = std::chrono::duration_cast<std::chrono::microseconds>(
current_time_since_epoch - seconds_since_epoch).count();
if (clock_settime(CLOCK_REALTIME, &ts) == -1)
{
throw std::system_error(errno, std::generic_category());
}
}
void set_local_rtc(bool local_rtc, bool fix_system, bool)
{
std::ofstream hardwareclock{ "/etc/hardwareclock", std::ios::trunc };
std::string hwclock_argument;
hardwareclock << "# /etc/hardwareclock" << std::endl
<< "#" << std::endl
<< "# Tells how the hardware clock time is stored." << std::endl
<< "# You should run timeconfig to edit this file." << std::endl
<< std::endl;
if (local_rtc)
{
hwclock_argument = "--localtime";
hardwareclock << "localtime";
}
else
{
hwclock_argument = "--utc";
hardwareclock << "UTC";
}
hardwareclock << std::endl;
if (!fix_system)
{
Glib::spawn_sync("", std::vector<std::string>{ "/sbin/hwclock", hwclock_argument, "--hctosys" },
Glib::SpawnFlags::SPAWN_STDOUT_TO_DEV_NULL | Glib::SpawnFlags::SPAWN_STDERR_TO_DEV_NULL,
{}, nullptr, nullptr, static_cast<int *>(nullptr));
}
}
bool local_rtc()
{
std::ifstream fh{ "/etc/hardwareclock", std::ios::in };
if (!fh.is_open())
{
return false;
}
std::array<char, 10> time_str; // "localtime" is longer than "UTC" and has 9 letters + \0
while (fh.good())
{
fh.getline(time_str.data(), time_str.size());
fh.clear(fh.rdstate() & (~std::ios_base::failbit));
if (std::strncmp(time_str.data(), "localtime", time_str.size()) == 0)
{
return true;
}
}
return false;
}
bool ntp()
{
return Glib::file_test("/etc/rc.d/rc.ntpd", Glib::FileTest::FILE_TEST_IS_EXECUTABLE);
}
bool can_ntp()
{
std::string standard_output;
int wait_status{-1};
try
{
Glib::spawn_sync("", std::vector<std::string>{ "s6-rc-db", "type", "ntpd" },
Glib::SpawnFlags::SPAWN_SEARCH_PATH | Glib::SpawnFlags::SPAWN_STDERR_TO_DEV_NULL,
{}, &standard_output, nullptr, &wait_status);
}
catch (const Glib::SpawnError& spawn_error)
{
return std::filesystem::exists("/etc/rc.d/rc.ntpd");
}
return wait_status == 0 && standard_output == "bundle\n";
}
bool ntp_synchronized()
{
timex buffer{ .modes = 0 };
int ntp_result = adjtimex(&buffer);
if (ntp_result == -1)
{
throw std::system_error(errno, std::generic_category());
}
return ntp_result != TIME_ERROR && (buffer.status & STA_UNSYNC) == 0;
}
std::uint64_t time_usec()
{
timespec spec;
if (clock_gettime(CLOCK_REALTIME, &spec) == -1)
{
throw std::system_error(errno, std::generic_category());
}
time_t seconds = spec.tv_sec;
tm time;
if (local_rtc())
{
gmtime_r(&seconds, &time);
}
else
{
localtime_r(&seconds, &time);
}
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::seconds(std::mktime(&time)) + std::chrono::nanoseconds(spec.tv_nsec)).count();
}
std::uint64_t rtc_time_usec()
{
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
}
}
|