|
root / tools
tools Plain Text 508 lines 31.1 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
# sysv-wrapper Makefile.
#
# Build:    make
# Install:  make install DESTDIR=<root>      (defaults to /)
# Clean:    make clean
#
# Installs the wrapper at /sbin/sysv-wrapper and symlinks the legacy
# tool names to it. /sbin/init is NOT symlinked here — that path is
# the zyginit daemon binary. If you want sysv-wrapper to handle
# `init <N>` too, move zyginit aside (e.g. to /sbin/zyginit) and
# symlink /sbin/init -> sysv-wrapper instead.

CC      ?= gcc
CFLAGS  ?= -O2 -Wall
DESTDIR ?=
SBIN     = $(DESTDIR)/sbin
WRAPPER  = $(SBIN)/sysv-wrapper

all: sysv-wrapper

sysv-wrapper: wrapper.c version.h
	$(CC) $(CFLAGS) -o $@ wrapper.c

install: sysv-wrapper
	install -d $(SBIN)
	install -m 0755 sysv-wrapper $(WRAPPER)
	ln -sf sysv-wrapper $(SBIN)/halt
	ln -sf sysv-wrapper $(SBIN)/reboot
	ln -sf sysv-wrapper $(SBIN)/poweroff
	ln -sf sysv-wrapper $(SBIN)/telinit

clean:
	rm -f sysv-wrapper

