xref: /openbmc/libmctp/utils/mctp-pipe.c (revision e4d8456f)
1 /* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */
2 
3 #include <assert.h>
4 #include <err.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <sys/poll.h>
9 #include <sys/socket.h>
10 
11 #include "libmctp.h"
12 #include "libmctp-serial.h"
13 
14 static void rx_message(uint8_t eid, void *data, void *msg, size_t len)
15 {
16 	(void)eid;
17 	(void)data;
18 	write(STDOUT_FILENO, msg, len);
19 }
20 
21 int main(void)
22 {
23 	struct mctp_binding_serial *serial[2];
24 	mctp_eid_t eids[] = {8, 9};
25 	struct pollfd pollfds[3];
26 	int rc, n, mctp_fds[2];
27 	struct mctp *mctp[2];
28 
29 	mctp[0] = mctp_init();
30 	mctp[1] = mctp_init();
31 
32 	assert(mctp[0] && mctp[1]);
33 
34 	serial[0] = mctp_serial_init();
35 	serial[1] = mctp_serial_init();
36 
37 	assert(serial[0] && serial[1]);
38 
39 	rc = socketpair(AF_UNIX, SOCK_STREAM, 0, mctp_fds);
40 	if (rc)
41 		err(EXIT_FAILURE, "Can't create sockets");
42 
43 	mctp_serial_open_fd(serial[0], mctp_fds[0]);
44 	mctp_serial_open_fd(serial[1], mctp_fds[1]);
45 
46 	mctp_register_bus(mctp[0], mctp_binding_serial_core(serial[0]), eids[0]);
47 	mctp_register_bus(mctp[1], mctp_binding_serial_core(serial[1]), eids[1]);
48 
49 	mctp_set_rx_all(mctp[1], rx_message, NULL);
50 
51 	pollfds[0].fd = mctp_fds[0];
52 	pollfds[0].events = POLLIN;
53 	pollfds[1].fd = mctp_fds[1];
54 	pollfds[1].events = POLLIN;
55 	pollfds[2].fd = STDIN_FILENO;
56 	pollfds[2].events = POLLIN;
57 	n = 3;
58 
59 	for (;;) {
60 		uint8_t buf[1024];
61 
62 		rc = poll(pollfds, n, -1);
63 		if (rc < 0)
64 			return EXIT_FAILURE;
65 
66 		if (pollfds[0].revents) {
67 			rc = mctp_serial_read(serial[0]);
68 			if (rc)
69 				pollfds[0].fd = -1;
70 		}
71 
72 		if (pollfds[1].revents) {
73 			rc = mctp_serial_read(serial[1]);
74 			if (rc)
75 				pollfds[1].fd = -1;
76 		}
77 
78 		if (n > 2 && pollfds[2].revents) {
79 			rc = read(STDIN_FILENO, buf, sizeof(buf));
80 			if (rc == 0) {
81 				n = 2;
82 				close(mctp_fds[0]);
83 				pollfds[0].fd = -1;
84 			} else if (rc < 0) {
85 				err(EXIT_FAILURE, "read");
86 			} else {
87 				mctp_message_tx(mctp[0], eids[1], buf, rc);
88 			}
89 		}
90 
91 		if (n == 2 && pollfds[0].fd < 0 && pollfds[1].fd < 0)
92 			break;
93 	}
94 
95 	return EXIT_SUCCESS;
96 
97 }
98