Debian Codegraph @

src/modbus-tcp.c

raw symbols SCIP
1 /*
2 * Copyright © Stéphane Raimbault <[email protected]>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 */
6
7 // clang-format off
8 #if defined(_WIN32)
9 # define OS_WIN32
10 /* ws2_32.dll has getaddrinfo and freeaddrinfo on Windows XP and later.
11 * minwg32 headers check WINVER before allowing the use of these */
12 # ifndef WINVER
13 # define WINVER 0x0501
14 # endif
15 #endif
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <stdint.h>
20 #include <limits.h>
21 #include <string.h>
22 #include <errno.h>
23 #ifndef _MSC_VER
24 #include <unistd.h>
25 #endif
26 #include <signal.h>
27 #include <sys/types.h>
28
29 #if defined(_WIN32)
30 /* Already set in modbus-tcp.h but it seems order matters in VS2005 */
31 # include <winsock2.h>
32 # include <ws2tcpip.h>
33 # define SHUT_RDWR 2
34 # define close closesocket
35 # define strdup _strdup
36 #else
37 # include <sys/socket.h>
38 # include <sys/ioctl.h>
39
40 #if defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ < 5)
41 # define OS_BSD
42 # include <netinet/in_systm.h>
43 #endif
44
45 #ifdef HAVE_NETINET_IN_H
46 #include <netinet/in.h>
47 #endif /* HAVE_NETINET_IN_H */
48 #ifdef HAVE_NETINET_IP_H
49 #include <netinet/ip.h>
50 #endif /* HAVE_NETINET_IP_H */
51 # include <netinet/tcp.h>
52 # include <arpa/inet.h>
53 # include <netdb.h>
54 #endif
55
56 #if !defined(MSG_NOSIGNAL)
57 #define MSG_NOSIGNAL 0
58 #endif
59
60 #if defined(_AIX) && !defined(MSG_DONTWAIT)
61 #define MSG_DONTWAIT MSG_NONBLOCK
62 #endif
63 // clang-format on
64
65 #include "modbus-private.h"
66
67 #include "modbus-tcp-private.h"
68 #include "modbus-tcp.h"
69
70 #ifdef OS_WIN32
71 static int _modbus_tcp_init_win32(void)
72 {
73 /* Initialise Windows Socket API */
74 WSADATA wsaData;
75
76 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
77 fprintf(stderr,
78 "WSAStartup() returned error code %d\n",
79 (unsigned int) GetLastError());
80 errno = EIO;
81 return -1;
82 }
83 return 0;
84 }
85 #endif
86
87 static int _modbus_set_slave(modbus_t *ctx, int slave)
88 {
89 int max_slave = (ctx->quirks & MODBUS_QUIRK_MAX_SLAVE) ? 255 : 247;
90
91 /* Broadcast address is 0 (MODBUS_BROADCAST_ADDRESS) */
92 if (slave >= 0 && slave <= max_slave) {
93 ctx->slave = slave;
94 } else if (slave == MODBUS_TCP_SLAVE) {
95 /* The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to
96 * restore the default value. */
97 ctx->slave = slave;
98 } else {
99 errno = EINVAL;
100 return -1;
101 }
102
103 return 0;
104 }
105
106 /* Builds a TCP request header */
107 static int _modbus_tcp_build_request_basis(
108 modbus_t *ctx, int function, int addr, int nb, uint8_t *req)
109 {
110 modbus_tcp_t *ctx_tcp = ctx->backend_data;
111
112 /* Increase transaction ID */
113 if (ctx_tcp->t_id < UINT16_MAX)
114 ctx_tcp->t_id++;
115 else
116 ctx_tcp->t_id = 0;
117 req[0] = ctx_tcp->t_id >> 8;
118 req[1] = ctx_tcp->t_id & 0x00ff;
119
120 /* Protocol Modbus */
121 req[2] = 0;
122 req[3] = 0;
123
124 /* Length will be defined later by set_req_length_tcp at offsets 4
125 and 5 */
126
127 req[6] = ctx->slave;
128 req[7] = function;
129 req[8] = addr >> 8;
130 req[9] = addr & 0x00ff;
131 req[10] = nb >> 8;
132 req[11] = nb & 0x00ff;
133
134 return _MODBUS_TCP_PRESET_REQ_LENGTH;
135 }
136
137 /* Builds a TCP response header */
138 static int _modbus_tcp_build_response_basis(sft_t *sft, uint8_t *rsp)
139 {
140 /* Extract from MODBUS Messaging on TCP/IP Implementation
141 Guide V1.0b (page 23/46):
142 The transaction identifier is used to associate the future
143 response with the request. */
144 rsp[0] = sft->t_id >> 8;
145 rsp[1] = sft->t_id & 0x00ff;
146
147 /* Protocol Modbus */
148 rsp[2] = 0;
149 rsp[3] = 0;
150
151 /* Length will be set later by send_msg (4 and 5) */
152
153 /* The slave ID is copied from the indication */
154 rsp[6] = sft->slave;
155 rsp[7] = sft->function;
156
157 return _MODBUS_TCP_PRESET_RSP_LENGTH;
158 }
159
160 static int _modbus_tcp_get_response_tid(const uint8_t *req)
161 {
162 return (req[0] << 8) + req[1];
163 }
164
165 static int _modbus_tcp_send_msg_pre(uint8_t *req, int req_length)
166 {
167 /* Subtract the header length to the message length */
168 int mbap_length = req_length - 6;
169
170 req[4] = mbap_length >> 8;
171 req[5] = mbap_length & 0x00FF;
172
173 return req_length;
174 }
175
176 static ssize_t _modbus_tcp_send(modbus_t *ctx, const uint8_t *req, int req_length)
177 {
178 /* MSG_NOSIGNAL
179 Requests not to send SIGPIPE on errors on stream oriented
180 sockets when the other end breaks the connection. The EPIPE
181 error is still returned. */
182 return send(ctx->s, (const char *) req, req_length, MSG_NOSIGNAL);
183 }
184
185 static int _modbus_tcp_receive(modbus_t *ctx, uint8_t *req)
186 {
187 return _modbus_receive_msg(ctx, req, MSG_INDICATION);
188 }
189
190 static ssize_t _modbus_tcp_recv(modbus_t *ctx, uint8_t *rsp, int rsp_length)
191 {
192 return recv(ctx->s, (char *) rsp, rsp_length, 0);
193 }
194
195 static int _modbus_tcp_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length)
196 {
197 return msg_length;
198 }
199
200 static int _modbus_tcp_pre_check_confirmation(modbus_t *ctx,
201 const uint8_t *req,
202 const uint8_t *rsp,
203 int rsp_length)
204 {
205 unsigned int protocol_id;
206 /* Check transaction ID */
207 if (req[0] != rsp[0] || req[1] != rsp[1]) {
208 if (ctx->debug) {
209 fprintf(stderr,
210 "Invalid transaction ID received 0x%X (not 0x%X)\n",
211 (rsp[0] << 8) + rsp[1],
212 (req[0] << 8) + req[1]);
213 }
214 errno = EMBBADDATA;
215 return -1;
216 }
217
218 /* Check protocol ID */
219 protocol_id = (rsp[2] << 8) + rsp[3];
220 if (protocol_id != 0x0) {
221 if (ctx->debug) {
222 fprintf(stderr, "Invalid protocol ID received 0x%X (not 0x0)\n", protocol_id);
223 }
224 errno = EMBBADDATA;
225 return -1;
226 }
227
228 return 0;
229 }
230
231 static int _modbus_tcp_set_ipv4_options(int s)
232 {
233 int rc;
234 int option;
235
236 /* Set the TCP no delay flag */
237 /* SOL_TCP = IPPROTO_TCP */
238 option = 1;
239 #ifdef _WIN32
240 rc = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const char *)&option, sizeof(int));
241 #else
242 rc = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const void *)&option, sizeof(int));
243 #endif
244 if (rc == -1) {
245 return -1;
246 }
247
248 /* If the OS does not offer SOCK_NONBLOCK, fall back to setting FIONBIO to
249 * make sockets non-blocking */
250 /* Do not care about the return value, this is optional */
251 #if !defined(SOCK_NONBLOCK) && defined(FIONBIO)
252 #ifdef OS_WIN32
253 {
254 /* Setting FIONBIO expects an unsigned long according to MSDN */
255 u_long loption = 1;
256 ioctlsocket(s, FIONBIO, &loption);
257 }
258 #else
259 option = 1;
260 ioctl(s, FIONBIO, &option);
261 #endif
262 #endif
263
264 #ifndef OS_WIN32
265 /**
266 * Cygwin defines IPTOS_LOWDELAY but can't handle that flag so it's
267 * necessary to workaround that problem.
268 **/
269 /* Set the IP low delay option */
270 option = IPTOS_LOWDELAY;
271 #ifdef _WIN32
272 rc = setsockopt(s, IPPROTO_IP, IP_TOS, (const char *)&option, sizeof(int));
273 #else
274 rc = setsockopt(s, IPPROTO_IP, IP_TOS, (const void *)&option, sizeof(int));
275 #endif
276 if (rc == -1) {
277 return -1;
278 }
279 #endif
280
281 return 0;
282 }
283
284 static int _connect(int sockfd,
285 const struct sockaddr *addr,
286 socklen_t addrlen,
287 const struct timeval *ro_tv)
288 {
289 int rc = connect(sockfd, addr, addrlen);
290
291 #ifdef OS_WIN32
292 int wsaError = 0;
293 if (rc == -1) {
294 wsaError = WSAGetLastError();
295 }
296
297 if (wsaError == WSAEWOULDBLOCK || wsaError == WSAEINPROGRESS) {
298 #else
299 if (rc == -1 && errno == EINPROGRESS) {
300 #endif
301 fd_set wset;
302 int optval;
303 socklen_t optlen = sizeof(optval);
304 struct timeval tv = *ro_tv;
305
306 /* Wait to be available in writing */
307 FD_ZERO(&wset);
308 if (sockfd >= FD_SETSIZE) {
309 errno = EINVAL;
310 return -1;
311 }
312 FD_SET(sockfd, &wset);
313 rc = select(sockfd + 1, NULL, &wset, NULL, &tv);
314 if (rc < 0) {
315 /* Fail */
316 return -1;
317 }
318
319 if (rc == 0) {
320 /* Timeout */
321 errno = ETIMEDOUT;
322 return -1;
323 }
324
325 /* The connection is established if SO_ERROR and optval are set to 0 */
326 rc = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
327 if (rc == 0 && optval == 0) {
328 return 0;
329 } else {
330 errno = ECONNREFUSED;
331 return -1;
332 }
333 }
334 return rc;
335 }
336
337 /* Establishes a modbus TCP connection with a Modbus server. */
338 static int _modbus_tcp_connect(modbus_t *ctx)
339 {
340 int rc;
341 int s;
342 /* Specialized version of sockaddr for Internet socket address (same size) */
343 struct sockaddr_in addr;
344 modbus_tcp_t *ctx_tcp = ctx->backend_data;
345 int flags = SOCK_STREAM;
346
347 #ifdef OS_WIN32
348 if (_modbus_tcp_init_win32() == -1) {
349 return -1;
350 }
351 #endif
352
353 #ifdef SOCK_CLOEXEC
354 flags |= SOCK_CLOEXEC;
355 #endif
356
357 #ifdef SOCK_NONBLOCK
358 flags |= SOCK_NONBLOCK;
359 #endif
360
361 s = socket(PF_INET, flags, 0);
362 if (s < 0) {
363 return -1;
364 }
365
366 if (s >= FD_SETSIZE) {
367 if (ctx->debug) {
368 fprintf(
369 stderr,
370 "ERROR Socket descriptor %d exceeds FD_SETSIZE (%d)\n",
371 s,
372 FD_SETSIZE);
373 }
374 close(s);
375 errno = EINVAL;
376 return -1;
377 }
378
379 rc = _modbus_tcp_set_ipv4_options(s);
380 if (rc == -1) {
381 close(s);
382 return -1;
383 }
384
385 if (ctx->debug) {
386 printf("Connecting to %s:%d\n", ctx_tcp->ip, ctx_tcp->port);
387 }
388
389 addr.sin_family = AF_INET;
390 addr.sin_port = htons(ctx_tcp->port);
391 rc = inet_pton(addr.sin_family, ctx_tcp->ip, &(addr.sin_addr));
392 if (rc <= 0) {
393 if (ctx->debug) {
394 fprintf(stderr, "Invalid IP address: %s\n", ctx_tcp->ip);
395 }
396 close(s);
397 return -1;
398 }
399
400 rc = _connect(s, (struct sockaddr *) &addr, sizeof(addr), &ctx->response_timeout);
401 if (rc == -1) {
402 close(s);
403 return -1;
404 }
405
406 /* Replace any previously open socket */
407 if (ctx->s >= 0) {
408 close(ctx->s);
409 }
410 ctx->s = s;
411
412 return 0;
413 }
414
415 /* Establishes a modbus TCP PI connection with a Modbus server. */
416 static int _modbus_tcp_pi_connect(modbus_t *ctx)
417 {
418 int rc;
419 int new_s = -1;
420 struct addrinfo *ai_list;
421 struct addrinfo *ai_ptr;
422 struct addrinfo ai_hints;
423 modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
424
425 #ifdef OS_WIN32
426 if (_modbus_tcp_init_win32() == -1) {
427 return -1;
428 }
429 #endif
430
431 memset(&ai_hints, 0, sizeof(ai_hints));
432 #ifdef AI_ADDRCONFIG
433 ai_hints.ai_flags |= AI_ADDRCONFIG;
434 #endif
435 ai_hints.ai_family = AF_UNSPEC;
436 ai_hints.ai_socktype = SOCK_STREAM;
437 ai_hints.ai_addr = NULL;
438 ai_hints.ai_canonname = NULL;
439 ai_hints.ai_next = NULL;
440
441 ai_list = NULL;
442 rc = getaddrinfo(ctx_tcp_pi->node, ctx_tcp_pi->service, &ai_hints, &ai_list);
443 if (rc != 0) {
444 if (ctx->debug) {
445 #ifdef HAVE_GAI_STRERROR
446 fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
447 #else
448 fprintf(stderr, "Error returned by getaddrinfo: %d\n", rc);
449 #endif
450 }
451 if (ai_list != NULL) {
452 freeaddrinfo(ai_list);
453 }
454 errno = ECONNREFUSED;
455 return -1;
456 }
457
458 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
459 int flags = ai_ptr->ai_socktype;
460 int s;
461
462 #ifdef SOCK_CLOEXEC
463 flags |= SOCK_CLOEXEC;
464 #endif
465
466 #ifdef SOCK_NONBLOCK
467 flags |= SOCK_NONBLOCK;
468 #endif
469
470 s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
471 if (s < 0)
472 continue;
473
474 if (s >= FD_SETSIZE) {
475 if (ctx->debug) {
476 fprintf(
477 stderr,
478 "ERROR Socket descriptor %d exceeds FD_SETSIZE (%d)\n",
479 s,
480 FD_SETSIZE);
481 }
482 close(s);
483 continue;
484 }
485
486 if (ai_ptr->ai_family == AF_INET)
487 _modbus_tcp_set_ipv4_options(s);
488
489 if (ctx->debug) {
490 printf("Connecting to [%s]:%s\n", ctx_tcp_pi->node, ctx_tcp_pi->service);
491 }
492
493 rc = _connect(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen, &ctx->response_timeout);
494 if (rc == -1) {
495 close(s);
496 continue;
497 }
498
499 new_s = s;
500 break;
501 }
502
503 freeaddrinfo(ai_list);
504
505 if (new_s < 0) {
506 return -1;
507 }
508
509 /* Replace any previously open socket */
510 if (ctx->s >= 0) {
511 close(ctx->s);
512 }
513 ctx->s = new_s;
514
515 return 0;
516 }
517
518 static unsigned int _modbus_tcp_is_connected(modbus_t *ctx)
519 {
520 return ctx->s >= 0;
521 }
522
523 /* Closes the network connection and socket in TCP mode */
524 static void _modbus_tcp_close(modbus_t *ctx)
525 {
526 if (ctx->s >= 0) {
527 shutdown(ctx->s, SHUT_RDWR);
528 close(ctx->s);
529 ctx->s = -1;
530 }
531 }
532
533 static int _modbus_tcp_flush(modbus_t *ctx)
534 {
535 int rc;
536 // Use an unsigned 16-bit integer to reduce overflow risk. The flush function
537 // is not expected to handle huge amounts of data (> 2GB).
538 uint16_t rc_sum = 0;
539
540 do {
541 /* Extract the garbage from the socket */
542 char devnull[MODBUS_TCP_MAX_ADU_LENGTH];
543 #ifndef OS_WIN32
544 rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, MSG_DONTWAIT);
545 #else
546 /* On Win32, it's a bit more complicated to not wait */
547 fd_set rset;
548 struct timeval tv;
549
550 tv.tv_sec = 0;
551 tv.tv_usec = 0;
552 FD_ZERO(&rset);
553 if (ctx->s < 0 || ctx->s >= FD_SETSIZE) {
554 errno = EINVAL;
555 return -1;
556 }
557 FD_SET(ctx->s, &rset);
558 rc = select(ctx->s + 1, &rset, NULL, NULL, &tv);
559 if (rc == -1) {
560 return -1;
561 }
562
563 if (rc == 1) {
564 /* There is data to flush */
565 rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, 0);
566 }
567 #endif
568 if (rc > 0) {
569 // Check for overflow before adding
570 if (rc_sum <= UINT16_MAX - rc) {
571 rc_sum += rc;
572 } else {
573 // Handle overflow
574 errno = EOVERFLOW;
575 return -1;
576 }
577 }
578 } while (rc == MODBUS_TCP_MAX_ADU_LENGTH);
579
580 /* Cast is safe: uint16_t always fits in int, and overflow is checked above */
581 return (int) rc_sum;
582 }
583
584 /* Listens for any request from one or many modbus masters in TCP */
585 int modbus_tcp_listen(modbus_t *ctx, int nb_connection)
586 {
587 int new_s;
588 int enable;
589 int flags;
590 struct sockaddr_in addr;
591 modbus_tcp_t *ctx_tcp;
592 int rc;
593
594 if (ctx == NULL) {
595 errno = EINVAL;
596 return -1;
597 }
598
599 ctx_tcp = ctx->backend_data;
600
601 #ifdef OS_WIN32
602 if (_modbus_tcp_init_win32() == -1) {
603 return -1;
604 }
605 #endif
606
607 flags = SOCK_STREAM;
608
609 #ifdef SOCK_CLOEXEC
610 flags |= SOCK_CLOEXEC;
611 #endif
612
613 new_s = socket(PF_INET, flags, IPPROTO_TCP);
614 if (new_s == -1) {
615 return -1;
616 }
617
618 enable = 1;
619 #ifdef _WIN32
620 if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable, sizeof(enable)) == -1) {
621 #else
622 if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR, (const void *)&enable, sizeof(enable)) == -1) {
623 #endif
624 close(new_s);
625 return -1;
626 }
627
628 memset(&addr, 0, sizeof(addr));
629 addr.sin_family = AF_INET;
630 /* If the modbus port is < to 1024, we need the setuid root. */
631 addr.sin_port = htons(ctx_tcp->port);
632 if (ctx_tcp->ip[0] == '0') {
633 /* Listen any addresses */
634 addr.sin_addr.s_addr = htonl(INADDR_ANY);
635 } else {
636 /* Listen only specified IP address */
637 rc = inet_pton(addr.sin_family, ctx_tcp->ip, &(addr.sin_addr));
638 if (rc <= 0) {
639 if (ctx->debug) {
640 fprintf(stderr, "Invalid IP address: %s\n", ctx_tcp->ip);
641 }
642 close(new_s);
643 return -1;
644 }
645 }
646
647 if (bind(new_s, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
648 close(new_s);
649 return -1;
650 }
651
652 if (listen(new_s, nb_connection) == -1) {
653 close(new_s);
654 return -1;
655 }
656
657 return new_s;
658 }
659
660 int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection)
661 {
662 int rc;
663 struct addrinfo *ai_list;
664 struct addrinfo *ai_ptr;
665 struct addrinfo ai_hints;
666 const char *node;
667 const char *service;
668 int new_s;
669 modbus_tcp_pi_t *ctx_tcp_pi;
670
671 if (ctx == NULL) {
672 errno = EINVAL;
673 return -1;
674 }
675
676 ctx_tcp_pi = ctx->backend_data;
677
678 #ifdef OS_WIN32
679 if (_modbus_tcp_init_win32() == -1) {
680 return -1;
681 }
682 #endif
683
684 if (ctx_tcp_pi->node[0] == 0) {
685 node = NULL; /* == any */
686 } else {
687 node = ctx_tcp_pi->node;
688 }
689
690 if (ctx_tcp_pi->service[0] == 0) {
691 service = "502";
692 } else {
693 service = ctx_tcp_pi->service;
694 }
695
696 memset(&ai_hints, 0, sizeof(ai_hints));
697 /* If node is not NULL, than the AI_PASSIVE flag is ignored. */
698 ai_hints.ai_flags |= AI_PASSIVE;
699 #ifdef AI_ADDRCONFIG
700 ai_hints.ai_flags |= AI_ADDRCONFIG;
701 #endif
702 ai_hints.ai_family = AF_UNSPEC;
703 ai_hints.ai_socktype = SOCK_STREAM;
704 ai_hints.ai_addr = NULL;
705 ai_hints.ai_canonname = NULL;
706 ai_hints.ai_next = NULL;
707
708 ai_list = NULL;
709 rc = getaddrinfo(node, service, &ai_hints, &ai_list);
710 if (rc != 0) {
711 if (ctx->debug) {
712 #ifdef HAVE_GAI_STRERROR
713 fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
714 #else
715 fprintf(stderr, "Error returned by getaddrinfo: %d\n", rc);
716 #endif
717 }
718 if (ai_list != NULL) {
719 freeaddrinfo(ai_list);
720 }
721 errno = ECONNREFUSED;
722 return -1;
723 }
724
725 new_s = -1;
726 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
727 int flags = ai_ptr->ai_socktype;
728 int s;
729
730 #ifdef SOCK_CLOEXEC
731 flags |= SOCK_CLOEXEC;
732 #endif
733
734 s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
735 if (s < 0) {
736 if (ctx->debug) {
737 perror("socket");
738 }
739 continue;
740 } else {
741 int enable = 1;
742 #ifdef _WIN32
743 rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable, sizeof(enable));
744 #else
745 rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const void *)&enable, sizeof(enable));
746 #endif
747 if (rc != 0) {
748 close(s);
749 if (ctx->debug) {
750 perror("setsockopt");
751 }
752 continue;
753 }
754 }
755
756 rc = bind(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
757 if (rc != 0) {
758 close(s);
759 if (ctx->debug) {
760 perror("bind");
761 }
762 continue;
763 }
764
765 rc = listen(s, nb_connection);
766 if (rc != 0) {
767 close(s);
768 if (ctx->debug) {
769 perror("listen");
770 }
771 continue;
772 }
773
774 new_s = s;
775 break;
776 }
777 freeaddrinfo(ai_list);
778
779 if (new_s < 0) {
780 return -1;
781 }
782
783 return new_s;
784 }
785
786 int modbus_tcp_accept(modbus_t *ctx, int *s)
787 {
788 struct sockaddr_in addr;
789 socklen_t addrlen;
790
791 if (ctx == NULL) {
792 errno = EINVAL;
793 return -1;
794 }
795
796 addrlen = sizeof(addr);
797 #ifdef HAVE_ACCEPT4
798 /* Inherit socket flags and use accept4 call */
799 ctx->s = accept4(*s, (struct sockaddr *) &addr, &addrlen, SOCK_CLOEXEC);
800 #else
801 ctx->s = accept(*s, (struct sockaddr *) &addr, &addrlen);
802 #endif
803
804 if (ctx->s < 0) {
805 return -1;
806 }
807
808 if (ctx->s >= FD_SETSIZE) {
809 if (ctx->debug) {
810 fprintf(
811 stderr,
812 "ERROR Socket descriptor %d exceeds FD_SETSIZE (%d)\n",
813 ctx->s,
814 FD_SETSIZE);
815 }
816 close(ctx->s);
817 ctx->s = -1;
818 errno = EINVAL;
819 return -1;
820 }
821
822 if (ctx->debug) {
823 char buf[INET_ADDRSTRLEN];
824 if (inet_ntop(AF_INET, &(addr.sin_addr), buf, INET_ADDRSTRLEN) == NULL) {
825 fprintf(stderr, "Client connection accepted from unparsable IP.\n");
826 } else {
827 printf("Client connection accepted from %s.\n", buf);
828 }
829 }
830
831 return ctx->s;
832 }
833
834 int modbus_tcp_pi_accept(modbus_t *ctx, int *s)
835 {
836 struct sockaddr_in6 addr;
837 socklen_t addrlen;
838
839 if (ctx == NULL) {
840 errno = EINVAL;
841 return -1;
842 }
843
844 addrlen = sizeof(addr);
845 #ifdef HAVE_ACCEPT4
846 /* Inherit socket flags and use accept4 call */
847 ctx->s = accept4(*s, (struct sockaddr *) &addr, &addrlen, SOCK_CLOEXEC);
848 #else
849 ctx->s = accept(*s, (struct sockaddr *) &addr, &addrlen);
850 #endif
851
852 if (ctx->s < 0) {
853 return -1;
854 }
855
856 if (ctx->s >= FD_SETSIZE) {
857 if (ctx->debug) {
858 fprintf(
859 stderr,
860 "ERROR Socket descriptor %d exceeds FD_SETSIZE (%d)\n",
861 ctx->s,
862 FD_SETSIZE);
863 }
864 close(ctx->s);
865 ctx->s = -1;
866 errno = EINVAL;
867 return -1;
868 }
869
870 if (ctx->debug) {
871 char buf[INET6_ADDRSTRLEN];
872 if (inet_ntop(AF_INET6, &(addr.sin6_addr), buf, INET6_ADDRSTRLEN) == NULL) {
873 fprintf(stderr, "Client connection accepted from unparsable IP.\n");
874 } else {
875 printf("Client connection accepted from %s.\n", buf);
876 }
877 }
878
879 return ctx->s;
880 }
881
882 static int
883 _modbus_tcp_select(modbus_t *ctx, fd_set *rset, struct timeval *tv, int length_to_read)
884 {
885 int s_rc;
886 while ((s_rc = select(ctx->s + 1, rset, NULL, NULL, tv)) == -1) {
887 if (errno == EINTR) {
888 if (ctx->debug) {
889 fprintf(stderr, "A non blocked signal was caught\n");
890 }
891 /* Necessary after an error */
892 FD_ZERO(rset);
893 if (ctx->s < 0 || ctx->s >= FD_SETSIZE) {
894 errno = EINVAL;
895 return -1;
896 }
897 FD_SET(ctx->s, rset);
898 } else {
899 return -1;
900 }
901 }
902
903 if (s_rc == 0) {
904 errno = ETIMEDOUT;
905 return -1;
906 }
907
908 return s_rc;
909 }
910
911 static void _modbus_tcp_free(modbus_t *ctx)
912 {
913 if (ctx->backend_data) {
914 free(ctx->backend_data);
915 }
916 free(ctx);
917 }
918
919 static void _modbus_tcp_pi_free(modbus_t *ctx)
920 {
921 if (ctx->backend_data) {
922 modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
923 free(ctx_tcp_pi->node);
924 free(ctx_tcp_pi->service);
925 free(ctx->backend_data);
926 }
927
928 free(ctx);
929 }
930
931 // clang-format off
932 const modbus_backend_t _modbus_tcp_backend = {
933 _MODBUS_BACKEND_TYPE_TCP,
934 _MODBUS_TCP_HEADER_LENGTH,
935 _MODBUS_TCP_CHECKSUM_LENGTH,
936 MODBUS_TCP_MAX_ADU_LENGTH,
937 _modbus_set_slave,
938 _modbus_tcp_build_request_basis,
939 _modbus_tcp_build_response_basis,
940 _modbus_tcp_get_response_tid,
941 _modbus_tcp_send_msg_pre,
942 _modbus_tcp_send,
943 _modbus_tcp_receive,
944 _modbus_tcp_recv,
945 _modbus_tcp_check_integrity,
946 _modbus_tcp_pre_check_confirmation,
947 _modbus_tcp_connect,
948 _modbus_tcp_is_connected,
949 _modbus_tcp_close,
950 _modbus_tcp_flush,
951 _modbus_tcp_select,
952 _modbus_tcp_free
953 };
954
955 const modbus_backend_t _modbus_tcp_pi_backend = {
956 _MODBUS_BACKEND_TYPE_TCP,
957 _MODBUS_TCP_HEADER_LENGTH,
958 _MODBUS_TCP_CHECKSUM_LENGTH,
959 MODBUS_TCP_MAX_ADU_LENGTH,
960 _modbus_set_slave,
961 _modbus_tcp_build_request_basis,
962 _modbus_tcp_build_response_basis,
963 _modbus_tcp_get_response_tid,
964 _modbus_tcp_send_msg_pre,
965 _modbus_tcp_send,
966 _modbus_tcp_receive,
967 _modbus_tcp_recv,
968 _modbus_tcp_check_integrity,
969 _modbus_tcp_pre_check_confirmation,
970 _modbus_tcp_pi_connect,
971 _modbus_tcp_is_connected,
972 _modbus_tcp_close,
973 _modbus_tcp_flush,
974 _modbus_tcp_select,
975 _modbus_tcp_pi_free
976 };
977
978 // clang-format on
979
980 modbus_t *modbus_new_tcp(const char *ip, int port)
981 {
982 modbus_t *ctx;
983 modbus_tcp_t *ctx_tcp;
984 size_t dest_size;
985 size_t ret_size;
986
987 #if defined(OS_BSD)
988 /* MSG_NOSIGNAL is unsupported on *BSD so we install an ignore
989 handler for SIGPIPE. */
990 struct sigaction sa;
991
992 memset(&sa, 0, sizeof(sa));
993 sa.sa_handler = SIG_IGN;
994 sigemptyset(&sa.sa_mask);
995 if (sigaction(SIGPIPE, &sa, NULL) < 0) {
996 /* The debug flag can't be set here... */
997 fprintf(stderr, "Could not install SIGPIPE handler.\n");
998 return NULL;
999 }
1000 #endif
1001
1002 ctx = (modbus_t *) malloc(sizeof(modbus_t));
1003 if (ctx == NULL) {
1004 return NULL;
1005 }
1006 _modbus_init_common(ctx);
1007
1008 /* Could be changed after to reach a remote serial Modbus device */
1009 ctx->slave = MODBUS_TCP_SLAVE;
1010
1011 ctx->backend = &_modbus_tcp_backend;
1012
1013 ctx->backend_data = (modbus_tcp_t *) malloc(sizeof(modbus_tcp_t));
1014 if (ctx->backend_data == NULL) {
1015 modbus_free(ctx);
1016 errno = ENOMEM;
1017 return NULL;
1018 }
1019 ctx_tcp = (modbus_tcp_t *) ctx->backend_data;
1020
1021 if (ip != NULL) {
1022 dest_size = sizeof(char) * 16;
1023 ret_size = strlcpy(ctx_tcp->ip, ip, dest_size);
1024 if (ret_size == 0) {
1025 fprintf(stderr, "The IP string is empty\n");
1026 modbus_free(ctx);
1027 errno = EINVAL;
1028 return NULL;
1029 }
1030
1031 if (ret_size >= dest_size) {
1032 fprintf(stderr, "The IP string has been truncated\n");
1033 modbus_free(ctx);
1034 errno = EINVAL;
1035 return NULL;
1036 }
1037 } else {
1038 ctx_tcp->ip[0] = '0';
1039 ctx_tcp->ip[1] = '\0';
1040 }
1041 ctx_tcp->port = port;
1042 ctx_tcp->t_id = 0;
1043
1044 return ctx;
1045 }
1046
1047 modbus_t *modbus_new_tcp_pi(const char *node, const char *service)
1048 {
1049 modbus_t *ctx;
1050 modbus_tcp_pi_t *ctx_tcp_pi;
1051
1052 ctx = (modbus_t *) malloc(sizeof(modbus_t));
1053 if (ctx == NULL) {
1054 return NULL;
1055 }
1056 _modbus_init_common(ctx);
1057
1058 /* Could be changed after to reach a remote serial Modbus device */
1059 ctx->slave = MODBUS_TCP_SLAVE;
1060
1061 ctx->backend = &_modbus_tcp_pi_backend;
1062
1063 ctx->backend_data = (modbus_tcp_pi_t *) malloc(sizeof(modbus_tcp_pi_t));
1064 if (ctx->backend_data == NULL) {
1065 modbus_free(ctx);
1066 errno = ENOMEM;
1067 return NULL;
1068 }
1069 ctx_tcp_pi = (modbus_tcp_pi_t *) ctx->backend_data;
1070 ctx_tcp_pi->node = NULL;
1071 ctx_tcp_pi->service = NULL;
1072
1073 if (node != NULL) {
1074 ctx_tcp_pi->node = strdup(node);
1075 } else {
1076 /* The node argument can be empty to indicate any hosts */
1077 ctx_tcp_pi->node = strdup("");
1078 }
1079
1080 if (ctx_tcp_pi->node == NULL) {
1081 modbus_free(ctx);
1082 errno = ENOMEM;
1083 return NULL;
1084 }
1085
1086 if (service != NULL && service[0] != '\0') {
1087 ctx_tcp_pi->service = strdup(service);
1088 } else {
1089 /* Default Modbus port number */
1090 ctx_tcp_pi->service = strdup("502");
1091 }
1092
1093 if (ctx_tcp_pi->service == NULL) {
1094 modbus_free(ctx);
1095 errno = ENOMEM;
1096 return NULL;
1097 }
1098
1099 ctx_tcp_pi->t_id = 0;
1100
1101 return ctx;
1102 }