.PHONY: all install clean
ELF>@@�8@8@ @@@���pp--   ���-�=�=���-�=�=��PPP  ppp$$###��S�tdPPP  P�td�!�!�!44Q�tdR�td�-�=�=88GNU��GNU-A���Tb���䎸��n��/lib64/ld-linux-x86-64.so.2��e�mi� <b;� 
[� R.4C"freestrdup__xpg_basename__libc_start_mainexeclstderrfprintf__cxa_finalizestrerrorfwritestrcmp__errno_locationlibc.so.6GLIBC_2.34GLIBC_2.2.5_ITM_deregisterTMCloneTable__gmon_start___ITM_registerTMCloneTablez����ui	��= �=�X@X@�?�?�?�?�?�?@@@@ @(@	0@
8@@@
H@��H��H��/H��t��H����5�/�%�/@�%�/h������%�/h������%�/h������%�/h������%�/h������%�/h������%�/h������%�/h�p����%�/h�`����%�/h	�P����%/f�AVSPH��H��H�5�H��1�1������H��.L�0�0����8�����H�5�H��L��H��I��1�H��[A^�4���@��1�I��^H��H���PTE1�1�H�=��S.�f.�H�=�.H��.H9�tH�6.H��t	�����H�=�.H�5�.H)�H��H��?H��H�H��tH�.H��t��fD�����=u.u+UH�=�-H��tH�=V.������d����M.]������w����UAWAVATSI����H�>�[���H����I��H���'���H�Ã�|UM�fH�5�L���������tA�<$-u7A�|$Vu/A�|$u'H�=�H��1�H��1������L�������_H�5�H���������tH�5jH���������u~��EH��,H�8I�H�5�1��t����H��,H�H�=���o�����I�N���Ѓ�C��H��Hc�H���H�=D�������H�5�
H���������uH�=�
�g�����H�5�
H���������u*H�=�
�C����qH�=�
�5����cH�=�
�'����UH�5�
H���������uH�=y
�����4H��+H�8H�5j
H������H��+H�8I�H�5�
1��`������[A\A^A_]���H��H���i���E���������������������������������������������������������������������������������������������������������������������������������������E�������������������������������������������������������������������������������������������������������������������������������E���out of memory
--version%s %s
0.1.2telinithaltrebootpoweroffsysv-wrapper: unknown invocation '%s'
usage: %s <runlevel>
singlemultireload%s: unknown runlevel '%s'
/sbin/zygctl%s: cannot exec %s: %s
sysv-wrapper;4(���h����������H���P8����zRx�����&D$4�����FJw�?;*3$"\@���8t�����ABB B(A0������(B BBA$�����\BAA ��PABGNU`~��FDO{"type":"deb","os":"ubuntu","name":"glibc","version":"2.42-0ubuntu3.1","architecture":"amd64"} �z
 �=�=���o�p�
��?����	���o���ox���o���oP���o�=6FVfv�����X@GCC: (Ubuntu 15.2.0-4ubuntu4) 15.2.0Ubuntu clang version 21.1.2 (2ubuntu6)��	# ���\(��3p5�H�^`@j�=� ��=(���#����=��!��?�
*G r P@c`@j �pP@}�� �X@� ��h@v@&�`@�0�`@ 9Las"��Scrt1.o__abi_tagwrapper.crun_zygctlcrtstuff.cderegister_tm_clones__do_global_dtors_auxcompleted.0__do_global_dtors_aux_fini_array_entryframe_dummy__frame_dummy_init_array_entry__FRAME_END___DYNAMIC__GNU_EH_FRAME_HDR_GLOBAL_OFFSET_TABLE_free@GLIBC_2.2.5__libc_start_main@GLIBC_2.34__errno_location@GLIBC_2.2.5_ITM_deregisterTMCloneTable_edata_fini__data_startstrcmp@GLIBC_2.2.5fprintf@GLIBC_2.2.5__gmon_start____dso_handle_IO_stdin_used__xpg_basename@GLIBC_2.2.5_end__bss_startmainfwrite@GLIBC_2.2.5__TMC_END___ITM_registerTMCloneTablestrdup@GLIBC_2.2.5strerror@GLIBC_2.2.5execl@GLIBC_2.2.5__cxa_finalize@GLIBC_2.2.5_initstderr@GLIBC_2.2.5.symtab.strtab.shstrtab.note.gnu.property.note.gnu.build-id.interp.gnu.hash.dynsym.dynstr.gnu.version.gnu.version_r.rela.dyn.rela.plt.init.plt.got.text.fini.rodata.eh_frame_hdr.eh_frame.note.ABI-tag.note.package.init_array.fini_array.dynamic.got.plt.data.bss.commentPP .pp$A��I���o��$S���[pp�c���oPP"p���oxx0����B�����  �������@�  
�  ���!�!4�0"0"��## �(#(#p��=�-��=�-�=�-���?�/0�?�/hP@P0`@`00`0L�0h	5��7(/******************************************************************************
                __               ____                __
               / /   ___  ____ _/ __/_____________ _/ /__
              / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
             / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
            /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

    (C)opyright 2025-2026, Leafscale, LLC -  https://www.leafscale.com

    Project: zyginit
   Filename: version.h
    Authors: Chris Tusa <chris.tusa@leafscale.com>
    License: <see LICENSE file included with this source code>
Description: Generated version constant. Do not edit by hand — regenerated
             by scripts/bump-version.sh.

******************************************************************************/

#ifndef ZYGINIT_VERSION_H
#define ZYGINIT_VERSION_H
#define ZYGINIT_VERSION "0.2.7"
#endif
/*
 * sysv-wrapper — translate traditional sysv-init commands to zygctl calls.
 *
 * Installed as multiple symlinks pointing at the same binary; we dispatch
 * on argv[0] (basename) so each link behaves like the legacy tool.
 *
 *   /sbin/init <runlevel>     map runlevel char to a zygctl verb
 *   /sbin/telinit <runlevel>  same; telinit is the historical client name
 *   /sbin/halt                zygctl halt
 *   /sbin/reboot              zygctl reboot
 *   /sbin/poweroff            zygctl poweroff
 *
 * The wrapper itself does not connect to zyginit's socket — it just exec's
 * /sbin/zygctl with the right verb. zygctl handles the socket protocol.
 *
 * Note: when /sbin/init is run by the kernel as PID 1, it is the zyginit
 * daemon binary, NOT this wrapper. This wrapper lives at a different path
 * (or replaces /sbin/init only on systems where zyginit is at /sbin/zyginit).
 * On the current Hammerhead deploy /sbin/init IS zyginit; the wrapper
 * is therefore meant for /sbin/halt, /sbin/reboot, /sbin/poweroff,
 * /sbin/telinit. If you DO want /sbin/init to be this wrapper, install
 * zyginit at /sbin/zyginit and point the kernel boot path there.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>
#include <errno.h>
#include "version.h"

#define ZYGCTL "/sbin/zygctl"

static int
run_zygctl(const char *verb)
{
	execl(ZYGCTL, "zygctl", verb, (char *)NULL);
	/* execl returns only on failure */
	(void) fprintf(stderr, "%s: cannot exec %s: %s\n",
	    "sysv-wrapper", ZYGCTL, strerror(errno));
	return (1);
}

static int
init_dispatch(int argc, char **argv)
{
	if (argc < 2) {
		(void) fprintf(stderr, "usage: %s <runlevel>\n", argv[0]);
		return (1);
	}

	switch (argv[1][0]) {
	case '0':
		return (run_zygctl("halt"));
	case '5':
		return (run_zygctl("poweroff"));
	case '6':
		return (run_zygctl("reboot"));
	case '1':
	case 's':
	case 'S':
		return (run_zygctl("single"));
	case '2':
	case '3':
	case '4':
		return (run_zygctl("multi"));
	case 'q':
	case 'Q':
		return (run_zygctl("reload"));
	default:
		(void) fprintf(stderr,
		    "%s: unknown runlevel '%s'\n", argv[0], argv[1]);
		return (1);
	}
}

int
main(int argc, char **argv)
{
	const char *me;
	char *argv0_copy;

	/* basename(3) on illumos modifies its argument, so duplicate first */
	argv0_copy = strdup(argv[0]);
	if (argv0_copy == NULL) {
		(void) fprintf(stderr, "out of memory\n");
		return (1);
	}
	me = basename(argv0_copy);

	if (argc >= 2 &&
	    (strcmp(argv[1], "--version") == 0 ||
	     strcmp(argv[1], "-V") == 0)) {
		(void) printf("%s %s\n", me, ZYGINIT_VERSION);
		free(argv0_copy);
		return (0);
	}

	if (strcmp(me, "init") == 0 || strcmp(me, "telinit") == 0)
		return (init_dispatch(argc, argv));
	if (strcmp(me, "halt") == 0)
		return (run_zygctl("halt"));
	if (strcmp(me, "reboot") == 0)
		return (run_zygctl("reboot"));
	if (strcmp(me, "poweroff") == 0)
		return (run_zygctl("poweroff"));

	(void) fprintf(stderr, "sysv-wrapper: unknown invocation '%s'\n", me);
	return (1);
}
[package]
name = "zygctl"
version = "0.2.7"
author = "Chris Tusa <chris.tusa@leafscale.com>"
description = "Administrative CLI for zyginit"
license = "CDDL-1.0"

[build]
entry = "src/main.reef"
output = "zygctl"
output_dir = "build"
source_dirs = ["src"]
/******************************************************************************
                __               ____                __
               / /   ___  ____ _/ __/_____________ _/ /__
              / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
             / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
            /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

    (C)opyright 2025-2026, Leafscale, LLC -  https://www.leafscale.com

    Project: zygctl
   Filename: main.reef
    Authors: Chris Tusa <chris.tusa@leafscale.com>
    License: <see LICENSE file included with this source code>
Description: Administrative CLI for zyginit service manager

******************************************************************************/

module zygctl

import sys.args as args
import sys.env as env
import sys.process as process
import net.unix as unix
import io.file
import io.dir
import core.str
import core.result as res
import version

extern "C" fn zyginit_symlink(target: string, linkpath: string): int
extern "C" fn zyginit_isatty(fd: int): int

fn client_should_be_plain(): bool
    if env.has_env("NO_COLOR")  return true  end if
    if zyginit_isatty(1) == 0   return true  end if
    let term = env.get_env_or("TERM", "")
    if str.length(term) == 0    return true  end if
    if term == "dumb"           return true  end if
    return false
end client_should_be_plain

fn SOCKET_PATH(): string
    return env.get_env_or("ZYGINIT_SOCKET", "/var/run/zyginit.sock")
end SOCKET_PATH

fn CONFIG_DIR(): string
    return env.get_env_or("ZYGINIT_CONFIG_DIR", "/etc/zyginit")
end CONFIG_DIR

proc main()
    let argc = args.count()

    if argc < 2
        print_usage()
        return
    end if

    let command = args.get(1)

    // Local commands (no daemon needed)
    if command == "help" or command == "--help" or command == "-h"
        print_usage()
        return
    end if

    if command == "version" or command == "--version"
        println("zygctl " + version.VERSION())
        return
    end if

    // Local commands that operate on the filesystem directly
    if command == "enable"
        if argc < 3
            println("error: usage: zygctl enable <service>")
            return
        end if
        cmd_enable(args.get(2))
        return
    end if

    if command == "disable"
        if argc < 3
            println("error: usage: zygctl disable <service>")
            return
        end if
        cmd_disable(args.get(2))
        return
    end if

    // single/multi are forwarded to zyginit's socket — handled there.
    // (Earlier versions of zygctl had local stubs for these; removed
    // now that the daemon implements runlevel transitions.)

    // TTY-aware dispatch for status and list:
    // When stdout is not a TTY (piped/redirected), or when NO_COLOR is set,
    // append PLAIN so the daemon sends plain text without ANSI escapes.
    if command == "status"
        mut req = "status"
        if client_should_be_plain()
            req = "status plain"
        end if
        if argc >= 3
            req = str.concat(req, " ")
            req = str.concat(req, args.get(2))
        end if
        req = str.concat(req, "\n")
        let connect_r = unix.unix_connect(SOCKET_PATH())
        if res.is_err(connect_r)
            println("zygctl: cannot connect to zyginit at " + SOCKET_PATH())
            println("zygctl: is zyginit running?")
            return
        end if
        let fd = res.unwrap_ok(connect_r)
        unix.unix_send(fd, req)
        let resp_r = unix.unix_recv(fd, 4096)
        unix.unix_close(fd)
        let resp = res.unwrap_or(resp_r, "")
        if str.length(resp) > 0
            print(resp)
        end if
        return
    end if

    if command == "list"
        mut req = "list"
        if client_should_be_plain()
            req = "list plain"
        end if
        req = str.concat(req, "\n")
        let connect_r = unix.unix_connect(SOCKET_PATH())
        if res.is_err(connect_r)
            println("zygctl: cannot connect to zyginit at " + SOCKET_PATH())
            println("zygctl: is zyginit running?")
            return
        end if
        let fd = res.unwrap_ok(connect_r)
        unix.unix_send(fd, req)
        let resp_r = unix.unix_recv(fd, 4096)
        unix.unix_close(fd)
        let resp = res.unwrap_or(resp_r, "")
        if str.length(resp) > 0
            print(resp)
        end if
        return
    end if

    // Build the message to send to zyginit
    mut message = command

    if argc >= 3
        message = str.concat(message, " ")
        message = str.concat(message, args.get(2))
    end if

    message = str.concat(message, "\n")

    // Connect to zyginit socket
    let sock_path = SOCKET_PATH()
    let connect_r = unix.unix_connect(sock_path)

    if res.is_err(connect_r)
        println("zygctl: cannot connect to zyginit at " + sock_path)
        println("zygctl: is zyginit running?")
        return
    end if
    let fd = res.unwrap_ok(connect_r)

    // Send command
    unix.unix_send(fd, message)

    // Read response
    let response_r = unix.unix_recv(fd, 4096)
    unix.unix_close(fd)
    let response = res.unwrap_or(response_r, "")

    if str.length(response) > 0
        print(response)
    end if
end main

// ============================================================================
// Local commands — enable/disable (filesystem operations, no daemon needed)
// ============================================================================

proc cmd_enable(name: string)
    let config_dir = CONFIG_DIR()
    let svc_dir = str.concat(str.concat(config_dir, "/services/"), name)

    if not dir.dir_exists(svc_dir)
        println("error: no service definition found: " + svc_dir)
        return
    end if

    let enabled_dir = str.concat(config_dir, "/enabled.d")

    // Create enabled.d/ if it does not exist
    if not dir.dir_exists(enabled_dir)
        if res.is_err(dir.create_dir(enabled_dir))
            println("error: cannot create " + enabled_dir)
            return
        end if
    end if

    let link_path = str.concat(str.concat(enabled_dir, "/"), name)

    if file.fileExists(link_path)
        println(name + " is already enabled")
        return
    end if

    // Create symlink: enabled.d/<name> -> ../services/<name>
    let target = str.concat("../services/", name)
    let rc = zyginit_symlink(target, link_path)
    if rc < 0
        println("error: failed to create symlink for " + name)
        return
    end if

    println(name + " enabled")
end cmd_enable

proc cmd_disable(name: string)
    let config_dir = CONFIG_DIR()
    let enabled_dir = str.concat(config_dir, "/enabled.d")
    let link_path = str.concat(str.concat(enabled_dir, "/"), name)

    if not file.fileExists(link_path)
        println(name + " is not enabled")
        return
    end if

    if res.is_ok(file.deleteFile(link_path))
        println(name + " disabled")
    else
        println("error: failed to remove " + link_path)
    end if
end cmd_disable

// ============================================================================
// Usage
// ============================================================================

proc print_usage()
    println("zygctl — zyginit service control")
    println("")
    println("Usage: zygctl <command> [argument]")
    println("")
    println("Commands:")
    println("  status [name]    Show service status (all or one)")
    println("  start <name>     Start a service")
    println("  stop <name>      Stop a service")
    println("  restart <name>   Restart a service")
    println("  enable <name>    Enable a service (symlink in enabled.d/)")
    println("  disable <name>   Disable a service (remove from enabled.d/)")
    println("  reload           Reload service configuration")
    println("  replace [--wait=N]")
    println("                   Replace running zyginit via execve(/sbin/init);")
    println("                   keeps services alive across the swap")
    println("  log <name>       Show service output log")
    println("  list             List all service definitions")
    println("  halt             Cleanly stop all services and halt the system")
    println("  reboot           Cleanly stop all services and reboot")
    println("  poweroff         Cleanly stop all services and power off")
    println("  single           Transition to single-user (recovery) mode")
    println("  multi            Transition to multi-user mode")
    println("  version          Show version")
    println("  help             Show this help")
    println("")
    println("Environment:")
    println("  ZYGINIT_SOCKET     Socket path (default: /var/run/zyginit.sock)")
    println("  ZYGINIT_CONFIG_DIR Config directory (default: /etc/zyginit)")
end print_usage

end module
/*
 * symlink_wrapper.c — Wrapper for symlink() to avoid const char* FFI conflict
 *
 * Reef generates char* for string parameters, but POSIX symlink() expects
 * const char*. This thin wrapper bridges the two declarations.
 */

#include <unistd.h>

int zyginit_symlink(char *target, char *linkpath) {
    return symlink(target, linkpath);
}

int zyginit_isatty(int fd) {
    return isatty(fd) ? 1 : 0;
}
/******************************************************************************
                __               ____                __
               / /   ___  ____ _/ __/_____________ _/ /__
              / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
             / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
            /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

    (C)opyright 2025-2026, Leafscale, LLC -  https://www.leafscale.com

    Project: zygctl
   Filename: version.reef
    Authors: Chris Tusa <chris.tusa@leafscale.com>
    License: <see LICENSE file included with this source code>
Description: Generated version constant. Do not edit by hand — regenerated
             by scripts/bump-version.sh.

******************************************************************************/

module version

export
    fn VERSION(): string
end export

fn VERSION(): string
    return "0.2.7"
end VERSION

end module