Debian Codegraph @

src/modbus.c

raw symbols SCIP
1 /*
2 * Copyright © Stéphane Raimbault <[email protected]>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 *
6 * This library implements the Modbus protocol.
7 * http://libmodbus.org/
8 */
9
10 #include <errno.h>
11 #include <limits.h>
12 #include <stdarg.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <time.h>
17 #ifndef _MSC_VER
18 #include <unistd.h>
19 #endif
20
21 #include <config.h>
22
23 #include "modbus-private.h"
24 #include "modbus.h"
25
26 /* Internal use */
27 #define MSG_LENGTH_UNDEFINED -1
28
29 /* The Modbus address space is 16-bit, so a mapping table cannot hold more
30 than 65536 entries. */
31 #define MODBUS_MAX_TABLE_SIZE 65536
32
33 /* Exported version */
34 const unsigned int libmodbus_version_major = LIBMODBUS_VERSION_MAJOR;
35 const unsigned int libmodbus_version_minor = LIBMODBUS_VERSION_MINOR;
36 const unsigned int libmodbus_version_micro = LIBMODBUS_VERSION_MICRO;
37
38 /* Max between RTU and TCP max adu length (so TCP) */
39 #define MAX_MESSAGE_LENGTH 260
40
41 /* 3 steps are used to parse the query */
42 typedef enum {
43 _STEP_FUNCTION,
44 _STEP_META,
45 _STEP_DATA
46 } _step_t;
47
48 const char *modbus_strerror(int errnum)
49 {
50 switch (errnum) {
51 case EMBXILFUN:
52 return "Illegal function";
53 case EMBXILADD:
54 return "Illegal data address";
55 case EMBXILVAL:
56 return "Illegal data value";
57 case EMBXSFAIL:
58 return "Slave device or server failure";
59 case EMBXACK:
60 return "Acknowledge";
61 case EMBXSBUSY:
62 return "Slave device or server is busy";
63 case EMBXNACK:
64 return "Negative acknowledge";
65 case EMBXMEMPAR:
66 return "Memory parity error";
67 case EMBXGPATH:
68 return "Gateway path unavailable";
69 case EMBXGTAR:
70 return "Target device failed to respond";
71 case EMBBADCRC:
72 return "Invalid CRC";
73 case EMBBADDATA:
74 return "Invalid data";
75 case EMBBADEXC:
76 return "Invalid exception code";
77 case EMBMDATA:
78 return "Too many data";
79 case EMBBADSLAVE:
80 return "Response not from requested slave";
81 default:
82 return strerror(errnum);
83 }
84 }
85
86 void _error_print(modbus_t *ctx, const char *context)
87 {
88 if (ctx->debug) {
89 fprintf(stderr, "ERROR %s", modbus_strerror(errno));
90 if (context != NULL) {
91 fprintf(stderr, ": %s\n", context);
92 } else {
93 fprintf(stderr, "\n");
94 }
95 }
96 }
97
98 static void _sleep_response_timeout(modbus_t *ctx)
99 {
100 /* Response timeout is always positive */
101 #ifdef _WIN32
102 /* usleep doesn't exist on Windows */
103 Sleep((ctx->response_timeout.tv_sec * 1000) + (ctx->response_timeout.tv_usec / 1000));
104 #else
105 /* usleep source code */
106 struct timespec request, remaining;
107 request.tv_sec = ctx->response_timeout.tv_sec;
108 request.tv_nsec = ((long int) ctx->response_timeout.tv_usec) * 1000;
109 while (nanosleep(&request, &remaining) == -1 && errno == EINTR) {
110 request = remaining;
111 }
112 #endif
113 }
114
115 int modbus_flush(modbus_t *ctx)
116 {
117 int rc;
118
119 if (ctx == NULL) {
120 errno = EINVAL;
121 return -1;
122 }
123
124 rc = ctx->backend->flush(ctx);
125 if (rc != -1 && ctx->debug) {
126 /* Not all backends are able to return the number of bytes flushed */
127 printf("Bytes flushed (%d)\n", rc);
128 }
129 return rc;
130 }
131
132 /* Computes the length of the expected response including checksum */
133 static unsigned int compute_response_length_from_request(modbus_t *ctx, uint8_t *req)
134 {
135 int length;
136 const int offset = ctx->backend->header_length;
137
138 switch (req[offset]) {
139 case MODBUS_FC_READ_COILS:
140 case MODBUS_FC_READ_DISCRETE_INPUTS: {
141 /* Header + nb values (code from write_bits) */
142 int nb = (req[offset + 3] << 8) | req[offset + 4];
143 length = 2 + (nb / 8) + ((nb % 8) ? 1 : 0);
144 } break;
145 case MODBUS_FC_WRITE_AND_READ_REGISTERS:
146 case MODBUS_FC_READ_HOLDING_REGISTERS:
147 case MODBUS_FC_READ_INPUT_REGISTERS:
148 /* Header + 2 * nb values */
149 length = 2 + 2 * (req[offset + 3] << 8 | req[offset + 4]);
150 break;
151 case MODBUS_FC_READ_EXCEPTION_STATUS:
152 length = 3;
153 break;
154 case MODBUS_FC_REPORT_SLAVE_ID:
155 /* The response is device specific (the header provides the
156 length) */
157 return MSG_LENGTH_UNDEFINED;
158 case MODBUS_FC_MASK_WRITE_REGISTER:
159 length = 7;
160 break;
161 default:
162 length = 5;
163 }
164
165 return offset + length + ctx->backend->checksum_length;
166 }
167
168 /* Sends a request/response */
169 static int send_msg(modbus_t *ctx, uint8_t *msg, int msg_length)
170 {
171 int rc;
172 int i;
173
174 msg_length = ctx->backend->send_msg_pre(msg, msg_length);
175
176 if (ctx->debug) {
177 for (i = 0; i < msg_length; i++)
178 printf("[%.2X]", msg[i]);
179 printf("\n");
180 }
181
182 /* In recovery mode, the write command will be issued until to be
183 successful! Disabled by default. */
184 do {
185 rc = ctx->backend->send(ctx, msg, msg_length);
186 if (rc == -1) {
187 _error_print(ctx, NULL);
188 if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) {
189 #ifdef _WIN32
190 int saved_errno = errno;
191 const int wsa_err = WSAGetLastError();
192
193 if (wsa_err == WSAENETRESET || wsa_err == WSAENOTCONN ||
194 wsa_err == WSAENOTSOCK || wsa_err == WSAESHUTDOWN ||
195 wsa_err == WSAEHOSTUNREACH || wsa_err == WSAECONNABORTED ||
196 wsa_err == WSAECONNRESET || wsa_err == WSAETIMEDOUT) {
197 modbus_close(ctx);
198 _sleep_response_timeout(ctx);
199 modbus_connect(ctx);
200 } else {
201 _sleep_response_timeout(ctx);
202 modbus_flush(ctx);
203 }
204 errno = saved_errno;
205 #else
206 int saved_errno = errno;
207
208 if ((errno == EBADF || errno == ECONNRESET || errno == EPIPE)) {
209 modbus_close(ctx);
210 _sleep_response_timeout(ctx);
211 modbus_connect(ctx);
212 } else {
213 _sleep_response_timeout(ctx);
214 modbus_flush(ctx);
215 }
216 errno = saved_errno;
217 #endif
218 }
219 }
220 } while ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) && rc == -1);
221
222 if (rc > 0 && rc != msg_length) {
223 errno = EMBBADDATA;
224 return -1;
225 }
226
227 return rc;
228 }
229
230 int modbus_send_raw_request_tid(modbus_t *ctx,
231 const uint8_t *raw_req,
232 int raw_req_length,
233 int tid)
234 {
235 sft_t sft;
236 uint8_t req[MAX_MESSAGE_LENGTH];
237 int req_length;
238
239 if (ctx == NULL || raw_req == NULL) {
240 errno = EINVAL;
241 return -1;
242 }
243
244 if (raw_req_length < 2 || raw_req_length > (MODBUS_MAX_PDU_LENGTH + 1)) {
245 /* The raw request must contain function and slave at least and
246 must not be longer than the maximum pdu length plus the slave
247 address. */
248 errno = EINVAL;
249 return -1;
250 }
251
252 sft.slave = raw_req[0];
253 sft.function = raw_req[1];
254 /* The t_id is left to zero */
255 sft.t_id = tid;
256 /* This response function only set the header so it's convenient here */
257 req_length = ctx->backend->build_response_basis(&sft, req);
258
259 if (raw_req_length > 2) {
260 /* Copy data after function code */
261 memcpy(req + req_length, raw_req + 2, raw_req_length - 2);
262 req_length += raw_req_length - 2;
263 }
264
265 return send_msg(ctx, req, req_length);
266 }
267
268 int modbus_send_raw_request(modbus_t *ctx, const uint8_t *raw_req, int raw_req_length)
269 {
270 return modbus_send_raw_request_tid(ctx, raw_req, raw_req_length, 0);
271 }
272
273 /*
274 * ---------- Request Indication ----------
275 * | Client | ---------------------->| Server |
276 * ---------- Confirmation Response ----------
277 */
278
279 /* Computes the length to read after the function received */
280 static uint8_t compute_meta_length_after_function(int function, msg_type_t msg_type)
281 {
282 int length;
283
284 if (msg_type == MSG_INDICATION) {
285 if (function <= MODBUS_FC_WRITE_SINGLE_REGISTER) {
286 length = 4;
287 } else if (function == MODBUS_FC_WRITE_MULTIPLE_COILS ||
288 function == MODBUS_FC_WRITE_MULTIPLE_REGISTERS) {
289 length = 5;
290 } else if (function == MODBUS_FC_MASK_WRITE_REGISTER) {
291 length = 6;
292 } else if (function == MODBUS_FC_WRITE_AND_READ_REGISTERS) {
293 length = 9;
294 } else {
295 /* MODBUS_FC_READ_EXCEPTION_STATUS, MODBUS_FC_REPORT_SLAVE_ID */
296 length = 0;
297 }
298 } else {
299 /* MSG_CONFIRMATION */
300 switch (function) {
301 case MODBUS_FC_WRITE_SINGLE_COIL:
302 case MODBUS_FC_WRITE_SINGLE_REGISTER:
303 case MODBUS_FC_WRITE_MULTIPLE_COILS:
304 case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
305 length = 4;
306 break;
307 case MODBUS_FC_MASK_WRITE_REGISTER:
308 length = 6;
309 break;
310 default:
311 length = 1;
312 }
313 }
314
315 return length;
316 }
317
318 /* Computes the length to read after the meta information (address, count, etc) */
319 static int
320 compute_data_length_after_meta(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type)
321 {
322 int function = msg[ctx->backend->header_length];
323 int length;
324
325 if (msg_type == MSG_INDICATION) {
326 switch (function) {
327 case MODBUS_FC_WRITE_MULTIPLE_COILS:
328 case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
329 length = msg[ctx->backend->header_length + 5];
330 break;
331 case MODBUS_FC_WRITE_AND_READ_REGISTERS:
332 length = msg[ctx->backend->header_length + 9];
333 break;
334 default:
335 length = 0;
336 }
337 } else {
338 /* MSG_CONFIRMATION */
339 if (function <= MODBUS_FC_READ_INPUT_REGISTERS ||
340 function == MODBUS_FC_REPORT_SLAVE_ID ||
341 function == MODBUS_FC_WRITE_AND_READ_REGISTERS) {
342 length = msg[ctx->backend->header_length + 1];
343 } else {
344 length = 0;
345 }
346 }
347
348 length += ctx->backend->checksum_length;
349
350 return length;
351 }
352
353 /* Waits a response from a modbus server or a request from a modbus client.
354 This function blocks if there is no replies (3 timeouts).
355
356 The function shall return the number of received characters and the received
357 message in an array of uint8_t if successful. Otherwise it shall return -1
358 and errno is set to one of the values defined below:
359 - ECONNRESET
360 - EMBBADDATA
361 - ETIMEDOUT
362 - read() or recv() error codes
363 */
364
365 int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type)
366 {
367 int rc;
368 fd_set rset;
369 struct timeval tv;
370 struct timeval *p_tv;
371 unsigned int length_to_read;
372 int msg_length = 0;
373 _step_t step;
374 #ifdef _WIN32
375 int wsa_err;
376 #endif
377
378 if (ctx->debug) {
379 if (msg_type == MSG_INDICATION) {
380 printf("Waiting for an indication...\n");
381 } else {
382 printf("Waiting for a confirmation...\n");
383 }
384 }
385
386 if (!ctx->backend->is_connected(ctx)) {
387 if (ctx->debug) {
388 fprintf(stderr, "ERROR The connection is not established.\n");
389 }
390 return -1;
391 }
392
393 /* Add a file descriptor to the set */
394 FD_ZERO(&rset);
395 if (ctx->s < 0 || ctx->s >= FD_SETSIZE) {
396 if (ctx->debug) {
397 fprintf(stderr, "ERROR Invalid socket descriptor %d\n", ctx->s);
398 }
399 errno = EINVAL;
400 return -1;
401 }
402 FD_SET(ctx->s, &rset);
403
404 /* We need to analyse the message step by step. At the first step, we want
405 * to reach the function code because all packets contain this
406 * information. */
407 step = _STEP_FUNCTION;
408 length_to_read = ctx->backend->header_length + 1;
409
410 if (msg_type == MSG_INDICATION) {
411 /* Wait for a message, we don't know when the message will be received */
412 if (ctx->indication_timeout.tv_sec == 0 && ctx->indication_timeout.tv_usec == 0) {
413 /* By default, the indication timeout isn't set */
414 p_tv = NULL;
415 } else {
416 /* Wait for an indication (name of a received request by a server, see schema)
417 */
418 tv.tv_sec = ctx->indication_timeout.tv_sec;
419 tv.tv_usec = ctx->indication_timeout.tv_usec;
420 p_tv = &tv;
421 }
422 } else {
423 tv.tv_sec = ctx->response_timeout.tv_sec;
424 tv.tv_usec = ctx->response_timeout.tv_usec;
425 p_tv = &tv;
426 }
427
428 while (length_to_read != 0) {
429 rc = ctx->backend->select(ctx, &rset, p_tv, length_to_read);
430 if (rc == -1) {
431 _error_print(ctx, "select");
432 if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) {
433 #ifdef _WIN32
434 int saved_errno = errno;
435
436 wsa_err = WSAGetLastError();
437
438 // no equivalent to ETIMEDOUT when select fails on Windows
439 if (wsa_err == WSAENETDOWN || wsa_err == WSAENOTSOCK) {
440 modbus_close(ctx);
441 modbus_connect(ctx);
442 }
443 errno = saved_errno;
444 #else
445 int saved_errno = errno;
446
447 if (errno == ETIMEDOUT) {
448 _sleep_response_timeout(ctx);
449 modbus_flush(ctx);
450 } else if (errno == EBADF) {
451 modbus_close(ctx);
452 modbus_connect(ctx);
453 }
454 errno = saved_errno;
455 #endif
456 }
457 return -1;
458 }
459
460 rc = ctx->backend->recv(ctx, msg + msg_length, length_to_read);
461 if (rc == 0) {
462 errno = ECONNRESET;
463 rc = -1;
464 }
465
466 if (rc == -1) {
467 _error_print(ctx, "read");
468 #ifdef _WIN32
469 wsa_err = WSAGetLastError();
470 if ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) &&
471 (wsa_err == WSAENOTCONN || wsa_err == WSAENETRESET ||
472 wsa_err == WSAENOTSOCK || wsa_err == WSAESHUTDOWN ||
473 wsa_err == WSAECONNABORTED || wsa_err == WSAETIMEDOUT ||
474 wsa_err == WSAECONNRESET)) {
475 int saved_errno = errno;
476 modbus_close(ctx);
477 modbus_connect(ctx);
478 /* Could be removed by previous calls */
479 errno = saved_errno;
480 }
481 #else
482 if ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) &&
483 (errno == ECONNRESET || errno == ECONNREFUSED || errno == EBADF)) {
484 int saved_errno = errno;
485 modbus_close(ctx);
486 modbus_connect(ctx);
487 /* Could be removed by previous calls */
488 errno = saved_errno;
489 }
490 #endif
491 return -1;
492 }
493
494 /* Display the hex code of each character received */
495 if (ctx->debug) {
496 int i;
497 for (i = 0; i < rc; i++)
498 printf("<%.2X>", msg[msg_length + i]);
499 }
500
501 /* Sums bytes received */
502 msg_length += rc;
503 /* Computes remaining bytes */
504 length_to_read -= rc;
505
506 if (length_to_read == 0) {
507 switch (step) {
508 case _STEP_FUNCTION:
509 /* Function code position */
510 length_to_read = compute_meta_length_after_function(
511 msg[ctx->backend->header_length], msg_type);
512 if (length_to_read != 0) {
513 step = _STEP_META;
514 break;
515 } /* else switches straight to the next step */
516 case _STEP_META:
517 length_to_read = compute_data_length_after_meta(ctx, msg, msg_type);
518 if ((msg_length + length_to_read) > ctx->backend->max_adu_length) {
519 errno = EMBBADDATA;
520 _error_print(ctx, "too many data");
521 return -1;
522 }
523 step = _STEP_DATA;
524 break;
525 default:
526 break;
527 }
528 }
529
530 if (length_to_read > 0 &&
531 (ctx->byte_timeout.tv_sec > 0 || ctx->byte_timeout.tv_usec > 0)) {
532 /* If there is no character in the buffer, the allowed timeout
533 interval between two consecutive bytes is defined by
534 byte_timeout */
535 tv.tv_sec = ctx->byte_timeout.tv_sec;
536 tv.tv_usec = ctx->byte_timeout.tv_usec;
537 p_tv = &tv;
538 }
539 /* else timeout isn't set again, the full response must be read before
540 expiration of response timeout (for CONFIRMATION only) */
541 }
542
543 if (ctx->debug)
544 printf("\n");
545
546 return ctx->backend->check_integrity(ctx, msg, msg_length);
547 }
548
549 /* Receive the request from a modbus master */
550 int modbus_receive(modbus_t *ctx, uint8_t *req)
551 {
552 if (ctx == NULL) {
553 errno = EINVAL;
554 return -1;
555 }
556
557 return ctx->backend->receive(ctx, req);
558 }
559
560 /* Receives the confirmation.
561
562 The function shall store the read response in rsp and return the number of
563 values (bits or words). Otherwise, its shall return -1 and errno is set.
564
565 The function doesn't check the confirmation is the expected response to the
566 initial request.
567 */
568 int modbus_receive_confirmation(modbus_t *ctx, uint8_t *rsp)
569 {
570 if (ctx == NULL) {
571 errno = EINVAL;
572 return -1;
573 }
574
575 return _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
576 }
577
578 static int check_confirmation(modbus_t *ctx, uint8_t *req, uint8_t *rsp, int rsp_length)
579 {
580 int rc;
581 int rsp_length_computed;
582 const unsigned int offset = ctx->backend->header_length;
583 const int function = rsp[offset];
584
585 if (ctx->backend->pre_check_confirmation) {
586 rc = ctx->backend->pre_check_confirmation(ctx, req, rsp, rsp_length);
587 if (rc == -1) {
588 if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
589 _sleep_response_timeout(ctx);
590 modbus_flush(ctx);
591 }
592 return -1;
593 }
594 }
595
596 rsp_length_computed = compute_response_length_from_request(ctx, req);
597
598 /* Exception code */
599 if (function >= 0x80) {
600 if (rsp_length == (int) (offset + 2 + ctx->backend->checksum_length) &&
601 req[offset] == (rsp[offset] - 0x80)) {
602 /* Valid exception code received */
603
604 int exception_code = rsp[offset + 1];
605 if (exception_code < MODBUS_EXCEPTION_MAX) {
606 errno = MODBUS_ENOBASE + exception_code;
607 } else {
608 errno = EMBBADEXC;
609 }
610 _error_print(ctx, NULL);
611 return -1;
612 } else {
613 errno = EMBBADEXC;
614 _error_print(ctx, NULL);
615 return -1;
616 }
617 }
618
619 /* Check length */
620 if ((rsp_length == rsp_length_computed ||
621 rsp_length_computed == MSG_LENGTH_UNDEFINED) &&
622 function < 0x80) {
623 int req_nb_value;
624 int rsp_nb_value;
625 int resp_addr_ok = TRUE;
626 int resp_data_ok = TRUE;
627
628 /* Check function code */
629 if (function != req[offset]) {
630 if (ctx->debug) {
631 fprintf(
632 stderr,
633 "Received function not corresponding to the request (0x%X != 0x%X)\n",
634 function,
635 req[offset]);
636 }
637 if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
638 _sleep_response_timeout(ctx);
639 modbus_flush(ctx);
640 }
641 errno = EMBBADDATA;
642 return -1;
643 }
644
645 /* Check the number of values is corresponding to the request */
646 switch (function) {
647 case MODBUS_FC_READ_COILS:
648 case MODBUS_FC_READ_DISCRETE_INPUTS:
649 /* Read functions, 8 values in a byte (nb
650 * of values in the request and byte count in
651 * the response. */
652 req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
653 req_nb_value = (req_nb_value / 8) + ((req_nb_value % 8) ? 1 : 0);
654 rsp_nb_value = rsp[offset + 1];
655 break;
656 case MODBUS_FC_WRITE_AND_READ_REGISTERS:
657 case MODBUS_FC_READ_HOLDING_REGISTERS:
658 case MODBUS_FC_READ_INPUT_REGISTERS:
659 /* Read functions 1 value = 2 bytes */
660 req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
661 rsp_nb_value = (rsp[offset + 1] / 2);
662 break;
663 case MODBUS_FC_WRITE_MULTIPLE_COILS:
664 case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
665 /* address in request and response must be equal */
666 if ((req[offset + 1] != rsp[offset + 1]) ||
667 (req[offset + 2] != rsp[offset + 2])) {
668 resp_addr_ok = FALSE;
669 }
670 /* N Write functions */
671 req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
672 rsp_nb_value = (rsp[offset + 3] << 8) | rsp[offset + 4];
673 break;
674 case MODBUS_FC_REPORT_SLAVE_ID:
675 /* Report slave ID (bytes received) */
676 req_nb_value = rsp_nb_value = rsp[offset + 1];
677 break;
678 case MODBUS_FC_WRITE_SINGLE_COIL:
679 case MODBUS_FC_WRITE_SINGLE_REGISTER:
680 /* address in request and response must be equal */
681 if ((req[offset + 1] != rsp[offset + 1]) ||
682 (req[offset + 2] != rsp[offset + 2])) {
683 resp_addr_ok = FALSE;
684 }
685 /* data in request and response must be equal */
686 if ((req[offset + 3] != rsp[offset + 3]) ||
687 (req[offset + 4] != rsp[offset + 4])) {
688 resp_data_ok = FALSE;
689 }
690 /* 1 Write functions & others */
691 req_nb_value = rsp_nb_value = 1;
692 break;
693 default:
694 /* 1 Write functions & others */
695 req_nb_value = rsp_nb_value = 1;
696 break;
697 }
698
699 if ((req_nb_value == rsp_nb_value) && (resp_addr_ok == TRUE) &&
700 (resp_data_ok == TRUE)) {
701 rc = rsp_nb_value;
702 } else {
703 if (ctx->debug) {
704 fprintf(stderr,
705 "Received data not corresponding to the request (%d != %d)\n",
706 rsp_nb_value,
707 req_nb_value);
708 }
709
710 if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
711 _sleep_response_timeout(ctx);
712 modbus_flush(ctx);
713 }
714
715 errno = EMBBADDATA;
716 rc = -1;
717 }
718 } else {
719 if (ctx->debug) {
720 fprintf(
721 stderr,
722 "Message length not corresponding to the computed length (%d != %d)\n",
723 rsp_length,
724 rsp_length_computed);
725 }
726 if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
727 _sleep_response_timeout(ctx);
728 modbus_flush(ctx);
729 }
730 errno = EMBBADDATA;
731 rc = -1;
732 }
733
734 return rc;
735 }
736
737 static int
738 response_io_status(uint8_t *tab_io_status, int address, int nb, uint8_t *rsp, int offset)
739 {
740 int shift = 0;
741 /* Instead of byte (not allowed in Win32) */
742 int one_byte = 0;
743 int i;
744
745 for (i = address; i < address + nb; i++) {
746 one_byte |= tab_io_status[i] << shift;
747 if (shift == 7) {
748 /* Byte is full */
749 rsp[offset++] = one_byte;
750 one_byte = shift = 0;
751 } else {
752 shift++;
753 }
754 }
755
756 if (shift != 0)
757 rsp[offset++] = one_byte;
758
759 return offset;
760 }
761
762 /* Build the exception response */
763 static int response_exception(modbus_t *ctx,
764 sft_t *sft,
765 int exception_code,
766 uint8_t *rsp,
767 unsigned int to_flush,
768 const char *template,
769 ...)
770 {
771 int rsp_length;
772
773 /* Print debug message */
774 if (ctx->debug) {
775 va_list ap;
776
777 va_start(ap, template);
778 vfprintf(stderr, template, ap);
779 va_end(ap);
780 }
781
782 /* Flush if required */
783 if (to_flush) {
784 _sleep_response_timeout(ctx);
785 modbus_flush(ctx);
786 }
787
788 /* Build exception response */
789 sft->function = sft->function + 0x80;
790 rsp_length = ctx->backend->build_response_basis(sft, rsp);
791 rsp[rsp_length++] = exception_code;
792
793 return rsp_length;
794 }
795
796 /* Send a response to the received request.
797 Analyses the request and constructs a response.
798
799 If an error occurs, this function construct the response
800 accordingly.
801 */
802 int modbus_reply(modbus_t *ctx,
803 const uint8_t *req,
804 int req_length,
805 modbus_mapping_t *mb_mapping)
806 {
807 unsigned int offset;
808 int slave;
809 int function;
810 uint16_t address;
811 uint8_t rsp[MAX_MESSAGE_LENGTH];
812 int rsp_length = 0;
813 sft_t sft;
814 uint8_t meta_length;
815 int data_length;
816
817 if (ctx == NULL || req == NULL || mb_mapping == NULL) {
818 errno = EINVAL;
819 return -1;
820 }
821
822 offset = ctx->backend->header_length;
823
824 /* The request must contain at least a slave address and a function code
825 before they can be read. */
826 if (req_length < (int) (offset + 1)) {
827 errno = EMBBADDATA;
828 return -1;
829 }
830
831 slave = req[offset - 1];
832 function = req[offset];
833
834 /* Some function codes (eg. FC_READ_EXCEPTION_STATUS, FC_REPORT_SLAVE_ID)
835 carry no address in the request PDU, so only read when available. Reading
836 them is safe as it fits within MODBUS_MAX_ADU_LENGTH, it's just for
837 coherency.
838 */
839 if (req_length >= (int) (offset + 3))
840 address = (req[offset + 1] << 8) + req[offset + 2];
841 else
842 address = 0;
843
844 sft.slave = slave;
845 sft.function = function;
846 sft.t_id = ctx->backend->get_response_tid(req);
847
848 /* Ensure the request is long enough to contain the meta fields (address,
849 quantity, byte count...) and the declared data read by the handlers
850 below. On the canonical modbus_receive() path the framing layer already
851 guarantees a complete PDU; this check defends direct callers that pass a
852 truncated or untrusted request to modbus_reply(). */
853 meta_length = compute_meta_length_after_function(function, MSG_INDICATION);
854 data_length = 0;
855 if (req_length >= (int) (offset + 1 + meta_length)) {
856 /* The meta fields (including the byte count) are present, so the
857 declared data length can be read safely. */
858 data_length = compute_data_length_after_meta(ctx, (uint8_t *) req, MSG_INDICATION);
859 }
860 if (req_length < (int) (offset + 1 + meta_length + data_length)) {
861 rsp_length = response_exception(ctx,
862 &sft,
863 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
864 rsp,
865 TRUE,
866 "Truncated request (length %d) for function "
867 "0x%0X in modbus_reply\n",
868 req_length,
869 function);
870 /* Suppress responses to broadcasts in RTU, see below. */
871 if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&
872 slave == MODBUS_BROADCAST_ADDRESS &&
873 !(ctx->quirks & MODBUS_QUIRK_REPLY_TO_BROADCAST)) {
874 return 0;
875 }
876 return send_msg(ctx, rsp, rsp_length);
877 }
878
879 /* Data are flushed on illegal number of values errors. */
880 switch (function) {
881 case MODBUS_FC_READ_COILS:
882 case MODBUS_FC_READ_DISCRETE_INPUTS: {
883 unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS);
884 int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits;
885 int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits;
886 uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits;
887 const char *const name = is_input ? "read_input_bits" : "read_bits";
888 int nb = (req[offset + 3] << 8) + req[offset + 4];
889 /* The mapping can be shifted to reduce memory consumption and it
890 doesn't always start at address zero. */
891 int mapping_address = address - start_bits;
892
893 if (nb < 1 || MODBUS_MAX_READ_BITS < nb) {
894 rsp_length = response_exception(ctx,
895 &sft,
896 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
897 rsp,
898 TRUE,
899 "Illegal nb of values %d in %s (max %d)\n",
900 nb,
901 name,
902 MODBUS_MAX_READ_BITS);
903 } else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) {
904 rsp_length = response_exception(ctx,
905 &sft,
906 MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
907 rsp,
908 FALSE,
909 "Illegal data address 0x%0X in %s\n",
910 mapping_address < 0 ? address : address + nb,
911 name);
912 } else {
913 rsp_length = ctx->backend->build_response_basis(&sft, rsp);
914 rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
915 rsp_length =
916 response_io_status(tab_bits, mapping_address, nb, rsp, rsp_length);
917 }
918 } break;
919 case MODBUS_FC_READ_HOLDING_REGISTERS:
920 case MODBUS_FC_READ_INPUT_REGISTERS: {
921 unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS);
922 int start_registers =
923 is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers;
924 int nb_registers =
925 is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers;
926 uint16_t *tab_registers =
927 is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers;
928 const char *const name = is_input ? "read_input_registers" : "read_registers";
929 int nb = (req[offset + 3] << 8) + req[offset + 4];
930 /* The mapping can be shifted to reduce memory consumption and it
931 doesn't always start at address zero. */
932 int mapping_address = address - start_registers;
933
934 if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) {
935 rsp_length = response_exception(ctx,
936 &sft,
937 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
938 rsp,
939 TRUE,
940 "Illegal nb of values %d in %s (max %d)\n",
941 nb,
942 name,
943 MODBUS_MAX_READ_REGISTERS);
944 } else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) {
945 rsp_length = response_exception(ctx,
946 &sft,
947 MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
948 rsp,
949 FALSE,
950 "Illegal data address 0x%0X in %s\n",
951 mapping_address < 0 ? address : address + nb,
952 name);
953 } else {
954 int i;
955
956 rsp_length = ctx->backend->build_response_basis(&sft, rsp);
957 rsp[rsp_length++] = nb << 1;
958 for (i = mapping_address; i < mapping_address + nb; i++) {
959 rsp[rsp_length++] = tab_registers[i] >> 8;
960 rsp[rsp_length++] = tab_registers[i] & 0xFF;
961 }
962 }
963 } break;
964 case MODBUS_FC_WRITE_SINGLE_COIL: {
965 int mapping_address = address - mb_mapping->start_bits;
966
967 if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) {
968 rsp_length = response_exception(ctx,
969 &sft,
970 MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
971 rsp,
972 FALSE,
973 "Illegal data address 0x%0X in write bit\n",
974 address);
975 break;
976 }
977
978 /* This check is only done here to ensure using memcpy is safe. */
979 rsp_length = compute_response_length_from_request(ctx, (uint8_t *) req);
980 if (rsp_length != req_length) {
981 /* Bad use of modbus_reply */
982 rsp_length = response_exception(
983 ctx,
984 &sft,
985 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
986 rsp,
987 FALSE,
988 "Invalid request length in modbus_reply to write bit (%d)\n",
989 req_length);
990 break;
991 }
992
993 /* Don't copy the CRC, if any, it will be computed later (even if identical to the
994 * request) */
995 rsp_length -= ctx->backend->checksum_length;
996
997 int data = (req[offset + 3] << 8) + req[offset + 4];
998 if (data == 0xFF00 || data == 0x0) {
999 /* Apply the change to mapping */
1000 mb_mapping->tab_bits[mapping_address] = data ? ON : OFF;
1001 /* Prepare response */
1002 memcpy(rsp, req, rsp_length);
1003 } else {
1004 rsp_length = response_exception(
1005 ctx,
1006 &sft,
1007 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
1008 rsp,
1009 FALSE,
1010 "Illegal data value 0x%0X in write_bit request at address %0X\n",
1011 data,
1012 address);
1013 }
1014 } break;
1015 case MODBUS_FC_WRITE_SINGLE_REGISTER: {
1016 int mapping_address = address - mb_mapping->start_registers;
1017
1018 if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
1019 rsp_length =
1020 response_exception(ctx,
1021 &sft,
1022 MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
1023 rsp,
1024 FALSE,
1025 "Illegal data address 0x%0X in write_register\n",
1026 address);
1027 break;
1028 }
1029
1030 rsp_length = compute_response_length_from_request(ctx, (uint8_t *) req);
1031 if (rsp_length != req_length) {
1032 /* Bad use of modbus_reply */
1033 rsp_length = response_exception(
1034 ctx,
1035 &sft,
1036 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
1037 rsp,
1038 FALSE,
1039 "Invalid request length in modbus_reply to write register (%d)\n",
1040 req_length);
1041 break;
1042 }
1043 int data = (req[offset + 3] << 8) + req[offset + 4];
1044
1045 mb_mapping->tab_registers[mapping_address] = data;
1046
1047 rsp_length -= ctx->backend->checksum_length;
1048 memcpy(rsp, req, rsp_length);
1049 } break;
1050 case MODBUS_FC_WRITE_MULTIPLE_COILS: {
1051 int nb = (req[offset + 3] << 8) + req[offset + 4];
1052 int nb_bits = req[offset + 5];
1053 int mapping_address = address - mb_mapping->start_bits;
1054
1055 if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb || nb_bits * 8 < nb) {
1056 /* May be the indication has been truncated on reading because of
1057 * invalid address (eg. nb is 0 but the request contains values to
1058 * write) so it's necessary to flush. */
1059 rsp_length =
1060 response_exception(ctx,
1061 &sft,
1062 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
1063 rsp,
1064 TRUE,
1065 "Illegal number of values %d in write_bits (max %d)\n",
1066 nb,
1067 MODBUS_MAX_WRITE_BITS);
1068 } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_bits) {
1069 rsp_length = response_exception(ctx,
1070 &sft,
1071 MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
1072 rsp,
1073 FALSE,
1074 "Illegal data address 0x%0X in write_bits\n",
1075 mapping_address < 0 ? address : address + nb);
1076 } else {
1077 /* 6 = byte count */
1078 modbus_set_bits_from_bytes(
1079 mb_mapping->tab_bits, mapping_address, nb, &req[offset + 6]);
1080
1081 rsp_length = ctx->backend->build_response_basis(&sft, rsp);
1082 /* 4 to copy the bit address (2) and the quantity of bits */
1083 memcpy(rsp + rsp_length, req + rsp_length, 4);
1084 rsp_length += 4;
1085 }
1086 } break;
1087 case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: {
1088 int nb = (req[offset + 3] << 8) + req[offset + 4];
1089 int nb_bytes = req[offset + 5];
1090 int mapping_address = address - mb_mapping->start_registers;
1091
1092 if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb || nb_bytes != nb * 2) {
1093 rsp_length = response_exception(
1094 ctx,
1095 &sft,
1096 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
1097 rsp,
1098 TRUE,
1099 "Illegal number of values %d in write_registers (max %d)\n",
1100 nb,
1101 MODBUS_MAX_WRITE_REGISTERS);
1102 } else if (mapping_address < 0 ||
1103 (mapping_address + nb) > mb_mapping->nb_registers) {
1104 rsp_length =
1105 response_exception(ctx,
1106 &sft,
1107 MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
1108 rsp,
1109 FALSE,
1110 "Illegal data address 0x%0X in write_registers\n",
1111 mapping_address < 0 ? address : address + nb);
1112 } else {
1113 int i, j;
1114 for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) {
1115 /* 6 and 7 = first value */
1116 mb_mapping->tab_registers[i] =
1117 (req[offset + j] << 8) + req[offset + j + 1];
1118 }
1119
1120 rsp_length = ctx->backend->build_response_basis(&sft, rsp);
1121 /* 4 to copy the address (2) and the no. of registers */
1122 memcpy(rsp + rsp_length, req + rsp_length, 4);
1123 rsp_length += 4;
1124 }
1125 } break;
1126 case MODBUS_FC_REPORT_SLAVE_ID: {
1127 int str_len;
1128 int byte_count_pos;
1129
1130 rsp_length = ctx->backend->build_response_basis(&sft, rsp);
1131 /* Skip byte count for now */
1132 byte_count_pos = rsp_length++;
1133 rsp[rsp_length++] = _REPORT_SLAVE_ID;
1134 /* Run indicator status to ON */
1135 rsp[rsp_length++] = 0xFF;
1136 /* LMB + length of LIBMODBUS_VERSION_STRING */
1137 str_len = 3 + strlen(LIBMODBUS_VERSION_STRING);
1138 memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len);
1139 rsp_length += str_len;
1140 rsp[byte_count_pos] = rsp_length - byte_count_pos - 1;
1141 } break;
1142 case MODBUS_FC_READ_EXCEPTION_STATUS:
1143 rsp_length = response_exception(ctx,
1144 &sft,
1145 MODBUS_EXCEPTION_ILLEGAL_FUNCTION,
1146 rsp,
1147 TRUE,
1148 "Unsupported function: READ EXCEPTION STATUS (0x07)\n");
1149 break;
1150 case MODBUS_FC_MASK_WRITE_REGISTER: {
1151 int mapping_address = address - mb_mapping->start_registers;
1152
1153 if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
1154 rsp_length =
1155 response_exception(ctx,
1156 &sft,
1157 MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
1158 rsp,
1159 FALSE,
1160 "Illegal data address 0x%0X in write_register\n",
1161 address);
1162 } else {
1163 uint16_t data;
1164 uint16_t and = (req[offset + 3] << 8) + req[offset + 4];
1165 uint16_t or = (req[offset + 5] << 8) + req[offset + 6];
1166
1167 rsp_length = compute_response_length_from_request(ctx, (uint8_t *) req);
1168 if (rsp_length != req_length) {
1169 /* Bad use of modbus_reply */
1170 rsp_length = response_exception(ctx,
1171 &sft,
1172 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
1173 rsp,
1174 FALSE,
1175 "Invalid request length in modbus_reply "
1176 "to mask write register (%d)\n",
1177 req_length);
1178 break;
1179 }
1180
1181 data = mb_mapping->tab_registers[mapping_address];
1182 data = (data & and) | (or & (~and));
1183 mb_mapping->tab_registers[mapping_address] = data;
1184
1185 rsp_length -= ctx->backend->checksum_length;
1186 memcpy(rsp, req, rsp_length);
1187 }
1188 } break;
1189 case MODBUS_FC_WRITE_AND_READ_REGISTERS: {
1190 int nb = (req[offset + 3] << 8) + req[offset + 4];
1191 uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];
1192 int nb_write = (req[offset + 7] << 8) + req[offset + 8];
1193 int nb_write_bytes = req[offset + 9];
1194 int mapping_address = address - mb_mapping->start_registers;
1195 int mapping_address_write = address_write - mb_mapping->start_registers;
1196
1197 if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write || nb < 1 ||
1198 MODBUS_MAX_WR_READ_REGISTERS < nb || nb_write_bytes != nb_write * 2) {
1199 rsp_length = response_exception(
1200 ctx,
1201 &sft,
1202 MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
1203 rsp,
1204 TRUE,
1205 "Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, "
1206 "R%d)\n",
1207 nb_write,
1208 nb,
1209 MODBUS_MAX_WR_WRITE_REGISTERS,
1210 MODBUS_MAX_WR_READ_REGISTERS);
1211 } else if (mapping_address < 0 ||
1212 (mapping_address + nb) > mb_mapping->nb_registers ||
1213 mapping_address_write < 0 ||
1214 (mapping_address_write + nb_write) > mb_mapping->nb_registers) {
1215 rsp_length = response_exception(
1216 ctx,
1217 &sft,
1218 MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
1219 rsp,
1220 FALSE,
1221 "Illegal data read address 0x%0X or write address 0x%0X "
1222 "write_and_read_registers\n",
1223 mapping_address < 0 ? address : address + nb,
1224 mapping_address_write < 0 ? address_write : address_write + nb_write);
1225 } else {
1226 int i, j;
1227 rsp_length = ctx->backend->build_response_basis(&sft, rsp);
1228 rsp[rsp_length++] = nb << 1;
1229
1230 /* Write first.
1231 10 and 11 are the offset of the first values to write */
1232 for (i = mapping_address_write, j = 10; i < mapping_address_write + nb_write;
1233 i++, j += 2) {
1234 mb_mapping->tab_registers[i] =
1235 (req[offset + j] << 8) + req[offset + j + 1];
1236 }
1237
1238 /* and read the data for the response */
1239 for (i = mapping_address; i < mapping_address + nb; i++) {
1240 rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
1241 rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
1242 }
1243 }
1244 } break;
1245
1246 default:
1247 rsp_length = response_exception(ctx,
1248 &sft,
1249 MODBUS_EXCEPTION_ILLEGAL_FUNCTION,
1250 rsp,
1251 TRUE,
1252 "Unknown Modbus function code: 0x%0X\n",
1253 function);
1254 break;
1255 }
1256
1257 /* Suppress any responses in RTU when the request was a broadcast, excepted when
1258 * quirk is enabled. */
1259 if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&
1260 slave == MODBUS_BROADCAST_ADDRESS &&
1261 !(ctx->quirks & MODBUS_QUIRK_REPLY_TO_BROADCAST)) {
1262 return 0;
1263 }
1264 return send_msg(ctx, rsp, rsp_length);
1265 }
1266
1267 int modbus_reply_exception(modbus_t *ctx, const uint8_t *req, unsigned int exception_code)
1268 {
1269 unsigned int offset;
1270 int slave;
1271 int function;
1272 uint8_t rsp[MAX_MESSAGE_LENGTH];
1273 int rsp_length;
1274 sft_t sft;
1275
1276 if (ctx == NULL || req == NULL) {
1277 errno = EINVAL;
1278 return -1;
1279 }
1280
1281 offset = ctx->backend->header_length;
1282 slave = req[offset - 1];
1283 function = req[offset];
1284
1285 sft.slave = slave;
1286 sft.function = function + 0x80;
1287 sft.t_id = ctx->backend->get_response_tid(req);
1288 rsp_length = ctx->backend->build_response_basis(&sft, rsp);
1289
1290 /* Positive exception code */
1291 if (exception_code < MODBUS_EXCEPTION_MAX) {
1292 rsp[rsp_length++] = exception_code;
1293 return send_msg(ctx, rsp, rsp_length);
1294 } else {
1295 errno = EINVAL;
1296 return -1;
1297 }
1298 }
1299
1300 /* Forward a request received on one context to another and relay the response back.
1301 This function is useful to implement a Modbus gateway/proxy that bridges
1302 two different backends (eg. TCP to RTU). */
1303 int modbus_proxy(modbus_t *frontend_ctx,
1304 modbus_t *backend_ctx,
1305 const uint8_t *req,
1306 int req_length)
1307 {
1308 int rc;
1309 int frontend_header_length;
1310 int frontend_checksum_length;
1311 int backend_header_length;
1312 int backend_checksum_length;
1313 int pdu_length;
1314 uint8_t backend_req[MAX_MESSAGE_LENGTH];
1315 int backend_req_length;
1316 uint8_t backend_rsp[MAX_MESSAGE_LENGTH];
1317 int backend_rsp_length;
1318 uint8_t frontend_rsp[MAX_MESSAGE_LENGTH];
1319 int frontend_rsp_length;
1320 sft_t sft;
1321
1322 if (frontend_ctx == NULL || backend_ctx == NULL) {
1323 errno = EINVAL;
1324 return -1;
1325 }
1326
1327 if (req == NULL || req_length < 1) {
1328 errno = EINVAL;
1329 return -1;
1330 }
1331
1332 frontend_header_length = frontend_ctx->backend->header_length;
1333 frontend_checksum_length = frontend_ctx->backend->checksum_length;
1334 backend_header_length = backend_ctx->backend->header_length;
1335 backend_checksum_length = backend_ctx->backend->checksum_length;
1336
1337 /* Extract the PDU (slave + function + data) from the frontend request.
1338 The PDU sits between the header and the checksum. */
1339 pdu_length = req_length - frontend_header_length - frontend_checksum_length;
1340 if (pdu_length < 1 || pdu_length > MODBUS_MAX_PDU_LENGTH + 1) {
1341 errno = EMBBADDATA;
1342 return -1;
1343 }
1344
1345 /* Set the slave address on the backend context */
1346 rc = modbus_set_slave(backend_ctx, req[frontend_header_length - 1]);
1347 if (rc == -1) {
1348 modbus_reply_exception(frontend_ctx, req, MODBUS_EXCEPTION_GATEWAY_PATH);
1349 return -1;
1350 }
1351
1352 /* Build a raw request for the backend from the PDU.
1353 The raw request for modbus_send_raw_request is: slave + function + data
1354 (ie. the PDU from the frontend request, starting at header_length - 1).
1355 pdu_length is bounded above by the check on MODBUS_MAX_PDU_LENGTH, so
1356 pdu_length + 1 always fits in backend_req[MAX_MESSAGE_LENGTH]. */
1357 memcpy(backend_req, req + frontend_header_length - 1, pdu_length + 1);
1358 backend_req_length = pdu_length + 1;
1359
1360 /* Keep the transaction ID of the frontend request to restore it in the
1361 response sent to the frontend */
1362 sft.slave = backend_req[0];
1363 sft.function = backend_req[1];
1364 sft.t_id = frontend_ctx->backend->get_response_tid(req);
1365
1366 /* Send the request to the backend device using raw request.
1367 modbus_send_raw_request_tid wraps the PDU into the backend framing.
1368 The backend request uses transaction ID 0 and the pre-check of the
1369 confirmation below relies on it (check_sft.t_id) */
1370 rc = modbus_send_raw_request_tid(
1371 backend_ctx, backend_req, backend_req_length, 0);
1372 if (rc == -1) {
1373 modbus_reply_exception(frontend_ctx, req, MODBUS_EXCEPTION_GATEWAY_PATH);
1374 return -1;
1375 }
1376
1377 /* Receive the response from the backend */
1378 backend_rsp_length = _modbus_receive_msg(backend_ctx, backend_rsp, MSG_CONFIRMATION);
1379 if (backend_rsp_length == -1) {
1380 if (errno == ETIMEDOUT)
1381 modbus_reply_exception(
1382 frontend_ctx, req, MODBUS_EXCEPTION_GATEWAY_TARGET);
1383 else
1384 modbus_reply_exception(
1385 frontend_ctx, req, MODBUS_EXCEPTION_GATEWAY_PATH);
1386 return -1;
1387 }
1388
1389 /* Check the backend response integrity */
1390 if (backend_ctx->backend->pre_check_confirmation) {
1391 /* Build a minimal req for the pre_check (only header matters for TID/slave check).
1392 We reuse the backend_req buffer which still holds our sent data. */
1393 uint8_t check_req[MAX_MESSAGE_LENGTH];
1394 int check_req_length;
1395 sft_t check_sft;
1396
1397 check_sft.slave = sft.slave;
1398 check_sft.function = sft.function;
1399 check_sft.t_id = 0;
1400 check_req_length = backend_ctx->backend->build_response_basis(&check_sft, check_req);
1401 /* Append enough data so the length is valid */
1402 if (backend_req_length > 2) {
1403 memcpy(check_req + check_req_length, backend_req + 2, backend_req_length - 2);
1404 check_req_length += backend_req_length - 2;
1405 }
1406
1407 rc = backend_ctx->backend->pre_check_confirmation(
1408 backend_ctx, check_req, backend_rsp, backend_rsp_length);
1409 if (rc == -1) {
1410 modbus_reply_exception(
1411 frontend_ctx, req, MODBUS_EXCEPTION_GATEWAY_TARGET);
1412 return -1;
1413 }
1414 }
1415
1416 /* Extract the PDU from the backend response and wrap it for the frontend.
1417 Backend response layout: [header][function][data...][checksum] */
1418 pdu_length =
1419 backend_rsp_length - backend_header_length - backend_checksum_length;
1420 if (pdu_length < 1) {
1421 modbus_reply_exception(
1422 frontend_ctx, req, MODBUS_EXCEPTION_GATEWAY_TARGET);
1423 return -1;
1424 }
1425
1426 /* Build the frontend response: use the original slave and function from the
1427 backend response, and the transaction ID from the frontend request. */
1428 sft.slave = backend_rsp[backend_header_length - 1];
1429 sft.function = backend_rsp[backend_header_length];
1430 /* sft.t_id was already set from the frontend request above */
1431
1432 frontend_rsp_length =
1433 frontend_ctx->backend->build_response_basis(&sft, frontend_rsp);
1434
1435 /* Copy the remaining PDU data (everything after function code) */
1436 if (pdu_length > 1) {
1437 int data_length = pdu_length - 1;
1438 memcpy(frontend_rsp + frontend_rsp_length,
1439 backend_rsp + backend_header_length + 1,
1440 data_length);
1441 frontend_rsp_length += data_length;
1442 }
1443
1444 return send_msg(frontend_ctx, frontend_rsp, frontend_rsp_length);
1445 }
1446
1447 /* Reads IO status */
1448 static int read_io_status(modbus_t *ctx, int function, int addr, int nb, uint8_t *dest)
1449 {
1450 int rc;
1451 int req_length;
1452
1453 uint8_t req[_MIN_REQ_LENGTH];
1454 uint8_t rsp[MAX_MESSAGE_LENGTH];
1455
1456 req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req);
1457
1458 rc = send_msg(ctx, req, req_length);
1459 if (rc > 0) {
1460 int temp, bit;
1461 int pos = 0;
1462 unsigned int offset;
1463 unsigned int offset_end;
1464 unsigned int i;
1465
1466 rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
1467 if (rc == -1)
1468 return -1;
1469
1470 rc = check_confirmation(ctx, req, rsp, rc);
1471 if (rc == -1)
1472 return -1;
1473
1474 offset = ctx->backend->header_length + 2;
1475 offset_end = offset + rc;
1476 for (i = offset; i < offset_end; i++) {
1477 /* Shift reg hi_byte to temp */
1478 temp = rsp[i];
1479
1480 for (bit = 0x01; (bit & 0xff) && (pos < nb);) {
1481 dest[pos++] = (temp & bit) ? TRUE : FALSE;
1482 bit = bit << 1;
1483 }
1484 }
1485 }
1486
1487 return rc;
1488 }
1489
1490 /* Reads the boolean status of bits and sets the array elements
1491 in the destination to TRUE or FALSE (single bits). */
1492 int modbus_read_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest)
1493 {
1494 int rc;
1495
1496 if (ctx == NULL || dest == NULL) {
1497 errno = EINVAL;
1498 return -1;
1499 }
1500
1501 if (nb < 1 || nb > MODBUS_MAX_READ_BITS) {
1502 if (ctx->debug) {
1503 fprintf(stderr,
1504 "ERROR Too many bits requested (%d > %d)\n",
1505 nb,
1506 MODBUS_MAX_READ_BITS);
1507 }
1508 errno = EMBXILVAL;
1509 return -1;
1510 }
1511
1512 rc = read_io_status(ctx, MODBUS_FC_READ_COILS, addr, nb, dest);
1513
1514 if (rc == -1)
1515 return -1;
1516 else
1517 return nb;
1518 }
1519
1520 /* Same as modbus_read_bits but reads the remote device input table */
1521 int modbus_read_input_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest)
1522 {
1523 int rc;
1524
1525 if (ctx == NULL || dest == NULL) {
1526 errno = EINVAL;
1527 return -1;
1528 }
1529
1530 if (nb < 1 || nb > MODBUS_MAX_READ_BITS) {
1531 if (ctx->debug) {
1532 fprintf(stderr,
1533 "ERROR Too many discrete inputs requested (%d > %d)\n",
1534 nb,
1535 MODBUS_MAX_READ_BITS);
1536 }
1537 errno = EMBXILVAL;
1538 return -1;
1539 }
1540
1541 rc = read_io_status(ctx, MODBUS_FC_READ_DISCRETE_INPUTS, addr, nb, dest);
1542
1543 if (rc == -1)
1544 return -1;
1545 else
1546 return nb;
1547 }
1548
1549 /* Reads the data from a remote device and put that data into an array */
1550 static int read_registers(modbus_t *ctx, int function, int addr, int nb, uint16_t *dest)
1551 {
1552 int rc;
1553 int req_length;
1554 uint8_t req[_MIN_REQ_LENGTH];
1555 uint8_t rsp[MAX_MESSAGE_LENGTH];
1556
1557 if (nb > MODBUS_MAX_READ_REGISTERS) {
1558 if (ctx->debug) {
1559 fprintf(stderr,
1560 "ERROR Too many registers requested (%d > %d)\n",
1561 nb,
1562 MODBUS_MAX_READ_REGISTERS);
1563 }
1564 errno = EMBXILVAL;
1565 return -1;
1566 }
1567
1568 req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req);
1569
1570 rc = send_msg(ctx, req, req_length);
1571 if (rc > 0) {
1572 unsigned int offset;
1573 int i;
1574
1575 rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
1576 if (rc == -1)
1577 return -1;
1578
1579 rc = check_confirmation(ctx, req, rsp, rc);
1580 if (rc == -1)
1581 return -1;
1582
1583 offset = ctx->backend->header_length;
1584
1585 for (i = 0; i < rc; i++) {
1586 /* shift reg hi_byte to temp OR with lo_byte */
1587 dest[i] = (rsp[offset + 2 + (i << 1)] << 8) | rsp[offset + 3 + (i << 1)];
1588 }
1589 }
1590
1591 return rc;
1592 }
1593
1594 /* Reads the holding registers of remote device and put the data into an
1595 array */
1596 int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest)
1597 {
1598 int status;
1599
1600 if (ctx == NULL || dest == NULL) {
1601 errno = EINVAL;
1602 return -1;
1603 }
1604
1605 if (nb < 1 || nb > MODBUS_MAX_READ_REGISTERS) {
1606 if (ctx->debug) {
1607 fprintf(stderr,
1608 "ERROR Too many registers requested (%d > %d)\n",
1609 nb,
1610 MODBUS_MAX_READ_REGISTERS);
1611 }
1612 errno = EMBXILVAL;
1613 return -1;
1614 }
1615
1616 status = read_registers(ctx, MODBUS_FC_READ_HOLDING_REGISTERS, addr, nb, dest);
1617 return status;
1618 }
1619
1620 /* Reads the input registers of remote device and put the data into an array */
1621 int modbus_read_input_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest)
1622 {
1623 int status;
1624
1625 if (ctx == NULL || dest == NULL) {
1626 errno = EINVAL;
1627 return -1;
1628 }
1629
1630 if (nb < 1 || nb > MODBUS_MAX_READ_REGISTERS) {
1631 if (ctx->debug) {
1632 fprintf(stderr,
1633 "ERROR Too many input registers requested (%d > %d)\n",
1634 nb,
1635 MODBUS_MAX_READ_REGISTERS);
1636 }
1637 errno = EMBXILVAL;
1638 return -1;
1639 }
1640
1641 status = read_registers(ctx, MODBUS_FC_READ_INPUT_REGISTERS, addr, nb, dest);
1642
1643 return status;
1644 }
1645
1646 /* Write a value to the specified register of the remote device.
1647 Used by write_bit and write_register */
1648 static int write_single(modbus_t *ctx, int function, int addr, const uint16_t value)
1649 {
1650 int rc;
1651 int req_length;
1652 uint8_t req[_MIN_REQ_LENGTH];
1653
1654 if (ctx == NULL) {
1655 errno = EINVAL;
1656 return -1;
1657 }
1658
1659 req_length = ctx->backend->build_request_basis(ctx, function, addr, (int) value, req);
1660
1661 rc = send_msg(ctx, req, req_length);
1662 if (rc > 0) {
1663 /* Used by write_bit and write_register */
1664 uint8_t rsp[MAX_MESSAGE_LENGTH];
1665
1666 rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
1667 if (rc == -1)
1668 return -1;
1669
1670 rc = check_confirmation(ctx, req, rsp, rc);
1671 }
1672
1673 return rc;
1674 }
1675
1676 /* Turns ON or OFF a single bit of the remote device */
1677 int modbus_write_bit(modbus_t *ctx, int addr, int status)
1678 {
1679 if (ctx == NULL) {
1680 errno = EINVAL;
1681 return -1;
1682 }
1683
1684 return write_single(ctx, MODBUS_FC_WRITE_SINGLE_COIL, addr, status ? 0xFF00 : 0);
1685 }
1686
1687 /* Writes a value in one register of the remote device */
1688 int modbus_write_register(modbus_t *ctx, int addr, const uint16_t value)
1689 {
1690 if (ctx == NULL) {
1691 errno = EINVAL;
1692 return -1;
1693 }
1694
1695 return write_single(ctx, MODBUS_FC_WRITE_SINGLE_REGISTER, addr, value);
1696 }
1697
1698 /* Write the bits of the array in the remote device */
1699 int modbus_write_bits(modbus_t *ctx, int addr, int nb, const uint8_t *src)
1700 {
1701 int rc;
1702 int i;
1703 int byte_count;
1704 int req_length;
1705 int bit_check = 0;
1706 int pos = 0;
1707 uint8_t req[MAX_MESSAGE_LENGTH];
1708
1709 if (ctx == NULL || src == NULL) {
1710 errno = EINVAL;
1711 return -1;
1712 }
1713
1714 if (nb < 1 || nb > MODBUS_MAX_WRITE_BITS) {
1715 if (ctx->debug) {
1716 fprintf(stderr,
1717 "ERROR Writing too many bits (%d > %d)\n",
1718 nb,
1719 MODBUS_MAX_WRITE_BITS);
1720 }
1721 errno = EMBXILVAL;
1722 return -1;
1723 }
1724
1725 req_length = ctx->backend->build_request_basis(
1726 ctx, MODBUS_FC_WRITE_MULTIPLE_COILS, addr, nb, req);
1727 byte_count = (nb / 8) + ((nb % 8) ? 1 : 0);
1728 req[req_length++] = byte_count;
1729
1730 for (i = 0; i < byte_count; i++) {
1731 int bit;
1732
1733 bit = 0x01;
1734 req[req_length] = 0;
1735
1736 while ((bit & 0xFF) && (bit_check++ < nb)) {
1737 if (src[pos++])
1738 req[req_length] |= bit;
1739 else
1740 req[req_length] &= ~bit;
1741
1742 bit = bit << 1;
1743 }
1744 req_length++;
1745 }
1746
1747 rc = send_msg(ctx, req, req_length);
1748 if (rc > 0) {
1749 uint8_t rsp[MAX_MESSAGE_LENGTH];
1750
1751 rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
1752 if (rc == -1)
1753 return -1;
1754
1755 rc = check_confirmation(ctx, req, rsp, rc);
1756 }
1757
1758 return rc;
1759 }
1760
1761 /* Write the values from the array to the registers of the remote device */
1762 int modbus_write_registers(modbus_t *ctx, int addr, int nb, const uint16_t *src)
1763 {
1764 int rc;
1765 int i;
1766 int req_length;
1767 int byte_count;
1768 uint8_t req[MAX_MESSAGE_LENGTH];
1769
1770 if (ctx == NULL || src == NULL) {
1771 errno = EINVAL;
1772 return -1;
1773 }
1774
1775 if (nb < 1 || nb > MODBUS_MAX_WRITE_REGISTERS) {
1776 if (ctx->debug) {
1777 fprintf(stderr,
1778 "ERROR Trying to write to too many registers (%d > %d)\n",
1779 nb,
1780 MODBUS_MAX_WRITE_REGISTERS);
1781 }
1782 errno = EMBXILVAL;
1783 return -1;
1784 }
1785
1786 req_length = ctx->backend->build_request_basis(
1787 ctx, MODBUS_FC_WRITE_MULTIPLE_REGISTERS, addr, nb, req);
1788 byte_count = nb * 2;
1789 req[req_length++] = byte_count;
1790
1791 for (i = 0; i < nb; i++) {
1792 req[req_length++] = src[i] >> 8;
1793 req[req_length++] = src[i] & 0x00FF;
1794 }
1795
1796 rc = send_msg(ctx, req, req_length);
1797 if (rc > 0) {
1798 uint8_t rsp[MAX_MESSAGE_LENGTH];
1799
1800 rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
1801 if (rc == -1)
1802 return -1;
1803
1804 rc = check_confirmation(ctx, req, rsp, rc);
1805 }
1806
1807 return rc;
1808 }
1809
1810 int modbus_mask_write_register(modbus_t *ctx,
1811 int addr,
1812 uint16_t and_mask,
1813 uint16_t or_mask)
1814 {
1815 int rc;
1816 int req_length;
1817 /* The request length can not exceed _MIN_REQ_LENGTH - 2 and 4 bytes to
1818 * store the masks. The ugly substraction is there to remove the 'nb' value
1819 * (2 bytes) which is not used. */
1820 uint8_t req[_MIN_REQ_LENGTH + 2];
1821
1822 if (ctx == NULL) {
1823 errno = EINVAL;
1824 return -1;
1825 }
1826
1827 req_length = ctx->backend->build_request_basis(
1828 ctx, MODBUS_FC_MASK_WRITE_REGISTER, addr, 0, req);
1829
1830 /* HACKISH, count is not used */
1831 req_length -= 2;
1832
1833 req[req_length++] = and_mask >> 8;
1834 req[req_length++] = and_mask & 0x00ff;
1835 req[req_length++] = or_mask >> 8;
1836 req[req_length++] = or_mask & 0x00ff;
1837
1838 rc = send_msg(ctx, req, req_length);
1839 if (rc > 0) {
1840 /* Used by write_bit and write_register */
1841 uint8_t rsp[MAX_MESSAGE_LENGTH];
1842
1843 rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
1844 if (rc == -1)
1845 return -1;
1846
1847 rc = check_confirmation(ctx, req, rsp, rc);
1848 }
1849
1850 return rc;
1851 }
1852
1853 /* Write multiple registers from src array to remote device and read multiple
1854 registers from remote device to dest array. */
1855 int modbus_write_and_read_registers(modbus_t *ctx,
1856 int write_addr,
1857 int write_nb,
1858 const uint16_t *src,
1859 int read_addr,
1860 int read_nb,
1861 uint16_t *dest)
1862
1863 {
1864 int rc;
1865 int req_length;
1866 int i;
1867 int byte_count;
1868 uint8_t req[MAX_MESSAGE_LENGTH];
1869 uint8_t rsp[MAX_MESSAGE_LENGTH];
1870
1871 if (ctx == NULL || src == NULL || dest == NULL || write_nb < 1 || read_nb < 1) {
1872 errno = EINVAL;
1873 return -1;
1874 }
1875
1876 if (write_nb > MODBUS_MAX_WR_WRITE_REGISTERS) {
1877 if (ctx->debug) {
1878 fprintf(stderr,
1879 "ERROR Too many registers to write (%d > %d)\n",
1880 write_nb,
1881 MODBUS_MAX_WR_WRITE_REGISTERS);
1882 }
1883 errno = EMBXILVAL;
1884 return -1;
1885 }
1886
1887 if (read_nb > MODBUS_MAX_WR_READ_REGISTERS) {
1888 if (ctx->debug) {
1889 fprintf(stderr,
1890 "ERROR Too many registers requested (%d > %d)\n",
1891 read_nb,
1892 MODBUS_MAX_WR_READ_REGISTERS);
1893 }
1894 errno = EMBXILVAL;
1895 return -1;
1896 }
1897 req_length = ctx->backend->build_request_basis(
1898 ctx, MODBUS_FC_WRITE_AND_READ_REGISTERS, read_addr, read_nb, req);
1899
1900 req[req_length++] = write_addr >> 8;
1901 req[req_length++] = write_addr & 0x00ff;
1902 req[req_length++] = write_nb >> 8;
1903 req[req_length++] = write_nb & 0x00ff;
1904 byte_count = write_nb * 2;
1905 req[req_length++] = byte_count;
1906
1907 for (i = 0; i < write_nb; i++) {
1908 req[req_length++] = src[i] >> 8;
1909 req[req_length++] = src[i] & 0x00FF;
1910 }
1911
1912 rc = send_msg(ctx, req, req_length);
1913 if (rc > 0) {
1914 unsigned int offset;
1915
1916 rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
1917 if (rc == -1)
1918 return -1;
1919
1920 rc = check_confirmation(ctx, req, rsp, rc);
1921 if (rc == -1)
1922 return -1;
1923
1924 offset = ctx->backend->header_length;
1925 for (i = 0; i < rc; i++) {
1926 /* shift reg hi_byte to temp OR with lo_byte */
1927 dest[i] = (rsp[offset + 2 + (i << 1)] << 8) | rsp[offset + 3 + (i << 1)];
1928 }
1929 }
1930
1931 return rc;
1932 }
1933
1934 /* Send a request to get the slave ID of the device (only available in serial
1935 communication). */
1936 int modbus_report_slave_id(modbus_t *ctx, int max_dest, uint8_t *dest)
1937 {
1938 int rc;
1939 int req_length;
1940 uint8_t req[_MIN_REQ_LENGTH];
1941
1942 if (ctx == NULL || dest == NULL || max_dest <= 0) {
1943 errno = EINVAL;
1944 return -1;
1945 }
1946
1947 req_length =
1948 ctx->backend->build_request_basis(ctx, MODBUS_FC_REPORT_SLAVE_ID, 0, 0, req);
1949
1950 /* HACKISH, addr and count are not used */
1951 req_length -= 4;
1952
1953 rc = send_msg(ctx, req, req_length);
1954 if (rc > 0) {
1955 int i;
1956 unsigned int offset;
1957 uint8_t rsp[MAX_MESSAGE_LENGTH];
1958
1959 rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
1960 if (rc == -1)
1961 return -1;
1962
1963 rc = check_confirmation(ctx, req, rsp, rc);
1964 if (rc == -1)
1965 return -1;
1966
1967 offset = ctx->backend->header_length + 2;
1968
1969 /* Byte count, slave id, run indicator status and
1970 additional data. Truncate copy to max_dest. */
1971 for (i = 0; i < rc && i < max_dest; i++) {
1972 dest[i] = rsp[offset + i];
1973 }
1974 }
1975
1976 return rc;
1977 }
1978
1979 void _modbus_init_common(modbus_t *ctx)
1980 {
1981 /* Slave and socket are initialized to -1 */
1982 ctx->slave = -1;
1983 ctx->s = -1;
1984
1985 ctx->debug = FALSE;
1986 ctx->error_recovery = MODBUS_ERROR_RECOVERY_NONE;
1987 ctx->quirks = MODBUS_QUIRK_NONE;
1988
1989 ctx->response_timeout.tv_sec = 0;
1990 ctx->response_timeout.tv_usec = _RESPONSE_TIMEOUT;
1991
1992 ctx->byte_timeout.tv_sec = 0;
1993 ctx->byte_timeout.tv_usec = _BYTE_TIMEOUT;
1994
1995 ctx->indication_timeout.tv_sec = 0;
1996 ctx->indication_timeout.tv_usec = 0;
1997 }
1998
1999 /* Define the slave number */
2000 int modbus_set_slave(modbus_t *ctx, int slave)
2001 {
2002 if (ctx == NULL) {
2003 errno = EINVAL;
2004 return -1;
2005 }
2006
2007 return ctx->backend->set_slave(ctx, slave);
2008 }
2009
2010 int modbus_get_slave(modbus_t *ctx)
2011 {
2012 if (ctx == NULL) {
2013 errno = EINVAL;
2014 return -1;
2015 }
2016
2017 return ctx->slave;
2018 }
2019
2020 int modbus_set_error_recovery(modbus_t *ctx, modbus_error_recovery_mode error_recovery)
2021 {
2022 if (ctx == NULL) {
2023 errno = EINVAL;
2024 return -1;
2025 }
2026
2027 /* The type of modbus_error_recovery_mode is unsigned enum */
2028 ctx->error_recovery = (uint8_t) error_recovery;
2029 return 0;
2030 }
2031
2032 // FIXME Doesn't work under Windows RTU
2033 int modbus_set_socket(modbus_t *ctx, int s)
2034 {
2035 if (ctx == NULL) {
2036 errno = EINVAL;
2037 return -1;
2038 }
2039
2040 ctx->s = s;
2041 return 0;
2042 }
2043
2044 int modbus_get_socket(modbus_t *ctx)
2045 {
2046 if (ctx == NULL) {
2047 errno = EINVAL;
2048 return -1;
2049 }
2050
2051 return ctx->s;
2052 }
2053
2054 /* Get the timeout interval used to wait for a response */
2055 int modbus_get_response_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
2056 {
2057 if (ctx == NULL || to_sec == NULL || to_usec == NULL) {
2058 errno = EINVAL;
2059 return -1;
2060 }
2061
2062 *to_sec = ctx->response_timeout.tv_sec;
2063 *to_usec = ctx->response_timeout.tv_usec;
2064 return 0;
2065 }
2066
2067 int modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
2068 {
2069 if (ctx == NULL || (to_sec == 0 && to_usec == 0) || to_usec > 999999) {
2070 errno = EINVAL;
2071 return -1;
2072 }
2073
2074 ctx->response_timeout.tv_sec = to_sec;
2075 ctx->response_timeout.tv_usec = to_usec;
2076 return 0;
2077 }
2078
2079 /* Get the timeout interval between two consecutive bytes of a message */
2080 int modbus_get_byte_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
2081 {
2082 if (ctx == NULL || to_sec == NULL || to_usec == NULL) {
2083 errno = EINVAL;
2084 return -1;
2085 }
2086
2087 *to_sec = ctx->byte_timeout.tv_sec;
2088 *to_usec = ctx->byte_timeout.tv_usec;
2089 return 0;
2090 }
2091
2092 int modbus_set_byte_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
2093 {
2094 /* Byte timeout can be disabled when both values are zero */
2095 if (ctx == NULL || to_usec > 999999) {
2096 errno = EINVAL;
2097 return -1;
2098 }
2099
2100 ctx->byte_timeout.tv_sec = to_sec;
2101 ctx->byte_timeout.tv_usec = to_usec;
2102 return 0;
2103 }
2104
2105 /* Get the timeout interval used by the server to wait for an indication from a client
2106 */
2107 int modbus_get_indication_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
2108 {
2109 if (ctx == NULL || to_sec == NULL || to_usec == NULL) {
2110 errno = EINVAL;
2111 return -1;
2112 }
2113
2114 *to_sec = ctx->indication_timeout.tv_sec;
2115 *to_usec = ctx->indication_timeout.tv_usec;
2116 return 0;
2117 }
2118
2119 int modbus_set_indication_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
2120 {
2121 /* Indication timeout can be disabled when both values are zero */
2122 if (ctx == NULL || to_usec > 999999) {
2123 errno = EINVAL;
2124 return -1;
2125 }
2126
2127 ctx->indication_timeout.tv_sec = to_sec;
2128 ctx->indication_timeout.tv_usec = to_usec;
2129 return 0;
2130 }
2131
2132 int modbus_get_header_length(modbus_t *ctx)
2133 {
2134 if (ctx == NULL) {
2135 errno = EINVAL;
2136 return -1;
2137 }
2138
2139 return ctx->backend->header_length;
2140 }
2141
2142 int modbus_enable_quirks(modbus_t *ctx, unsigned int quirks_mask)
2143 {
2144 if (ctx == NULL) {
2145 errno = EINVAL;
2146 return -1;
2147 }
2148
2149 /* Enable quirks that have a true value at their index in the mask */
2150 ctx->quirks |= quirks_mask;
2151 return 0;
2152 }
2153
2154 int modbus_disable_quirks(modbus_t *ctx, unsigned int quirks_mask)
2155 {
2156 if (ctx == NULL) {
2157 errno = EINVAL;
2158 return -1;
2159 }
2160
2161 /* Disable quirks that have a true value at ther index in the mask */
2162 ctx->quirks &= ~quirks_mask;
2163 return 0;
2164 }
2165
2166 int modbus_connect(modbus_t *ctx)
2167 {
2168 if (ctx == NULL) {
2169 errno = EINVAL;
2170 return -1;
2171 }
2172
2173 return ctx->backend->connect(ctx);
2174 }
2175
2176 void modbus_close(modbus_t *ctx)
2177 {
2178 if (ctx == NULL)
2179 return;
2180
2181 ctx->backend->close(ctx);
2182 }
2183
2184 void modbus_free(modbus_t *ctx)
2185 {
2186 if (ctx == NULL)
2187 return;
2188
2189 ctx->backend->free(ctx);
2190 }
2191
2192 int modbus_set_debug(modbus_t *ctx, int flag)
2193 {
2194 if (ctx == NULL) {
2195 errno = EINVAL;
2196 return -1;
2197 }
2198
2199 ctx->debug = flag;
2200 return 0;
2201 }
2202
2203 /* Allocates 4 arrays to store bits, input bits, registers and inputs
2204 registers. The pointers are stored in modbus_mapping structure.
2205
2206 The modbus_mapping_new_start_address() function shall return the new allocated
2207 structure if successful. Otherwise it shall return NULL and set errno to
2208 ENOMEM. */
2209 modbus_mapping_t *modbus_mapping_new_start_address(unsigned int start_bits,
2210 unsigned int nb_bits,
2211 unsigned int start_input_bits,
2212 unsigned int nb_input_bits,
2213 unsigned int start_registers,
2214 unsigned int nb_registers,
2215 unsigned int start_input_registers,
2216 unsigned int nb_input_registers)
2217 {
2218 modbus_mapping_t *mb_mapping;
2219
2220 /* Reject dimensions larger than the addressable space to avoid excessively
2221 large allocations driven by untrusted configuration. */
2222 if (nb_bits > MODBUS_MAX_TABLE_SIZE || nb_input_bits > MODBUS_MAX_TABLE_SIZE ||
2223 nb_registers > MODBUS_MAX_TABLE_SIZE ||
2224 nb_input_registers > MODBUS_MAX_TABLE_SIZE) {
2225 errno = EINVAL;
2226 return NULL;
2227 }
2228
2229 mb_mapping = (modbus_mapping_t *) malloc(sizeof(modbus_mapping_t));
2230 if (mb_mapping == NULL) {
2231 return NULL;
2232 }
2233
2234 /* 0X */
2235 mb_mapping->nb_bits = nb_bits;
2236 mb_mapping->start_bits = start_bits;
2237 if (nb_bits == 0) {
2238 mb_mapping->tab_bits = NULL;
2239 } else {
2240 mb_mapping->tab_bits = (uint8_t *) malloc(nb_bits * sizeof(uint8_t));
2241 if (mb_mapping->tab_bits == NULL) {
2242 free(mb_mapping);
2243 return NULL;
2244 }
2245 memset(mb_mapping->tab_bits, 0, nb_bits * sizeof(uint8_t));
2246 }
2247
2248 /* 1X */
2249 mb_mapping->nb_input_bits = nb_input_bits;
2250 mb_mapping->start_input_bits = start_input_bits;
2251 if (nb_input_bits == 0) {
2252 mb_mapping->tab_input_bits = NULL;
2253 } else {
2254 mb_mapping->tab_input_bits = (uint8_t *) malloc(nb_input_bits * sizeof(uint8_t));
2255 if (mb_mapping->tab_input_bits == NULL) {
2256 free(mb_mapping->tab_bits);
2257 free(mb_mapping);
2258 return NULL;
2259 }
2260 memset(mb_mapping->tab_input_bits, 0, nb_input_bits * sizeof(uint8_t));
2261 }
2262
2263 /* 4X */
2264 mb_mapping->nb_registers = nb_registers;
2265 mb_mapping->start_registers = start_registers;
2266 if (nb_registers == 0) {
2267 mb_mapping->tab_registers = NULL;
2268 } else {
2269 mb_mapping->tab_registers = (uint16_t *) malloc(nb_registers * sizeof(uint16_t));
2270 if (mb_mapping->tab_registers == NULL) {
2271 free(mb_mapping->tab_input_bits);
2272 free(mb_mapping->tab_bits);
2273 free(mb_mapping);
2274 return NULL;
2275 }
2276 memset(mb_mapping->tab_registers, 0, nb_registers * sizeof(uint16_t));
2277 }
2278
2279 /* 3X */
2280 mb_mapping->nb_input_registers = nb_input_registers;
2281 mb_mapping->start_input_registers = start_input_registers;
2282 if (nb_input_registers == 0) {
2283 mb_mapping->tab_input_registers = NULL;
2284 } else {
2285 mb_mapping->tab_input_registers =
2286 (uint16_t *) malloc(nb_input_registers * sizeof(uint16_t));
2287 if (mb_mapping->tab_input_registers == NULL) {
2288 free(mb_mapping->tab_registers);
2289 free(mb_mapping->tab_input_bits);
2290 free(mb_mapping->tab_bits);
2291 free(mb_mapping);
2292 return NULL;
2293 }
2294 memset(mb_mapping->tab_input_registers, 0, nb_input_registers * sizeof(uint16_t));
2295 }
2296
2297 return mb_mapping;
2298 }
2299
2300 modbus_mapping_t *modbus_mapping_new(int nb_bits,
2301 int nb_input_bits,
2302 int nb_registers,
2303 int nb_input_registers)
2304 {
2305 /* Reject negative counts: they would otherwise be converted to very large
2306 unsigned dimensions and drive huge allocations. */
2307 if (nb_bits < 0 || nb_input_bits < 0 || nb_registers < 0 ||
2308 nb_input_registers < 0) {
2309 errno = EINVAL;
2310 return NULL;
2311 }
2312
2313 return modbus_mapping_new_start_address(
2314 0, nb_bits, 0, nb_input_bits, 0, nb_registers, 0, nb_input_registers);
2315 }
2316
2317 /* Frees the 4 arrays */
2318 void modbus_mapping_free(modbus_mapping_t *mb_mapping)
2319 {
2320 if (mb_mapping == NULL) {
2321 return;
2322 }
2323
2324 free(mb_mapping->tab_input_registers);
2325 free(mb_mapping->tab_registers);
2326 free(mb_mapping->tab_input_bits);
2327 free(mb_mapping->tab_bits);
2328 free(mb_mapping);
2329 }
2330
2331 #ifndef HAVE_STRLCPY
2332 /*
2333 * Function strlcpy was originally developed by
2334 * Todd C. Miller <[email protected]> to simplify writing secure code.
2335 * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
2336 * for more information.
2337 *
2338 * Thank you Ulrich Drepper... not!
2339 *
2340 * Copy src to string dest of size dest_size. At most dest_size-1 characters
2341 * will be copied. Always NUL terminates (unless dest_size == 0). Returns
2342 * strlen(src); if retval >= dest_size, truncation occurred.
2343 */
2344 size_t strlcpy(char *dest, const char *src, size_t dest_size)
2345 {
2346 register char *d = dest;
2347 register const char *s = src;
2348 register size_t n = dest_size;
2349
2350 /* Copy as many bytes as will fit */
2351 if (n != 0 && --n != 0) {
2352 do {
2353 if ((*d++ = *s++) == 0)
2354 break;
2355 } while (--n != 0);
2356 }
2357
2358 /* Not enough room in dest, add NUL and traverse rest of src */
2359 if (n == 0) {
2360 if (dest_size != 0)
2361 *d = '\0'; /* NUL-terminate dest */
2362 while (*s++)
2363 ;
2364 }
2365
2366 return (s - src - 1); /* count does not include NUL */
2367 }
2368 #endif