Debian Codegraph @

tests/proxy-test-server.c

raw symbols SCIP
1 /*
2 * Copyright © Stéphane Raimbault <[email protected]>
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7 /* Proxy test server: listens on TCP port 1503 and forwards all requests
8 to a backend server on TCP port 1502 using modbus_proxy(). */
9
10 #include <errno.h>
11 #include <modbus.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <unistd.h>
16
17 #ifndef PROXY_PORT
18 #define PROXY_PORT 1503
19 #endif
20
21 #ifndef BACKEND_PORT
22 #define BACKEND_PORT 1502
23 #endif
24
25 int main(int argc, char *argv[])
26 {
27 modbus_t *frontend_ctx;
28 modbus_t *backend_ctx;
29 int s = -1;
30 int rc;
31 uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
32 char *backend_ip = "127.0.0.1";
33
34 if (argc > 1) {
35 backend_ip = argv[1];
36 }
37
38 /* Frontend: accept connections from clients */
39 frontend_ctx = modbus_new_tcp("0.0.0.0", PROXY_PORT);
40 if (frontend_ctx == NULL) {
41 fprintf(stderr, "Failed to create frontend context: %s\n",
42 modbus_strerror(errno));
43 return -1;
44 }
45
46 /* Backend: connect to the real Modbus server */
47 backend_ctx = modbus_new_tcp(backend_ip, BACKEND_PORT);
48 if (backend_ctx == NULL) {
49 fprintf(stderr, "Failed to create backend context: %s\n",
50 modbus_strerror(errno));
51 modbus_free(frontend_ctx);
52 return -1;
53 }
54
55 modbus_set_debug(frontend_ctx, TRUE);
56 modbus_set_debug(backend_ctx, TRUE);
57
58 /* Connect to the backend server */
59 if (modbus_connect(backend_ctx) == -1) {
60 fprintf(stderr, "Backend connection failed: %s\n",
61 modbus_strerror(errno));
62 modbus_free(frontend_ctx);
63 modbus_free(backend_ctx);
64 return -1;
65 }
66
67 /* Listen for frontend client connections */
68 s = modbus_tcp_listen(frontend_ctx, 1);
69 if (s == -1) {
70 fprintf(stderr, "Frontend listen failed: %s\n",
71 modbus_strerror(errno));
72 modbus_close(backend_ctx);
73 modbus_free(frontend_ctx);
74 modbus_free(backend_ctx);
75 return -1;
76 }
77
78 modbus_tcp_accept(frontend_ctx, &s);
79
80 for (;;) {
81 do {
82 rc = modbus_receive(frontend_ctx, query);
83 /* Filtered queries return 0 */
84 } while (rc == 0);
85
86 if (rc == -1) {
87 /* Connection closed or error */
88 break;
89 }
90
91 /* Forward request to backend and relay response */
92 rc = modbus_proxy(frontend_ctx, backend_ctx, query, rc);
93 if (rc == -1) {
94 fprintf(stderr, "Proxy error: %s\n", modbus_strerror(errno));
95 /* Continue serving, the exception was already sent */
96 }
97 }
98
99 printf("Proxy server exiting: %s\n", modbus_strerror(errno));
100
101 if (s != -1) {
102 close(s);
103 }
104 modbus_close(backend_ctx);
105 modbus_close(frontend_ctx);
106 modbus_free(backend_ctx);
107 modbus_free(frontend_ctx);
108
109 return 0;
110 }