-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinitializer.cpp
More file actions
561 lines (483 loc) · 16.4 KB
/
initializer.cpp
File metadata and controls
561 lines (483 loc) · 16.4 KB
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
#include "initializer.h"
// safegaurds
#if !defined(WANT_MOUNT_ROOT) && defined(WANT_MODULES)
#pragma message("Modules loaded by the init system are expressly for mounting root. Not enabling Module loading.")
#undef WANT_MODULES
#endif
// STL
#include <string>
#include <unordered_map>
#include <list>
#include <algorithm>
#include <functional>
// PUT
#include <put/object.h>
#include <put/childprocess.h>
#include <put/cxxutils/posix_helpers.h>
#include <put/cxxutils/hashing.h>
#include <put/specialized/mount.h>
#include <put/specialized/fstable.h>
#if defined(WANT_MODULES)
# include <put/specialized/module.h>
#endif
#if defined(WANT_MOUNT_ROOT)
# include <put/specialized/mountpoints.h>
# include <put/specialized/blockdevices.h>
# include <put/specialized/blockinfo.h>
#endif
// Project
#include "display.h"
#ifndef CONFIG_SERVICE
#define CONFIG_SERVICE "sxconfig"
#endif
#ifndef DIRECTOR_SERVICE
#define DIRECTOR_SERVICE "sxdirector"
#endif
#ifndef CONFIG_USERNAME
#define CONFIG_USERNAME "config"
#endif
#ifndef DIRECTOR_USERNAME
#define DIRECTOR_USERNAME "director"
#endif
#ifndef BIN_PATH
#define SBIN_PATH "/sbin"
#endif
#ifndef PROCFS_PATH
#define PROCFS_PATH "/proc"
#endif
#ifndef SYSFS_PATH
#define SYSFS_PATH "/sys"
#endif
#ifndef DEVFS_PATH
#define DEVFS_PATH "/dev"
#endif
#ifndef SCFS_PATH
#define SCFS_PATH "/svc"
#endif
#ifndef SCFS_BIN
#define SCFS_BIN SBIN_PATH "/svcfs"
#endif
#ifndef CONFIG_BIN
#define CONFIG_BIN SBIN_PATH "/" CONFIG_SERVICE
#endif
#ifndef DIRECTOR_BIN
#define DIRECTOR_BIN SBIN_PATH "/" DIRECTOR_SERVICE
#endif
#ifndef SCFS_ARGS
#define SCFS_ARGS SCFS_BIN " " SCFS_PATH " -o allow_other"
#endif
#ifndef CONFIG_ARGS
#define CONFIG_ARGS CONFIG_BIN " -f"
#endif
#ifndef DIRECTOR_ARGS
#define DIRECTOR_ARGS DIRECTOR_BIN " -f"
#endif
#ifndef CONFIG_SOCKET
#define CONFIG_SOCKET "/" CONFIG_USERNAME "/io"
#endif
#ifndef DIRECTOR_SOCKET
#define DIRECTOR_SOCKET "/" DIRECTOR_USERNAME "/io"
#endif
#ifdef __linux__
# define PROCFS_NAME "proc"
# define PROCFS_OPTIONS "default"
# define WANT_PROCFS
#else
# define PROCFS_NAME "procfs"
# define PROCFS_OPTIONS "linux"
#endif
namespace Initializer
{
static std::unordered_map<const char*, ChildProcess> s_procs;
enum class State
{
Clear,
Starting,
Passed,
Failed,
Canceled,
Retrying,
};
void addInitStep(string_literal name, Object::fslot_t<State> func, bool fatal) noexcept;
void setStepState(string_literal step_id, State state) noexcept;
struct step_t
{
string_literal name;
Object::fslot_t<State> func;
bool fatal;
bool have_result;
State result;
};
static std::list<step_t> s_steps;
#if defined(WANT_MODULES)
State load_modules(void) noexcept;
#endif
#if defined(WANT_MOUNT_ROOT)
static fsentry_t root_entry;
static std::map<std::string, std::string> boot_options;
State mount_root(void) noexcept;
#endif
struct vfs_mount
{
string_literal step_id;
int rval;
const fsentry_t* fstab_entry;
fsentry_t defaults;
bool fatal;
};
State read_vfs_paths(void) noexcept;
State mount_vfs(vfs_mount* vfs) noexcept;
static std::list<vfs_mount> s_vfses = {
#if defined(WANT_PROCFS)
{ "Mount ProcFS", posix::error_response, nullptr, { "proc", PROCFS_PATH, PROCFS_NAME, PROCFS_OPTIONS }, false },
#endif
#if defined(WANT_SYSFS)
{ "Mount SysFS", posix::error_response, nullptr, { "sysfs", SYSFS_PATH, "sysfs", "defaults" }, false },
#endif
#if defined(WANT_NATIVE_SCFS)
{ "Mount SCFS", posix::error_response, nullptr, { "scfs", SCFS_PATH, "scfs", "defaults" }, false },
#endif
};
struct provider_data_t
{
const char* step_id;
const char* bin;
const char* arguments;
const char* username;
Object::fslot_t<bool> test;
bool fatal;
};
State provider_run (provider_data_t* data) noexcept;
void restart_provider(provider_data_t* data) noexcept;
bool start_provider (provider_data_t* data) noexcept;
// TESTS
// SXConfig
#if defined(WANT_CONFIG_SERVICE)
static char config_socket_path[PATH_MAX] = { 0 };
bool test_config_service(void) noexcept
{
struct stat data;
return posix::stat(config_socket_path, &data) && // stat file on VFS worked AND
data.st_mode & S_IFSOCK ; // it's a socket file
}
#endif
// SXDirector
static char director_socket_path[PATH_MAX] = { 0 };
bool test_director_service(void) noexcept
{
struct stat data;
return posix::stat(director_socket_path, &data) && // stat file on VFS worked AND
data.st_mode & S_IFSOCK; // it's a socket file
}
// SCFS
#if defined(WANT_FUSE_SCFS)
static char scfs_mountpoint[PATH_MAX] = { 0 };
bool test_scfs(void) noexcept
{
std::list<fsentry_t> mtab;
if(mount_table(mtab)) // parse mount table
for(auto pos = mtab.begin(); pos != mtab.end(); ++pos) // iterate newly parsed mount table
if(!posix::strcmp(pos->device, "scfs")) // if scfs is mounted
{
posix::strncpy(scfs_mountpoint, pos->path, sizeof(scfs_mountpoint));
posix::snprintf(config_socket_path , PATH_MAX, "%s%s", scfs_mountpoint, CONFIG_SOCKET );
posix::snprintf(director_socket_path, PATH_MAX, "%s%s", scfs_mountpoint, DIRECTOR_SOCKET);
return true;
}
return false;
}
#endif
static std::list<provider_data_t> s_providers = {
#if defined(WANT_FUSE_SCFS)
{ "Mount FUSE SCFS", SCFS_BIN, SCFS_ARGS, nullptr, test_scfs, false },
#endif
#if defined(WANT_CONFIG_SERVICE)
{ "Config Service", CONFIG_BIN, CONFIG_ARGS, CONFIG_USERNAME, test_config_service, false },
#endif
{ "Director Service", DIRECTOR_BIN, DIRECTOR_ARGS, DIRECTOR_USERNAME, test_director_service, true },
};
}
void Initializer::addInitStep(string_literal name, Object::fslot_t<State> func, bool fatal) noexcept
{
s_steps.emplace_back(step_t{ name, func, fatal, false, State::Clear });
Display::addItem(name);
}
void Initializer::setStepState(string_literal step_id, State state) noexcept
{
switch(state)
{
case State::Clear: Display::setItemState(step_id, terminal::style::reset , " "); break;
case State::Starting: Display::setItemState(step_id, terminal::style::darkCyan , "Starting"); break;
case State::Passed: Display::setItemState(step_id, terminal::style::darkGreen , " Passed "); break;
case State::Failed: Display::setItemState(step_id, terminal::style::darkRed , " Failed "); break;
case State::Canceled: Display::setItemState(step_id, terminal::style::reset , "Canceled"); break;
case State::Retrying: Display::setItemState(step_id, terminal::style::darkYellow , "Retrying"); break;
}
}
void Initializer::start(void) noexcept
{
enum {
Read = 0,
Write = 1,
};
posix::fd_t stderr_pipe[2];
if(!posix::pipe(stderr_pipe) ||
!posix::dup2(stderr_pipe[Write], STDERR_FILENO))
terminal::write("%s Unable to redirect stderr: %s", terminal::warning, posix::strerror(errno));
Display::clearItems();
Display::setItemsLocation(3, 1);
#if defined(WANT_MODULES)
addInitStep("Load Modules", load_modules, false);
#endif
#if defined(WANT_MOUNT_ROOT)
addInitStep("Mount Root", mount_root, false);
#endif
if(!s_vfses.empty()) // being empty is unlikely but possible
{
addInitStep("Find Mount Points", read_vfs_paths, false);
for(vfs_mount& vfs : s_vfses)
addInitStep(vfs.step_id, [&vfs]() noexcept { return mount_vfs(&vfs); }, vfs.fatal);
}
for(provider_data_t& provider : s_providers)
addInitStep(provider.step_id, [&provider]() noexcept { return provider_run(&provider); }, provider.fatal);
for(auto& step : s_steps)
setStepState(step.name, step.result);
for(auto& step : s_steps)
{
if(!step.have_result || step.result == State::Failed)
{
step.result = step.func();
setStepState(step.name, step.result);
if(step.result == State::Failed && step.fatal)
{
run_emergency_shell();
break;
}
}
}
}
Initializer::State Initializer::read_vfs_paths(void) noexcept
{
std::list<fsentry_t> fstab;
if(filesystem_table(fstab)) // parse filesystem table
{
for(const fsentry_t& entry : fstab) // iterate all fstab entries
for(vfs_mount& vfs : s_vfses) // iterate all vfses we want
if(!posix::strcmp(entry.device, vfs.defaults.device)) // if the fstab entry is the vfs we want
vfs.fstab_entry = &entry; // copy a pointer to the entry
return State::Passed;
}
else
Display::bailoutLine("Unable to parse /etc/fstab!: %s", posix::strerror(errno));
return State::Failed;
}
Initializer::State Initializer::mount_vfs(vfs_mount* vfs) noexcept
{
if(vfs->fstab_entry != nullptr)
{
::mkdir(vfs->fstab_entry->path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); // create directory (if it doesn't exist)
vfs->rval = mount(vfs->fstab_entry->device, vfs->fstab_entry->path, vfs->fstab_entry->filesystems, vfs->fstab_entry->options);
}
if(vfs->rval != posix::success_response) // if not mounted
{
::mkdir(vfs->defaults.path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); // create directory (if it doesn't exist)
vfs->rval = mount(vfs->defaults.device, vfs->defaults.path, vfs->defaults.filesystems, vfs->defaults.options); // mount to default directory with default options
}
return vfs->rval == posix::success_response ? State::Passed : State::Failed;
}
Initializer::State Initializer::provider_run(provider_data_t* data) noexcept
{
if(data->test())
return State::Canceled;
int retries = 5;
for(; retries > 0; --retries, ::sleep(1)) // keep trying and wait a second between tries
{
if(start_provider(data) && data->test())
retries = INT_MIN + 1; // exit loop
else
setStepState(data->step_id, State::Retrying);
}
if(retries == INT_MIN) // if succeeded
{
Object::connect(s_procs[data->bin].finished,
[data](pid_t, posix::error_t) noexcept { restart_provider(data); });
Object::connect(s_procs[data->bin].killed,
[data](pid_t, posix::Signal::EId) noexcept { restart_provider(data); });
}
return retries == INT_MIN ? State::Passed : State::Failed;
}
bool Initializer::start_provider(provider_data_t* data) noexcept
{
if(s_procs.find(data->bin) != s_procs.end()) // if process exists
return false; // do not try to start it
setStepState(data->step_id, State::Starting);
ChildProcess& proc = s_procs[data->bin]; // create process
return
(data->arguments == nullptr || proc.setOption("/Process/Arguments", data->arguments)) && // set arguments if they exist
(data->username == nullptr || proc.setOption("/Process/User", data->username)) && // set username if provided
proc.invoke(); // invoke the process
}
void Initializer::restart_provider(provider_data_t* data) noexcept
{
if(s_procs.find(data->bin) != s_procs.end()) // if process existed once
{
s_procs.erase(data->bin); // erase old process entry
::sleep(1); // safety delay
}
start_provider(data);
}
#if defined(WANT_MODULES)
Initializer::State Initializer::load_modules(void) noexcept
{
posix::fd_t fd = posix::open("/modules/modules.list", O_RDONLY);
if(fd == posix::error_response)
{
Display::bailoutLine("Unable to open list of modules to load: %s", posix::strerror(errno));
return State::Failed;
}
// TODO
if(false)
{
Display::bailoutLine("Unable to load module %s: %s", "xyz", posix::strerror(errno));
return State::Failed;
}
return State::Passed;
}
#endif
#if defined(WANT_MOUNT_ROOT)
Initializer::State Initializer::mount_root(void) noexcept
{
fsentry_t root_entry;
# if defined(WANT_PROCFS)
::mkdir(PROCFS_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); // create directory (if it doesn't exist)
if(mount("proc", PROCFS_PATH, PROCFS_NAME, PROCFS_OPTIONS) == posix::success_response) // temporarily mount procfs
{
reinitialize_paths();
constexpr posix::size_t cmdlength = 0x2000; // 8KB
char cmdline[cmdlength + 1] = { 0 }; // 8KB + NUL char
posix::fd_t fd = posix::open(PROCFS_PATH "/cmdline", O_RDONLY); // read /proc/cmdline so we can read boot options
posix::ssize_t count = posix::read(fd, cmdline, cmdlength);
std::string key;
std::string value;
key.reserve(cmdlength);
value.reserve(cmdlength);
for(char* pos = cmdline; *pos && pos < cmdline + count; ++pos)
{
key.clear();
value.clear();
while(*pos && posix::isspace(*pos))
++pos;
for(; *pos && pos < cmdline + cmdlength && posix::isgraph(*pos) && *pos != '='; ++pos)
key.push_back(char(::tolower(*pos))); // options must be lowercase
if(*pos == '=')
{
for(++pos; *pos && pos < cmdline + cmdlength && posix::isgraph(*pos); ++pos)
value.push_back(*pos);
boot_options.emplace(key, value);
}
else
{
switch (hash(key))
{
case "debug"_hash:
boot_options.emplace("debug", "yes");
break;
case "break"_hash:
boot_options.emplace("break", "premount");
break;
case "noresume"_hash:
boot_options.emplace("noresume", "premount");
break;
case "ro"_hash:
posix::strncpy(root_entry.options, "ro", sizeof(fsentry_t::options));
break;
case "rw"_hash:
posix::strncpy(root_entry.options, "rw", sizeof(fsentry_t::options));
break;
case "fastboot"_hash:
boot_options.emplace("fsck.mode", "skip");
break;
case "forcefsck"_hash:
boot_options.emplace("fsck.mode", "force");
break;
case "fsckfix"_hash:
boot_options.emplace("fsck.repair", "yes");
break;
default:
break;
}
}
}
blockdevices::init(); // probe system partitions (reads /proc/partitions)
blockdevice_t* root_device = nullptr;
auto pos = boot_options.find("root");
if(pos != boot_options.end())
{
std::string::size_type offset = pos->second.find('=');
if(offset == std::string::npos) // not found
{
root_device = blockdevices::lookupByPath(pos->second.c_str()); // try to find in detected devices
if(root_device == nullptr) // if none found
root_device = blockdevices::probe(pos->second.c_str()); // probe the specified device name
}
else // found '='
{
std::string prefix = pos->second.substr(0, offset);
std::transform(prefix.begin(), prefix.end(), prefix.begin(), ::toupper);
switch(hash(prefix))
{
case "UUID"_hash: // found "root=UUID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
root_device = blockdevices::lookupByUUID(pos->second.substr(offset).c_str());
break;
case "LABEL"_hash: // found "root=LABEL=XXXXXXXX"
root_device = blockdevices::lookupByLabel(pos->second.substr(offset).c_str());
break;
default: // found "root=???=XXXXXXXX" but try to find it anyway
root_device = blockdevices::lookup(pos->second.substr(offset).c_str());
break;
}
}
if(root_device != nullptr) // found a device
{
posix::strncpy(root_entry.device, root_device->path, sizeof(fsentry_t::device)); // copy over data
posix::strncpy(root_entry.filesystems, root_device->fstype, sizeof(fsentry_t::filesystems));
}
else
{
Display::bailoutLine("Could not find root device using: %s", pos->second.c_str());
return State::Failed;
}
}
else
{
Display::bailoutLine("No root device specified in boot arguments!");
return State::Failed;
}
unmount(PROCFS_PATH); // done with temporary procfs mount
}
else
{
Display::bailoutLine("Unable to temporarily mount proc to get boot arguments and find devices: %s", posix::strerror(errno));
return State::Failed;
}
# else
blockdevices::init(); // probe system partitions
# endif
if(mount(root_entry.device, "/", root_entry.filesystems, root_entry.options) != posix::success_response) // mount directly on top of Linux rootfs
{
Display::bailoutLine("Unable to mount device \"%s\": %s", root_entry.device, posix::strerror(errno));
return State::Failed;
}
return State::Passed;
}
#endif
// Desperation
void Initializer::run_emergency_shell(void) noexcept
{
uint16_t rows = 0;
uint16_t columns = 0;
terminal::getWindowSize(rows, columns);
terminal::setCursorPosition(rows - 5, 0);
terminal::write("Starting rescue shell\n");
terminal::showCursor();
}