-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmb_tcp.c
1700 lines (1432 loc) · 56 KB
/
mb_tcp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002,2016 Mario de Sousa ([email protected])
*
* This file is part of the Modbus library for Beremiz and matiec.
*
* This Modbus library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this Modbus library. If not, see <http://www.gnu.org/licenses/>.
*
* This code is made available on the understanding that it will not be
* used in safety-critical situations without a full and competent review.
*/
#include <fcntl.h> /* File control definitions */
#include <stdio.h> /* Standard input/output */
#include <string.h>
#include <stdlib.h>
#include <termio.h> /* POSIX terminal control definitions */
#include <sys/time.h> /* Time structures for select() */
#include <unistd.h> /* POSIX Symbolic Constants */
#include <assert.h>
#include <errno.h> /* Error definitions */
#include <time.h> /* clock_gettime() */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> /* required for htons() and ntohs() */
#include <netinet/tcp.h> /* TCP level socket options */
#include <netinet/ip.h> /* IP level socket options */
#include <pthread.h>
#include <sched.h> /* sched_yield() */
#include "sin_util.h" /* internet socket utility functions... */
#include "mb_layer1.h" /* The public interface this file implements... */
#include "mb_tcp_private.h"
/************************************/
/** **/
/** Include common code... **/
/** **/
/************************************/
#include "mb_time_util.h"
//#define ERRMSG
#define ERRMSG_HEAD "Modbus/TCP: "
// #define DEBUG /* uncomment to see the data sent and received */
#ifdef DEBUG
#ifndef ERRMSG
#define ERRMSG
#endif
#endif
/**************************************************************/
/**************************************************************/
/**** ****/
/**** ****/
/**** Forward Declarations ****/
/**** and Defaults ****/
/**** ****/
/**************************************************************/
/**************************************************************/
/* A Node Descriptor metadata,
* Due to the fact that modbus TCP is connection oriented,
* and that if the client detects an error the connection
* must be shut down and re-established automatically,
* the modbus TCP layer needs to keep the address of the remote server.
*
* We do this by implementing a node descriptor table, in which each
* entry will have the remote address, and the file descriptor
* of the socket currently in use.
*
* We do not pass the file descriptor up to the next higher layer. We
* send them the node descriptor instead...
*/
#define MB_MASTER_NODE 12
#define MB_LISTEN_NODE 14
#define MB_SLAVE_NODE 16
#define MB_FREE_NODE 18
typedef sa_family_t nd_type_t;
typedef struct {
int fd; /* socket descriptor == file descriptor */
/* NOTE:
* Modbus TCP says that on error, we should close
* a connection and retry with a new connection.
* Since it takes time for a socket to close
* a connection if the remote server is down,
* we close the connection on the socket, close the
* socket itself, and create a new one for the new
* connection. There will be times when the node will
* not have any valid socket, and it will have to
* be created on the fly.
* When the node does not have a valid socket,
* fd will be set to -1
*/
int node_type; /* What kind of use we are giving to this node...
* If node_type == MB_MASTER_NODE
* The node descriptor was initialised by the
* modbus_connect() function.
* The node descriptor is being used by a master
* device, and the addr contains the address of the slave.
* Remember that in this case fd may be >= 0 while
* we have a valid connection, or it may be < 0 when
* the connection needs to be reset.
* If node_type == MB_LISTEN_NODE
* The node descriptor was initialised by the
* modbus_listen() function.
* The node is merely used to accept() new connection
* requests. The new slave connections will use another
* node to transfer data.
* In this case fd must be >= 0.
* fd < 0 is an ilegal state and should never occur.
* If node_type == MB_SLAVE_NODE
* The node descriptor was initialised when a new
* connection request arrived on a MB_LISTEN type node.
* The node descriptor is being used by a slave device,
* and is currently being used to connect to a master.
* In this case fd must be >= 0.
* fd < 0 is an ilegal state and should never occur.
* If node_type == FREE_ND
* The node descriptor is currently not being used.
* In this case fd is set to -1, but is really irrelevant.
*/
struct sockaddr_in addr; /* The internet adress we are using.
* If node_type == MB_MASTER_NODE
* addr will be the address of the remote slave
* If node_type == MB_LISTEN_NODE
* addr will be the address of the local listening port and network interface
* If node_type == MB_SLAVE_NODE
* addr will be the address of the local port and network interface
* of the connection to the specific client.
*/
int listen_node; /* When a slave accepts a connection through a MB_LISTEN_NODE, it will
* will use an empty node for the new connection, and configure this new node
* to use the type MB_SLAVE_NODE.
* The listen_node entry is only used by nodes of type MB_SLAVE_NODE.
* In this case, listen_node will be the node of type MB_LISTEN_NODE through
* which the connection request came through...
*/
int close_on_silence; /* A flag used only by Master Nodes.
* When (close_on_silence > 0), then the connection to the
* slave device will be shut down whenever the
* modbus_tcp_silence_init() function is called.
* Remember that the connection will be automatically
* re-established the next time the user wishes to communicate
* with the same slave (using this same node descripto).
* If the user wishes to comply with the sugestion
* in the OpenModbus Spec, (s)he should set this flag
* if a silence interval longer than 1 second is expected.
*/
int print_connect_error; /* flag to guarantee we only print an error the first time we
* attempt to connect to a emote server.
* Stops us from generting a cascade of errors while the slave
* is down.
* Flag will get reset every time we successfully
* establish a connection, so a message is once again generated
* on the next error.
*/
u8 *recv_buf; /* This node's receive buffer
* The library supports multiple simultaneous connections,
* and may need to receive multiple frames through mutiple nodes concurrently.
* To make the library thread-safe, we use one buffer for each node.
*/
} nd_entry_t;
/* please make sure to lock the node table mutex before calling this function */
static int nd_entry_init(nd_entry_t *nde) {
nde->addr.sin_family = AF_INET ;
nde->node_type = MB_FREE_NODE;
nde->fd = -1; /* not currently connected... */
/* initialise recv buffer */
nde->recv_buf = malloc(sizeof(u8) * RECV_BUFFER_SIZE);
if (nde->recv_buf == NULL)
return -1;
return 0;
}
/* please make sure to lock the node table mutex before calling this function */
static int nd_entry_done(nd_entry_t *nde) {
free(nde->recv_buf);
return 0;
}
typedef struct {
/* the array of node descriptors, and current size... */
nd_entry_t *node; /* array of node entries. if NULL => node table not initialized */
int node_count; /* total number of nodes in the node[] array */
int free_node_count; /* number of free nodes in the node[] array */
pthread_mutex_t mutex;
} nd_table_t;
static int nd_table_done(nd_table_t *ndt) {
int count;
if (ndt->node == NULL)
return 0;
/* lock the mutex */
while (pthread_mutex_lock(&ndt->mutex) != 0) sched_yield();
/* initialise the state of each node in the array... */
for (count = 0; count < ndt->node_count; count++) {
nd_entry_done(&ndt->node[count]);
} /* for() */
free(ndt->node);
pthread_mutex_unlock (&ndt->mutex);
pthread_mutex_destroy(&ndt->mutex);
*ndt = (nd_table_t){.node=NULL, .node_count=0, .free_node_count=0};
return 0;
}
#if 1
/* nd_table_init()
* Version 1 of the nd_table_init() function.
* If called more than once, 2nd and any subsequent calls will
* be interpreted as a request to confirm that it was already correctly
* initialized with the requested number of nodes.
*/
static int nd_table_init(nd_table_t *ndt, int nd_count) {
int count;
if (ndt->node != NULL) {
/* this function has already been called, and the node table is already initialised */
return (ndt->node_count == nd_count)?0:-1;
}
/* initialise the node table mutex... */
pthread_mutex_init(&ndt->mutex, NULL);
if (pthread_mutex_lock(&ndt->mutex) != 0) {
#ifdef DEBUG
perror("pthread_mutex_lock()");
fprintf(stderr, "[%lu] Unable to lock newly crated mutex while creating new node table!\n", pthread_self());
#endif
pthread_mutex_destroy(&ndt->mutex);
return -1;
}
/* initialise the node descriptor metadata array... */
ndt->node = malloc(sizeof(nd_entry_t) * nd_count);
if (ndt->node == NULL) {
#ifdef DEBUG
perror("malloc()");
fprintf(stderr, "[%lu] Out of memory: error initializing node address buffer\n", pthread_self());
#endif
#ifdef ERRMSG
perror("malloc()");
fprintf(stderr, ERRMSG_HEAD "Out of memory. Error initializing node address buffer\n");
#endif
pthread_mutex_unlock (&ndt->mutex);
pthread_mutex_destroy(&ndt->mutex);
return -1;
}
/* initialise the state of each node in the array... */
for (count = 0; count < nd_count; count++) {
if (nd_entry_init(&ndt->node[count]) < 0) {
pthread_mutex_unlock(&ndt->mutex);
nd_table_done(ndt);
return -1;
}
ndt->node_count = count+1;
ndt->free_node_count = count+1;
} /* for() */
ndt->node_count = nd_count;
ndt->free_node_count = nd_count;
pthread_mutex_unlock(&ndt->mutex);
return nd_count; /* number of succesfully created nodes! */
}
#else
/* nd_table_init()
* Version 2 of the nd_table_init() function.
* If called more than once, 2nd and any subsequent calls will
* be interpreted as a request to reserve an extra new_nd_count
* number of nodes. This will be done using realloc().
*/
static int nd_table_init(nd_table_t *ndt, int new_nd_count) {
int count;
if (ndt->node == NULL) {
/* Node table nt yet initialized => we must initialise the node table mutex... */
pthread_mutex_init(&ndt->mutex, NULL);
}
/* lock the mutex */
while (pthread_mutex_lock(&ndt->mutex) != 0) sched_yield();
/* initialise the node descriptor metadata array... */
ndt->node = realloc(ndt->node, sizeof(nd_entry_t) * (ndt->node_count + new_nd_count));
if (ndt->node == NULL) {
#ifdef DEBUG
perror("malloc()");
fprintf(stderr, "[%lu] Out of memory: error initializing node address buffer\n", pthread_self());
#endif
#ifdef ERRMSG
perror("malloc()");
fprintf(stderr, ERRMSG_HEAD "Out of memory. Error initializing node address buffer\n");
#endif
pthread_mutex_unlock (&ndt->mutex);
pthread_mutex_destroy(&ndt->mutex);
return -1;
}
/* initialise the state of each newly added node in the array... */
for (count = ndt->node_count; count < ndt->node_count + new_nd_count; count++) {
if (nd_entry_init(&ndt->node[count]) < 0) {
pthread_mutex_unlock(&ndt->mutex);
return -1;
}
} /* for() */
ndt->node_count += new_nd_count;
ndt->free_node_count += new_nd_count;
pthread_mutex_unlock(&ndt->mutex);
return new_nd_count; /* number of succesfully created nodes! */
}
#endif
static int nd_table_get_free_node(nd_table_t *ndt, nd_type_t nd_type) {
int count;
/* lock the mutex */
while (pthread_mutex_lock(&ndt->mutex) != 0) sched_yield();
/* check for free nodes... */
if (ndt->free_node_count <= 0) {
/* no free nodes... */
pthread_mutex_unlock(&ndt->mutex);
return -1;
}
/* Decrement the free node counter...*/
ndt->free_node_count--;
/* search for a free node... */
for (count = 0; count < ndt->node_count; count++) {
if(ndt->node[count].node_type == MB_FREE_NODE) {
/* found one!! Allocate it to the new type! */
ndt->node[count].node_type = nd_type;
pthread_mutex_unlock(&ndt->mutex);
return count;
}
} /* for() */
/* Strange... We should have free nodes, but we didn't finda any! */
/* Let's try to get into a consistent state, and return an error! */
ndt->free_node_count = 0;
pthread_mutex_unlock(&ndt->mutex);
return -1;
}
static void nd_table_close_node(nd_table_t *ndt, int nd) {
/* lock the mutex */
while (pthread_mutex_lock(&ndt->mutex) != 0) sched_yield();
if(ndt->node[nd].node_type == MB_FREE_NODE) {
/* Node already free... */
pthread_mutex_unlock(&ndt->mutex);
return;
}
/* Increment the free node counter...*/
ndt->free_node_count++;
/* Mark the node as being free. */
ndt->node[nd].node_type = MB_FREE_NODE;
pthread_mutex_unlock(&ndt->mutex);
return;
}
/**************************************************************/
/**************************************************************/
/**** ****/
/**** ****/
/**** Global Library State ****/
/**** ****/
/**** ****/
/**************************************************************/
/**************************************************************/
/* The node descriptor table... */
/* NOTE: The node_table_ Must be initialized correctly here! */
static nd_table_t nd_table_ = {.node=NULL, .node_count=0, .free_node_count=0};
/**************************************************************/
/**************************************************************/
/**** ****/
/**** ****/
/**** Local Utility functions... ****/
/**** ****/
/**** ****/
/**************************************************************/
/**************************************************************/
#define min(a,b) ((a<b)?a:b)
#define max(a,b) ((a>b)?a:b)
/************************************/
/** **/
/** Configure socket for Modbus **/
/** **/
/************************************/
static int configure_socket(int socket_id) {
/* configure the socket */
/* Set it to be non-blocking. This is safe because we always use select() before reading from it!
* It is also required for the connect() call. The default timeout in the TCP stack is much too long
* (typically blocks for 128 s ??) when the connect does not succedd imediately!
*/
if (fcntl(socket_id, F_SETFL, O_NONBLOCK) < 0) {
#ifdef ERRMSG
perror("fcntl()");
fprintf(stderr, ERRMSG_HEAD "Error configuring socket 'non-blocking' option.\n");
#endif
return -1;
}
/* configure the socket */
{
int optval;
socklen_t optlen = sizeof(optval);
optval = 1;
if(setsockopt(socket_id, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) {
#ifdef ERRMSG
perror("setsockopt()");
fprintf(stderr, ERRMSG_HEAD "Error configuring socket 'KeepAlive' option.\n");
#endif
return -1;
}
}
/* set the TCP no delay flag. */
{int bool_opt = 1;
if (setsockopt(socket_id, SOL_TCP, TCP_NODELAY,
(const void *)&bool_opt, sizeof(bool_opt))
< 0) {
#ifdef ERRMSG
perror("setsockopt()");
fprintf(stderr, ERRMSG_HEAD "Error configuring socket 'TCP no delay' option.\n");
#endif
return -1;
}
}
/* set the IP low delay option. */
{int priority_opt = IPTOS_LOWDELAY;
if (setsockopt(socket_id, SOL_IP, IP_TOS,
(const void *)&priority_opt, sizeof(priority_opt))
< 0) {
#ifdef ERRMSG
perror("setsockopt()");
fprintf(stderr, ERRMSG_HEAD "Error configuring socket 'IP low delay' option.\n");
#endif
return -1;
}
}
#if 0
/* send buffer */
/* NOTE: For slave devices, that may be receiving multiple
* requests before they have a chance to reply to the first,
* it probably is a good idea to have a large receive buffer.
* So it is best to leave it with the default configuration, as it is
* larger than the largest Modbus TCP frame.
*
* For the send buffer, a smaller buffer should suffice.
* However, it probably does not make sense to
* waste time asking for a smaller buffer, since the larger
* default buffer has already been allocated (the socket has already
* been created!)
*
* We might just as well leave out the configuration of the socket
* buffer size...
*/
#define SOCK_BUF_SIZE 300 /* The size proposed in the Modbus TCP spec. */
{int sock_buf_size;
sock_buf_size = SOCK_BUF_SIZE;
if (setsockopt(socket_id, SOL_SOCKET, SO_SNDBUF,
(const void *)&sock_buf_size, sizeof(sock_buf_size))
< 0)
return -1;
/* recv buffer */
sock_buf_size = SOCK_BUF_SIZE;
if (setsockopt(socket_id, SOL_SOCKET, SO_RCVBUF,
(const void *)&sock_buf_size, sizeof(sock_buf_size))
< 0)
return -1;
}
#endif
return 0;
}
/************************************/
/** **/
/** Connect socket to remote host **/
/** **/
/************************************/
/* This function will create a new socket, and connect it to a remote host... */
static inline int open_connection(int nd, const struct timespec *timeout) {
int socket_id, con_res;
#ifdef DEBUG
printf("[%lu] open_connection(): called, nd = %d\n", pthread_self(), nd);
#endif
if (nd_table_.node[nd].fd >= 0)
/* nd already connected) */
return nd_table_.node[nd].fd;
if (nd_table_.node[nd].addr.sin_family != AF_INET)
/* invalid remote address, or invalid nd */
return -1;
/* lets try to connect... */
/* create the socket */
if ((socket_id = socket(PF_INET, DEF_TYPE, 0 /* protocol_num */)) < 0) {
#ifdef DEBUG
perror("socket()");
fprintf(stderr, "[%lu] Error creating socket\n", pthread_self());
#endif
#ifdef ERRMSG
perror("socket()");
fprintf(stderr, ERRMSG_HEAD "Error creating socket\n");
#endif
return -1;
}
/* configure the socket - includes setting non-blocking option! */
if (configure_socket(socket_id) < 0) {
close(socket_id);
return -1;
};
/* establish the connection to remote host */
con_res = connect(socket_id,
(struct sockaddr *)&(nd_table_.node[nd].addr),
sizeof(nd_table_.node[nd].addr));
/* The following condition is not strictly necessary
* (we could let the code fall through)
* but it does make the code easier to read/understand...
*/
if (con_res >= 0)
goto success_exit; /* connected succesfully on first try! */
if (con_res < 0) {
if ((errno != EINPROGRESS) && (errno != EALREADY))
goto error_exit; /* error in connection request! */
/* connection request is ongoing */
/* EINPROGRESS -> first call to connect, EALREADY -> subsequent calls to connect */
/* Must wait for connect to complete at most 'timeout' seconds */
{fd_set fdset;
int res, so_error;
socklen_t len;
struct timespec end_time, *et_ptr;
et_ptr = NULL;
if (timeout != NULL) {
et_ptr = &end_time;
*et_ptr = timespec_add_curtime(*timeout);
}
FD_ZERO(&fdset);
FD_SET(socket_id, &fdset);
res = my_select(socket_id+1, NULL, &fdset, et_ptr);
if (res < 0) goto error_exit; /* error on call to select */
if (res == 0) goto error_exit; /* timeout */
/* (res > 0) -> connection attemt completed. May have been success or failure! */
len = sizeof(so_error);
res = getsockopt(socket_id, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (res < 0) goto error_exit; /* error on call to getsockopt */
if (so_error != 0) goto error_exit; /* error on connection attempt */
goto success_exit; /* succesfully completed connection attempt! */
/* goto sucess_exit is not strcitly necessary - we could let the code fall through! */
}
}
success_exit:
nd_table_.node[nd].fd = socket_id;
/* Succesfully established connection => print a message next time we have error. */
nd_table_.node[nd].print_connect_error = 1;
#ifdef DEBUG
printf("[%lu] open_connection(): returning...\n", pthread_self());
#endif
return socket_id;
error_exit:
#ifdef ERRMSG
if (nd_table_.node[nd].print_connect_error > 0) {
perror("connect()");
fprintf(stderr, ERRMSG_HEAD "Error establishing socket connection.\n");
/* do not print more error messages for this node... */
nd_table_.node[nd].print_connect_error = 0;
}
#endif
close(socket_id);
return -1;
}
/* This function will accept a new connection request, and attribute it to a new node... */
static inline int accept_connection(int nd) {
int socket_id, new_nd;
#ifdef DEBUG
printf("[%lu] accept_connection(): called, nd = %d\n", pthread_self(), nd);
#endif
/* NOTE: We MUST accccept8) all connection requests, even if no new node is available.
* => We first accept the connection request, and only later look for a node.
* If no node is free/available for this new connections request, the
* connection will be accepted and immediately closed.
* Reason:
* When the library is used for a Modbus/TCP server and no free node is
* available, if we do not accept() all newly arrived connection requests
* we would enter an infinite loop calling
* - select() (in modbus_tcp_read())
* - and accept_connection().
* Note that select() will continue to return immediately if the
* connection request is not accept()ted!
*/
/* lets accept new connection request... */
if ((socket_id = accept(nd_table_.node[nd].fd, NULL, NULL)) < 0) {
#ifdef ERRMSG
perror("accept()");
fprintf(stderr, ERRMSG_HEAD "Error while waiting for connection request from new client\n");
#endif
/* error establishing new connection... */
return -1;
}
/* find a free node */
if ((new_nd = nd_table_get_free_node(&nd_table_, MB_SLAVE_NODE)) < 0) {
/* no available free nodes for the new connection... */
close(socket_id);
return -1;
}
/* configure the socket - includes setting the non-blocking option! */
if (configure_socket(socket_id) < 0) {
nd_table_close_node(&nd_table_, new_nd); /* first free up the un-used node. */
close(socket_id);
return -1;
}
/* set up the node entry and update the fd sets */
nd_table_.node[new_nd].fd = socket_id;
nd_table_.node[new_nd].listen_node = nd;
#ifdef DEBUG
printf("[%lu] accept_connection(): returning new_nd = %d\n", pthread_self(), new_nd);
#endif
return new_nd;
}
static inline void close_connection(int nd) {
if (nd_table_.node[nd].fd >= 0) {
/* disconnect the tcp connection */
shutdown(nd_table_.node[nd].fd, SHUT_RDWR);
#ifdef ERRMSG
int res =
#endif
close(nd_table_.node[nd].fd);
#ifdef ERRMSG
if (res < 0) {
perror("close()");
fprintf(stderr, ERRMSG_HEAD "Error closing socket\n");
}
#endif
nd_table_.node[nd].fd = -1;
}
if (nd_table_.node[nd].node_type == MB_SLAVE_NODE) {
/* If it is a slave node, we will not be receiving any more data over this disconnected node,
* (MB_SLAVE_NODE do not get re-connected!), so we free the node...
*/
nd_table_close_node(&nd_table_, nd);
}
}
/************************************/
/** **/
/** Data format conversion **/
/** **/
/************************************/
/*
* Functions to convert u16 variables
* between network and host byte order
*
* NOTE: Modbus uses MSByte first, just like
* tcp/ip, so we use the htons() and
* ntoh() functions to guarantee
* code portability.
*/
static inline u16 mb_hton(u16 h_value) {
/* return h_value; */
return htons(h_value);
}
static inline u16 mb_ntoh(u16 m_value) {
/* return m_value; */
return ntohs(m_value);
}
static inline u8 msb(u16 value) {
/* return Most Significant Byte of value; */
return (value >> 8) & 0xFF;
}
static inline u8 lsb(u16 value) {
/* return Least Significant Byte of value; */
return value & 0xFF;
}
#define u16_v(char_ptr) (*((u16 *)(&(char_ptr))))
/************************************/
/** **/
/** Build/Check a frame header **/
/** **/
/************************************/
/* A modbus TCP frame header has 6 bytes...
* header[0-1] -> transaction id
* header[2-3] -> must be 0
* header[4-5] -> frame data length (must be <= 255)
*/
#if TCP_HEADER_LENGTH < 6
#error This code assumes a header size of 6 bytes, but TCP_HEADER_LENGTH < 6
#endif
static inline void build_header(u8 *header,
u16 transaction_id,
u16 byte_count)
{
u16_v(header[0]) = mb_hton(transaction_id);
header[2] = 0;
header[3] = 0;
u16_v(header[4]) = mb_hton(byte_count);
}
static inline int check_header(u8 *header,
u16 *transaction_id,
u16 *byte_count)
{
if ((header[2] != 0) || (header[3] != 0))
return -1;
*transaction_id = mb_ntoh(*(u16 *)(header + 0));
*byte_count = mb_ntoh(*(u16 *)(header + 4));
if (*byte_count > MAX_L2_FRAME_LENGTH)
return -1;
return 0;
}
/**************************************************************/
/**************************************************************/
/**** ****/
/**** ****/
/**** Sending of Modbus TCP Frames ****/
/**** ****/
/**** ****/
/**************************************************************/
/**************************************************************/
// pthread_mutex_t sendmsg_mutex = PTHREAD_MUTEX_INITIALIZER;
/* NOTE: this function MUST be thread safe!! */
int modbus_tcp_write(int nd, /* node descriptor */
u8 *data,
size_t data_length,
u16 transaction_id,
const struct timespec *transmit_timeout
)
{
#define data_vector_size 2
u8 header[TCP_HEADER_LENGTH];
struct iovec data_vector[data_vector_size] = {
{(void *)header, TCP_HEADER_LENGTH},
{NULL, 0}};
struct msghdr msg = {NULL, 0, data_vector, data_vector_size, NULL, 0, 0};
int res, bytes_sent;
#ifdef DEBUG
printf("[%lu] modbus_tcp_write(): called... nd=%d\n", pthread_self(), nd);
#endif
if ((nd >= nd_table_.node_count) || (nd < 0))
/* invalid node descriptor... */
return -1;
#ifdef DEBUG
// printf("[%lu] locking mutex...\n", pthread_self());
#endif
// while (pthread_mutex_lock(&sendmsg_mutex) != 0);
/*************************
* prepare the header... *
*************************/
build_header(header, transaction_id, data_length);
#ifdef DEBUG
/* Print the hex value of each character that is about to be
* sent over the bus.
*/
{ int i;
printf("modbus_tcp_write(): sending data...\n");
for(i = 0; i < TCP_HEADER_LENGTH; i++)
printf("[0x%2X]", header[i]);
for(i = 0; i < data_length; i++)
printf("[0x%2X]", data[i]);
printf("\n");
}
#endif
/******************************************
* do we need to re-establish connection? *
******************************************/
if (open_connection(nd, transmit_timeout) < 0) {
#ifdef DEBUG
fprintf(stderr, "[%lu] modbus_tcp_write(): could not establish connection...\n", pthread_self());
#endif
#ifdef ERRMSG
fprintf(stderr, ERRMSG_HEAD "could not establish connection...\n");
#endif
return -1;
}
/**********************
* write to output... *
**********************/
/* TWO ALTERNATIVE IMPLEMENTATIONS !!! */
#if 0
/* write header */
bytes_sent = 0;
while (1) {
res = write(nd_table_.node[nd].fd, header+bytes_sent, TCP_HEADER_LENGTH-bytes_sent);
if (res < 0) {
if ((errno != EAGAIN ) && (errno != EINTR )) {
/* error sending message... */
close_connection(nd);
return -1;
} else {
continue;
}
} else {
/* res >= 0 */
bytes_sent += res;
if (bytes_sent >= TCP_HEADER_LENGTH) {
break;
}
}
}
/* write data */
bytes_sent = 0;
while (1) {
res = write(nd_table_.node[nd].fd, data+bytes_sent, data_length-bytes_sent);
if (res < 0) {
if ((errno != EAGAIN ) && (errno != EINTR )) {
/* error sending message... */
close_connection(nd);
return -1;
} else {
continue;
}
} else {
/* res >= 0 */
bytes_sent += res;
if (bytes_sent >= data_length) {
/* query succesfully sent! */
#ifdef DEBUG
printf("[%lu] modbus_tcp_write(): sent %d bytes\n", pthread_self(), TCP_HEADER_LENGTH+data_length);
#endif
return data_length;
}
}
}
/**********************
* write to output... *
**********************/
#else
/* We are optimising for the most likely case, and in doing that
* we are making the least likely case have worse behaviour!
* Read on for an explanation...
*
* - The optimised behaviour for the most likely case:
* We have set the NO_DELAY flag on the socket, so the IP datagram
* is not delayed and is therefore sent as soon as any data is written to
* the socket.
* In order to send the whole message in a single IP datagram, we have to
* write both the the header and the data with a single call to write()
* In order to not to have to copy the data around just to add the
* message header, we use sendmsg() instead of write()!
*
* - The worse behaviour for the least likely case:
* If for some reason only part of the data is sent with the first call to
* write(), a datagram is sent right away, and the subsequent data will
* be sent in another datagram. :-(
*/
/* NOTE: since snedmsg() is not thread safe, we use a mutex to protect access to this function... */
data_vector[data_vector_size - 1].iov_base = data;
data_vector[data_vector_size - 1].iov_len = data_length;
data_vector[ 0].iov_base = header;
data_vector[ 0].iov_len = TCP_HEADER_LENGTH;
bytes_sent = 0;
while (1) {
int sendmsg_errno;
/* Please see the comment just above the main loop!! */
res = sendmsg(nd_table_.node[nd].fd, &msg, 0);
sendmsg_errno = errno;
if (res < 0) {
if ((sendmsg_errno != EAGAIN ) && (sendmsg_errno != EINTR )) {
/* error sending message... */
close_connection(nd);
return -1;
} else {
continue;
}
} else {
/* res >= 0 */
bytes_sent += res;
if (bytes_sent >= data_length + TCP_HEADER_LENGTH) {
/* query succesfully sent! */
#ifdef DEBUG
printf("[%lu] modbus_tcp_write(): sent %d bytes\n", pthread_self(), bytes_sent);
#endif
// pthread_mutex_unlock(&sendmsg_mutex);