/
main.c
1782 lines (1497 loc) · 44.1 KB
/
main.c
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*This code is part of the Epoch Init System.
* The Epoch Init System is maintained by Subsentient.
* This software is public domain.
* Please read the file UNLICENSE.TXT for more information.*/
/**CLI parsing, etc. main() is here.**/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <grp.h>
#include <pwd.h>
#include <sys/reboot.h>
#include <sys/shm.h>
#ifndef NO_EXECINFO
#include <execinfo.h>
#endif
#include "epoch.h"
#define ArgIs(z) !strcmp(CArg, z)
#define CmdIs(z) __CmdIs(argv[0], z)
/*Forward declarations for static functions.*/
static ReturnCode ProcessGenericHalt(int argc, char **argv);
static Bool __CmdIs(const char *CArg, const char *InCmd);
static void PrintEpochHelp(const char *RootCommand, const char *InCmd);
static ReturnCode HandleEpochCommand(int argc, char **argv);
static void SigHandler(int Signal);
static void SetDefaultProcessTitle(int argc, char **argv);
/*
* Actual functions.
*/
Bool AreInit;
static Bool __CmdIs(const char *CArg, const char *InCmd)
{ /*Check if we are or end in the command name specified.*/
const char *TWorker = CArg;
if ((TWorker = strstr(CArg, InCmd)))
{
while (*TWorker != '\0') ++TWorker;
TWorker -= strlen(InCmd);
if (!strcmp(TWorker, InCmd))
{
return true;
}
}
return false;
}
static void SigHandler(int Signal)
{
const char *ErrorM = NULL;
char OutMsg[MAX_LINE_SIZE * 2] = { '\0' };
static Bool RecursiveProblem = false;
#ifndef NO_EXECINFO
void *BTList[25];
char **BTStrings;
size_t BTSize;
char *TWorker = OutMsg;
#endif
switch (Signal)
{
case SIGINT:
{
static unsigned LastKillAttempt = 0;
if (AreInit)
{
if (CurrentTask.Set && CurrentBootMode != BOOT_NEUTRAL
&& (LastKillAttempt == 0 || CurrentBootMode == BOOT_SHUTDOWN || time(NULL) > (LastKillAttempt + 5)))
{
char MsgBuf[MAX_LINE_SIZE];
ReturnCode KilledOK = SUCCESS;
snprintf(MsgBuf, sizeof MsgBuf,
"\n%sKilling task %s. %s",
CONSOLE_COLOR_YELLOW, CurrentTask.TaskName, CONSOLE_ENDCOLOR);
if (CurrentBootMode == BOOT_BOOTUP)
{
strncat(MsgBuf, "Press CTRL-ALT-DEL within 5 seconds to reboot.", MAX_LINE_SIZE - strlen(MsgBuf) - 1);
}
puts(MsgBuf);
WriteLogLine(MsgBuf, true);
if (CurrentTask.PID == 0)
{
Bool *TPtr = (void*)CurrentTask.Node;
*TPtr = true;
KilledOK = SUCCESS;
}
else
{
KilledOK = !kill(CurrentTask.PID, SIGKILL);
}
if (!KilledOK)
{
snprintf(MsgBuf, sizeof MsgBuf, "%sUnable to kill %s.%s",
CONSOLE_COLOR_RED, CurrentTask.TaskName, CONSOLE_ENDCOLOR);
}
else
{
snprintf(MsgBuf, sizeof MsgBuf, "%s%s was successfully killed.%s", CONSOLE_COLOR_GREEN,
CurrentTask.TaskName, CONSOLE_ENDCOLOR);
}
puts(MsgBuf);
WriteLogLine(MsgBuf, true);
LastKillAttempt = time(NULL);
return;
}
else
{
if (CurrentBootMode == BOOT_SHUTDOWN)
{
puts(CONSOLE_COLOR_YELLOW "System halt/reboot already in progress." CONSOLE_ENDCOLOR);
return;
}
else
{
LaunchShutdown(OSCTL_REBOOT);
}
}
}
else
{
puts("SIGINT received. Exiting.");
ShutdownMemBus(false);
exit(0);
}
}
case SIGSEGV:
{
ErrorM = "A segmentation fault has occurred in Epoch!";
break;
}
case SIGILL:
{
ErrorM = "Epoch has encountered an illegal instruction!";
break;
}
case SIGFPE:
{
ErrorM = "Epoch has encountered an arithmetic error!";
break;
}
case SIGABRT:
{
ErrorM = "Epoch has received an abort signal!";
break;
}
case SIGUSR2: /**We are init and being ordered to restart ourselves.**/
{
WriteLogLine(CONSOLE_COLOR_RED "Received SIGUSR2, reexecuting as requested." CONSOLE_ENDCOLOR, true);
ReexecuteEpoch();
return;
}
}
if (RecursiveProblem)
{
EmulWall("Epoch: Recursive fault detected. Sleeping forever.", false);
while (1) sleep(1);
}
RecursiveProblem = true;
#ifndef NO_EXECINFO
BTSize = backtrace(BTList, 25);
BTStrings = backtrace_symbols(BTList, BTSize);
snprintf(OutMsg, sizeof OutMsg, "%s\n\nBacktrace:\n", ErrorM);
TWorker += strlen(TWorker);
for (; BTSize > 0 && *BTStrings != NULL; --BTSize, ++BTStrings, TWorker += strlen(TWorker))
{
snprintf(TWorker, sizeof OutMsg - strlen(OutMsg) - 1, "\n%s", *BTStrings);
}
#else
snprintf(OutMsg, sizeof OutMsg, "%s\n\nEpoch was compiled without backtrace support.", ErrorM);
#endif
if (AreInit)
{
EmulWall(OutMsg, false);
EmergencyShell();
}
else
{
SpitError(OutMsg);
exit(1);
}
}
static void PrintEpochHelp(const char *RootCommand, const char *InCmd)
{ /*Used for help for the epoch command.*/
const char *HelpMsgs[] =
{
("[poweroff/halt/reboot]:\n\t" CONSOLE_ENDCOLOR
"Enter poweroff, halt, or reboot to do the obvious."
),
( "shutdown [-r/-p/-h] <time>:\n\t" CONSOLE_ENDCOLOR
"Wrapper for the 'shutdown' command. See 'shutdown --help' for more."
),
( "[disable/enable] objectid:\n\t" CONSOLE_ENDCOLOR
"Enter disable or enable followed by an object ID to disable or enable\n\tthat object."
),
( "[start/stop/restart] objectid:\n\t" CONSOLE_ENDCOLOR
"Enter start, stop, or restart followed by an object ID to control\n\tthat object."
),
( "reload objectid:\n\t" CONSOLE_ENDCOLOR
"If a reload command exists for the object specified,\n\tthe object is reloaded."
),
( "objrl objectid [del/add/check] runlevel:\n\t" CONSOLE_ENDCOLOR
"runlevel del and add do pretty much what it sounds like,\n\t"
"and check will tell you if that object is enabled for that runlevel."
),
( "status [objectid]:\n\t" CONSOLE_ENDCOLOR
"Prints information about the object specified.\n\t"
"If an object is not specified, it prints info on all known objects."
),
( "setcad [on/off]:\n\t" CONSOLE_ENDCOLOR
"Sets Ctrl-Alt-Del instant reboot modes. If set to on,\n\t"
"striking Ctrl-Alt-Del at a console will instantly reboot the system\n\t"
"without intervention by Epoch. Otherwise, if set to off, Epoch will\n\t"
"perform a normal reboot when Ctrl-Alt-Del is pressed."
),
( "configreload:\n\t" CONSOLE_ENDCOLOR
"Enter configreload to reload the configuration file from disk.\n\t"
"This is useful for when you change it\n\t"
"to add or remove services, change runlevels, and more."
),
( "reexec:\n\t" CONSOLE_ENDCOLOR
"Enter reeexec to partially restart Epoch from disk.\n\t"
"This is necessary for updating the Epoch binary to prevent\n\t"
"a failure with unmounting the filesystem the binary is on."
),
( "runlevel:\n\t" CONSOLE_ENDCOLOR
"Enter runlevel without any arguments to print the current runlevel,\n\t"
"or enter an argument as the new runlevel."
),
( "getpid objectid:\n\t" CONSOLE_ENDCOLOR
"Retrieves the PID Epoch has on record for the given object.\n\t"
"If a PID file is specified, then the PID will be gotten from there."
),
( "kill objectid:\n\t" CONSOLE_ENDCOLOR
"Sends SIGKILL to the object specified. If a PID file is specified,\n\t"
"the PID will be retrieved from that."
),
( "version:\n\t" CONSOLE_ENDCOLOR
"Prints the current version of the Epoch Init System."
)
};
enum { HCMD, SHTDN, ENDIS, STAP, REL, OBJRL, STATUS, SETCAD, CONFRL, REEXEC,
RLCTL, GETPID, KILLOBJ, VER, ENUM_MAX };
printf("%s\nCompiled %s %s\n\n", VERSIONSTRING, __DATE__, __TIME__);
if (InCmd == NULL)
{
short Inc = 0;
puts(CONSOLE_COLOR_RED "Printing all help.\n" CONSOLE_ENDCOLOR "-----\n");
for (; Inc < ENUM_MAX; ++Inc)
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[Inc]);
}
}
else if (!strcmp(InCmd, "poweroff") || !strcmp(InCmd, "halt") || !strcmp(InCmd, "reboot"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[HCMD]);
return;
}
else if (!strcmp(InCmd, "shutdown"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[SHTDN]);
return;
}
else if (!strcmp(InCmd, "disable") || !strcmp(InCmd, "enable"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[ENDIS]);
return;
}
else if (!strcmp(InCmd, "start") || !strcmp(InCmd, "stop") || !strcmp(InCmd, "restart"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[STAP]);
return;
}
else if (!strcmp(InCmd, "objrl"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[OBJRL]);
return;
}
else if (!strcmp(InCmd, "status"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[STATUS]);
return;
}
else if (!strcmp(InCmd, "setcad"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[SETCAD]);
return;
}
else if (!strcmp(InCmd, "configreload"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[CONFRL]);
return;
}
else if (!strcmp(InCmd, "reexec"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[REEXEC]);
return;
}
else if (!strcmp(InCmd, "reload"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[REL]);
return;
}
else if (!strcmp(InCmd, "runlevel"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[RLCTL]);
return;
}
else if (!strcmp(InCmd, "getpid"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[GETPID]);
return;
}
else if (!strcmp(InCmd, "kill"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[KILLOBJ]);
return;
}
else if (!strcmp(InCmd, "version"))
{
printf(CONSOLE_COLOR_GREEN "%s %s\n\n", RootCommand, HelpMsgs[VER]);
return;
}
else
{
fprintf(stderr, "Unknown command name, \"%s\".\n", InCmd);
return;
}
}
static ReturnCode ProcessGenericHalt(int argc, char **argv)
{
/*Figure out what we are.*/
if (CmdIs("poweroff") || CmdIs("halt") || CmdIs("reboot"))
{
char *GCode = NULL, *SuccessMsg = NULL, *FailMsg[2] = { NULL, NULL };
const char *CArg = NULL;
signed OSCode = -1;
if (CmdIs("poweroff"))
{
GCode = MEMBUS_CODE_POWEROFF;
OSCode = OSCTL_POWEROFF;
SuccessMsg = "Power off in progress.";
FailMsg[0] = "Failed to request immediate poweroff.";
FailMsg[1] = "Failed to request poweroff.";
}
else if (CmdIs("reboot"))
{
GCode = MEMBUS_CODE_REBOOT;
OSCode = OSCTL_REBOOT;
SuccessMsg = "Reboot in progress.";
FailMsg[0] = "Failed to request immediate reboot.";
FailMsg[1] = "Failed to request reboot.";
}
else if (CmdIs("halt"))
{
GCode = MEMBUS_CODE_HALT;
OSCode = OSCTL_HALT;
SuccessMsg = "System halt in progress.";
FailMsg[0] = "Failed to request immediate halt.";
FailMsg[1] = "Failed to request halt.";
}
else
{ /*Why are we called for a different task?*/
SpitError("ProcessGenericHalt(): We are being called for a task"
"other than shutdown procedures.\nThis is probably a bug. Please report.");
return FAILURE;
}
if ((CArg = argv[1]))
{
if (argc == 2 && ArgIs("-f"))
{
sync();
reboot(OSCode);
}
else
{
puts("Bad argument(s).");
return FAILURE;
}
}
else
{
if (!SendPowerControl(GCode))
{
SpitError(FailMsg[1]);
return FAILURE;
}
else
{
printf("\n%s\n", SuccessMsg);
}
}
}
else
{
return FAILURE;
}
return SUCCESS;
}
static ReturnCode HandleEpochCommand(int argc, char **argv)
{
const char *CArg = argv[1];
/*No arguments?*/
if (argc == 1)
{
PrintEpochHelp(argv[0], NULL);;
return SUCCESS;
}
/*Help parser and shutdown commands (for possible -f).*/
if (ArgIs("help"))
{
if (argc == 2)
{
PrintEpochHelp(argv[0], NULL);
}
else if (argc == 3)
{
PrintEpochHelp(argv[0], argv[2]);
}
else
{
puts("Too many arguments.\n");
return FAILURE;
}
return SUCCESS;
}
else if (ArgIs("--version") || ArgIs("version") || ArgIs("-v"))
{
if (argc > 2)
{
puts("Too many arguments.\n");
return FAILURE;
}
printf("%s\nCompiled %s %s\n", VERSIONSTRING, __DATE__, __TIME__);
return SUCCESS;
}
else if (ArgIs("poweroff") || ArgIs("reboot") || ArgIs("halt"))
{
Bool RVal;
if (argc > 3)
{
puts("Too many arguments.\n");
PrintEpochHelp(argv[0], "reboot");
return FAILURE;
}
if (!InitMemBus(false))
{
return FAILURE;
}
RVal = !ProcessGenericHalt(argc - 1, argv + 1);
ShutdownMemBus(false);
return (int)RVal;
}
else if (ArgIs("shutdown"))
{
return EmulShutdown(argc - 1, (const char**)argv + 1);
}
else if (ArgIs("reexec"))
{
char InStream[MAX_LINE_SIZE];
if (argc > 2)
{
puts("Too many arguments.\n");
PrintEpochHelp(argv[0], "reexec");
return FAILURE;
}
if (!InitMemBus(false))
{
return FAILURE;
}
MemBus_Write(MEMBUS_CODE_RXD, false);
puts("Re-executing Epoch.");
ShutdownMemBus(false);
while (shmget(MEMKEY, MEMBUS_SIZE, 0660) != -1) usleep(100); /*Wait for it to quit...*/
while (shmget(MEMKEY, MEMBUS_SIZE, 0660) == -1) usleep(100); /*Then wait for it to start...*/
InitMemBus(false);
while (!MemBus_Read(InStream, false)) usleep(100);
if (!strcmp(InStream, MEMBUS_CODE_ACKNOWLEDGED " " MEMBUS_CODE_RXD))
{
puts("Reexecution successful.");
}
else
{
puts(CONSOLE_COLOR_RED "FAILED TO REEXECUTE!" CONSOLE_ENDCOLOR);
}
ShutdownMemBus(false);
return SUCCESS;
}
else if (ArgIs("configreload"))
{
char TRecv[MEMBUS_MSGSIZE];
char TBuf[3][MAX_LINE_SIZE];
if (argc > 2)
{
puts("Too many arguments.\n");
PrintEpochHelp(argv[0], "configreload");
return FAILURE;
}
if (!InitMemBus(false))
{
return FAILURE;
}
if (!MemBus_Write(MEMBUS_CODE_RESET, false))
{
SpitError("Failed to write to membus.");
ShutdownMemBus(false);
return FAILURE;
}
while (!MemBus_Read(TRecv, false)) usleep(1000);
snprintf(TBuf[0], sizeof TBuf[0], "%s %s", MEMBUS_CODE_ACKNOWLEDGED, MEMBUS_CODE_RESET);
snprintf(TBuf[1], sizeof TBuf[1], "%s %s", MEMBUS_CODE_FAILURE, MEMBUS_CODE_RESET);
snprintf(TBuf[2], sizeof TBuf[2], "%s %s", MEMBUS_CODE_BADPARAM, MEMBUS_CODE_RESET);
if (!strcmp(TBuf[0], TRecv))
{
puts("Reload successful.");
ShutdownMemBus(false);
return SUCCESS;
}
else if (!strcmp(TBuf[1], TRecv))
{
puts("Reload failed!");
ShutdownMemBus(false);
return FAILURE;
}
else if (!strcmp(TBuf[2], TRecv))
{
SpitError("We are being told that MEMBUS_CODE_RESET is not a valid signal! Please report to Epoch.");
ShutdownMemBus(false);
return FAILURE;
}
else
{
SpitError("Unknown response received! Can't handle this! Report to Epoch please!");
ShutdownMemBus(false);
return FAILURE;
}
}
else if (ArgIs("status"))
{
char OutBuf[MEMBUS_MSGSIZE], InBuf[MEMBUS_MSGSIZE];
char *Worker = NULL;
const char *const YN[2] = { CONSOLE_COLOR_RED "No" CONSOLE_ENDCOLOR,
CONSOLE_COLOR_GREEN "Yes" CONSOLE_ENDCOLOR };
unsigned Inc = 2;
int Stopper = argc > 2 ? argc : 3;
if (!InitMemBus(false))
{
return FAILURE;
}
for (; Inc < Stopper; ++Inc)
{
/*Send the activation code.*/
if (argc > 2)
{
snprintf(OutBuf, sizeof OutBuf, "%s %s", MEMBUS_CODE_LSOBJS, argv[Inc]);
}
else
{
strncpy(OutBuf, MEMBUS_CODE_LSOBJS, strlen(MEMBUS_CODE_LSOBJS) + 1);
}
MemBus_Write(OutBuf, false);
while (!MemBus_BinRead(InBuf, MEMBUS_MSGSIZE, false)) usleep(100);
if (!strcmp(MEMBUS_CODE_ACKNOWLEDGED " " MEMBUS_CODE_LSOBJS, InBuf))
{
puts(argc < 3 ? "No objects found!" : "Specified object not found.");
ShutdownMemBus(false);
return FAILURE;
}
while (strcmp(InBuf, MEMBUS_CODE_ACKNOWLEDGED " " MEMBUS_CODE_LSOBJS) != 0)
{
Bool FoundRL = false;
unsigned PID = 0;
Bool Started = false, Running = false, Enabled = false, PivotRoot = false, Persistent = false, Exec = false;
enum _StopMode StopMode;
unsigned char TermSignal = 0, ReloadCommandSignal = 0, *BinWorker = NULL;
unsigned StartedSince, UserID, GroupID, Inc = 0, StopTimeout;
Bool HaltCmdOnly = false, IsService = false, AutoRestart = false, NoStopWait = false, NoTrack = false;
Bool ForceShell = false, RawDescription = false, Fork = false, RunOnce = false, ForkScanOnce = false;
Bool StartFailIsCritical = false, StopFailIsCritical = false, OptNewline = false;
char RLExpect[MEMBUS_MSGSIZE], ObjectID[MAX_DESCRIPT_SIZE], ObjectDescription[MAX_DESCRIPT_SIZE];
Worker = InBuf + strlen(MEMBUS_CODE_LSOBJS " ");
/*Version matters.*/
if (strncmp(Worker, MEMBUS_LSOBJS_VERSION, strlen(MEMBUS_LSOBJS_VERSION)) != 0)
{
SpitError("LSOBJS protocol version mismatch. Expected \"" MEMBUS_LSOBJS_VERSION "\".");
while (strcmp(InBuf, MEMBUS_CODE_ACKNOWLEDGED " " MEMBUS_CODE_LSOBJS) != 0)
{ /*Don't mess up the membus, let it empty.*/
while (!MemBus_Read(InBuf, false)) usleep(10);
}
ShutdownMemBus(false);
return FAILURE;
}
Worker += strlen(MEMBUS_LSOBJS_VERSION) + 1;
BinWorker = (void*)Worker;
Started = *BinWorker++;
Running = *BinWorker++;
Enabled = *BinWorker++;
TermSignal = *BinWorker++;
ReloadCommandSignal = *BinWorker++;
/*Remove this line when we make use of ReloadCommandSignal.*/
(void)ReloadCommandSignal;
memcpy(&UserID, BinWorker, sizeof(int));
memcpy(&GroupID, (BinWorker += sizeof(int)), sizeof(int));
memcpy(&StopMode, (BinWorker += sizeof(int)), sizeof(enum _StopMode));
memcpy(&PID, (BinWorker += sizeof(enum _StopMode)), sizeof(int));
memcpy(&StartedSince, (BinWorker += sizeof(int)), sizeof(int));
memcpy(&StopTimeout, BinWorker + sizeof(int), sizeof(int));
while (!MemBus_BinRead(InBuf, MEMBUS_MSGSIZE, false)) usleep(100);
for (Worker = InBuf, Inc = 0; Worker[Inc] != ' '; ++Inc)
{ /*Get ObjectID*/
ObjectID[Inc] = Worker[Inc];
}
ObjectID[Inc] = '\0';
Worker += Inc + 1;
/*Get ObjectDescription.*/
strncpy(ObjectDescription, Worker, strlen(Worker) + 1);
/*Retrieve the options.*/
while (!MemBus_BinRead(InBuf, MEMBUS_MSGSIZE, false)) usleep(100);
for (Worker = InBuf; *Worker != 0; ++Worker)
{
if (*(unsigned char*)Worker >= COPT_MAX) continue; /*If we don't understand.*/
switch (*(unsigned char*)Worker)
{
case COPT_HALTONLY:
HaltCmdOnly = true;
break;
case COPT_PERSISTENT:
Persistent = true;
break;
case COPT_FORK:
Fork = true;
break;
case COPT_FORKSCANONCE:
ForkScanOnce = true;
break;
case COPT_SERVICE:
IsService = true;
break;
case COPT_RAWDESCRIPTION:
RawDescription = true;
break;
case COPT_AUTORESTART:
AutoRestart = true;
break;
case COPT_FORCESHELL:
ForceShell = true;
break;
case COPT_NOSTOPWAIT:
NoStopWait = true;
break;
case COPT_NOTRACK:
NoTrack = true;
break;
case COPT_STARTFAILCRITICAL:
StartFailIsCritical = true;
break;
case COPT_STOPFAILCRITICAL:
StopFailIsCritical = true;
break;
case COPT_EXEC:
Exec = true;
break;
case COPT_PIVOTROOT:
PivotRoot = true;
break;
case COPT_RUNONCE:
RunOnce = true;
break;
default:
break;
}
}
printf("ObjectID: %s\nObjectDescription: %s\nEnabled: %s | Started: %s | Running: %s | Stop mode: ",
ObjectID, ObjectDescription, YN[Enabled],
HaltCmdOnly || PivotRoot || Exec ? CONSOLE_COLOR_YELLOW "N/A" CONSOLE_ENDCOLOR : YN[Started],
HaltCmdOnly || PivotRoot || Exec ? CONSOLE_COLOR_YELLOW "N/A" CONSOLE_ENDCOLOR : YN[Running]);
if (StopMode == STOP_COMMAND) printf("Command");
else if (StopMode == STOP_NONE) printf("None");
else if (StopMode == STOP_PID) printf("PID");
else if (StopMode == STOP_PIDFILE) printf("PID File");
if (Running)
{
printf(" | PID: %u\n", PID);
}
else
{
putchar('\n');
}
if (Started)
{
time_t SS = (time_t)StartedSince, CTime = time(NULL);
struct tm TStruct;
char TimeBuf[64] = { '\0' };
unsigned Offset = (CTime - StartedSince) / 60;
localtime_r(&SS, &TStruct);
asctime_r(&TStruct, TimeBuf);
TimeBuf[strlen(TimeBuf) - 1] = '\0'; /*Nuke newline.*/
printf("Started since %s, for total of %u mins.\n", TimeBuf, Offset);
}
if (IsService || AutoRestart || HaltCmdOnly || Persistent || Fork || StopTimeout != 10 || NoTrack ||
ForceShell || RawDescription || NoStopWait || PivotRoot || RunOnce || TermSignal != SIGTERM || Exec ||
StartFailIsCritical || StopFailIsCritical)
{
printf("Options:");
if (IsService) printf(" SERVICE");
if (AutoRestart) printf(" AUTORESTART");
if (HaltCmdOnly) printf(" HALTONLY");
if (Persistent) printf(" PERSISTENT");
if (ForceShell) printf(" FORCESHELL");
if (Fork)
{
if (ForkScanOnce) printf(" FORKN");
else printf(" FORK");
}
if (RawDescription) printf(" RAWDESCRIPTION");
if (TermSignal != SIGTERM) printf(" TERMSIGNAL=%u", TermSignal);
if (NoStopWait) printf(" NOSTOPWAIT");
if (PivotRoot) printf(" PIVOT");
if (Exec) printf(" EXEC");
if (RunOnce) printf(" RUNONCE");
if (NoTrack) printf(" NOTRACK");
if (StartFailIsCritical) printf( "STARTFAILCRITICAL");
if (StopFailIsCritical) printf( "STOPFAILCRITICAL");
if (StopTimeout != 10) printf(" STOPTIMEOUT=%u", StopTimeout);
OptNewline = true;
}
/*Get exit status mappings.*/
while (!MemBus_BinRead(InBuf, MEMBUS_MSGSIZE, false)) usleep(100);
BinWorker = (void*)(InBuf + sizeof MEMBUS_CODE_LSOBJS " MXS");
Inc = *BinWorker++; /*Get the count.*/
if (Inc > 0) OptNewline = true;
for (; Inc; --Inc)
{
const char *Stringy = NULL;
unsigned char Value = *BinWorker++, ExitStatus = *BinWorker++;
if (Value == SUCCESS) Stringy = "SUCCESS";
else if (Value == WARNING) Stringy = "WARNING";
else if (Value == FAILURE) Stringy = "FAILURE";
else Stringy = "<BAD>";
printf(" MAPEXITSTATUS=%d,%s", ExitStatus, Stringy);
}
if (OptNewline) putchar('\n');
snprintf(RLExpect, sizeof RLExpect, "%s %s %s", MEMBUS_CODE_LSOBJS, MEMBUS_LSOBJS_VERSION, ObjectID);
/*Done with this, now read runlevels.*/
while (!MemBus_BinRead(InBuf, MEMBUS_MSGSIZE, false)) usleep(100);
while (!strncmp(InBuf, RLExpect, strlen(RLExpect)))
{ /*Also causes the next object to be read.*/
if (!FoundRL && !HaltCmdOnly)
{
printf("Runlevels:");
FoundRL = true;
}
Worker = InBuf + strlen(MEMBUS_CODE_LSOBJS " " MEMBUS_LSOBJS_VERSION " ") + strlen(ObjectID) + 1;
if (!HaltCmdOnly)
{
printf(" %s", Worker);
}
while (!MemBus_BinRead(InBuf, MEMBUS_MSGSIZE, false)) usleep(100);
}
if (FoundRL) putchar('\n');
if (UserID || GroupID)
{
struct passwd *UserStruct = getpwuid(UserID);
struct group *GroupStruct = getgrgid(GroupID);
if (UserStruct) printf("User: %s\n", UserStruct->pw_name);
if (GroupStruct && GroupID != 0) printf("Group: %s\n", GroupStruct->gr_name);
}
if (argc == 2)
{
puts("-------");
}
}
if (argc > 3)
{
puts("-------");
}
}
ShutdownMemBus(false);
return SUCCESS;
}
else if (ArgIs("runlevel"))
{
char InBuf[MEMBUS_MSGSIZE];
ReturnCode RV = SUCCESS;
if (argc > 3)
{
puts("Too many arguments.");
PrintEpochHelp(argv[0], "runlevel");
return FAILURE;
}
if (!InitMemBus(false))
{
return FAILURE;
}
if (argc == 2)
{
MemBus_Write(MEMBUS_CODE_GETRL, false);
while (!MemBus_Read(InBuf, false)) usleep(1000);
if (!strcmp(MEMBUS_CODE_BADPARAM " " MEMBUS_CODE_GETRL, InBuf))
{
SpitError("We are being told that MEMBUS_CODE_GETRL is not valid.\n"
"This is a bug. Please report to Epoch.");
RV = FAILURE;
}
else if (!strncmp(MEMBUS_CODE_GETRL " ", InBuf, strlen(MEMBUS_CODE_GETRL " ")))
{
printf("Current runlevel is \"%s\".\n", InBuf + strlen(MEMBUS_CODE_GETRL " "));
RV = SUCCESS;
}
}
else
{
char OutBuf[MEMBUS_MSGSIZE];
char PossibleResponses[3][MEMBUS_MSGSIZE] = { { '\0' } };
snprintf(OutBuf, sizeof OutBuf, "%s %s", MEMBUS_CODE_RUNLEVEL, argv[2]);
snprintf(PossibleResponses[0], MEMBUS_MSGSIZE, "%s %s", MEMBUS_CODE_ACKNOWLEDGED, OutBuf);
snprintf(PossibleResponses[1], MEMBUS_MSGSIZE, "%s %s", MEMBUS_CODE_FAILURE, OutBuf);
snprintf(PossibleResponses[2], MEMBUS_MSGSIZE, "%s %s", MEMBUS_CODE_BADPARAM, OutBuf);
MemBus_Write(OutBuf, false);
while (!MemBus_Read(InBuf, false)) usleep(1000);
if (!strcmp(PossibleResponses[0], InBuf))
{
RV = SUCCESS;
}
else if (!strcmp(PossibleResponses[1], InBuf))
{
RV = FAILURE;
fprintf(stderr, "Unable to switch to runlevel %s.\n", argv[2]);
}
else if (!strcmp(PossibleResponses[2], InBuf))
{
RV = FAILURE;
SpitError("We are being told we sent bad data over the membus.\nThis is a bug. Please report.");
}
else
{
RV = FAILURE;
SpitError("We have received a corrupted response over the membus.\nThis is a bug. Please report.");
}
}