blob: 678391ff285859b68eea5aeac2fcd09ee2f3f6ad [file] [log] [blame]
Andrew Jeffery11cd2542021-05-03 11:03:30 +09301// SPDX-License-Identifier: Apache-2.0
2// Copyright (C) 2021 IBM Corp.
3
4#include <err.h>
5#include <fcntl.h>
6#include <getopt.h>
7#include <libgen.h>
8#include <limits.h>
9#include <linux/reboot.h>
10#include <stdlib.h>
11#include <string.h>
12#include <sys/reboot.h>
13#include <sys/stat.h>
14#include <sys/types.h>
15#include <unistd.h>
16
Andrew Jefferydb47cd72022-01-13 14:14:41 +103017static void process_debug(int sink)
18{
19 static const char action = 'c';
20 ssize_t rc;
21
22 sync();
23
24 if ((rc = write(sink, &action, sizeof(action))) == sizeof(action))
25 return;
26
27 if (rc == -1) {
28 warn("Failed to execute debug command");
29 } else {
30 warnx("Failed to execute debug command: %zd", rc);
31 }
32}
33
Andrew Jeffery11cd2542021-05-03 11:03:30 +093034static int process(int source, int sink)
35{
36 ssize_t ingress;
37 char command;
38
39 while ((ingress = read(source, &command, sizeof(command))) == sizeof(command)) {
Andrew Jeffery11cd2542021-05-03 11:03:30 +093040 ssize_t rc;
41
42 switch (command) {
Andrew Jefferydb47cd72022-01-13 14:14:41 +103043 case 'D':
44 process_debug(sink);
Andrew Jeffery11cd2542021-05-03 11:03:30 +093045 break;
46 case 'R':
47 sync();
48
49 if ((rc = reboot(LINUX_REBOOT_CMD_RESTART))) {
50 if (rc == -1)
51 warn("Failed to reboot BMC");
52 else
53 warnx("Failed to reboot BMC: %zd", rc);
54 }
55 break;
56 default:
57 warnx("Unexpected command: 0x%02x (%c)", command, command);
58 }
59 }
60
61 if (ingress == -1)
62 warn("Failed to read from source");
63
64 return ingress;
65}
66
67int main(int argc, char * const argv[])
68{
69 char devnode[PATH_MAX];
70 char *devid;
71 int source;
72 int sink;
73
74 while (1) {
75 static struct option long_options[] = {
76 {0, 0, 0, 0},
77 };
78 int c;
79
80 c = getopt_long(argc, argv, "", long_options, NULL);
81 if (c == -1)
82 break;
83 }
84
85 source = 0;
86 sink = 1;
87
88 if (optind < argc) {
89 char devpath[PATH_MAX];
90
91 strncpy(devpath, argv[optind], sizeof(devpath));
92 devpath[PATH_MAX - 1] = '\0';
93 devid = basename(devpath);
94
95 strncpy(devnode, "/dev/", sizeof(devnode));
96 strncat(devnode, devid, sizeof(devnode));
97 devnode[PATH_MAX - 1] = '\0';
98
99 if ((source = open(devnode, O_RDONLY)) == -1)
100 err(EXIT_FAILURE, "Failed to open %s", devnode);
101
102 optind++;
103 }
104
105 if (optind < argc) {
106 if ((sink = open(argv[optind], O_WRONLY)) == -1)
107 err(EXIT_FAILURE, "Failed to open %s", argv[optind]);
108
109 optind++;
110 }
111
112 if (optind < argc)
113 err(EXIT_FAILURE, "Found %d unexpected arguments", argc - optind);
114
115 if (process(source, sink) < 0)
116 errx(EXIT_FAILURE, "Failure while processing command stream");
117
118 return 0;
119}