modbus-tcp.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. /*
  2. * Copyright © 2001-2013 Stéphane Raimbault <stephane.raimbault@gmail.com>
  3. *
  4. * SPDX-License-Identifier: LGPL-2.1+
  5. */
  6. #if defined(_WIN32)
  7. # define OS_WIN32
  8. /* ws2_32.dll has getaddrinfo and freeaddrinfo on Windows XP and later.
  9. * minwg32 headers check WINVER before allowing the use of these */
  10. # ifndef WINVER
  11. # define WINVER 0x0501
  12. # endif
  13. #endif
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <errno.h>
  18. #ifndef _MSC_VER
  19. #include <unistd.h>
  20. #endif
  21. #include <signal.h>
  22. #include <sys/types.h>
  23. #if defined(_WIN32)
  24. /* Already set in modbus-tcp.h but it seems order matters in VS2005 */
  25. # include <winsock2.h>
  26. # include <ws2tcpip.h>
  27. # define SHUT_RDWR 2
  28. # define close closesocket
  29. #else
  30. # include <sys/socket.h>
  31. # include <sys/ioctl.h>
  32. #if defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ < 5)
  33. # define OS_BSD
  34. # include <netinet/in_systm.h>
  35. #endif
  36. # include <netinet/in.h>
  37. # include <netinet/ip.h>
  38. # include <netinet/tcp.h>
  39. # include <arpa/inet.h>
  40. # include <netdb.h>
  41. #endif
  42. #if !defined(MSG_NOSIGNAL)
  43. #define MSG_NOSIGNAL 0
  44. #endif
  45. #if defined(_AIX) && !defined(MSG_DONTWAIT)
  46. #define MSG_DONTWAIT MSG_NONBLOCK
  47. #endif
  48. #include "modbus-private.h"
  49. #include "modbus-tcp.h"
  50. #include "modbus-tcp-private.h"
  51. #ifdef OS_WIN32
  52. static int _modbus_tcp_init_win32(void)
  53. {
  54. /* Initialise Windows Socket API */
  55. WSADATA wsaData;
  56. if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
  57. fprintf(stderr, "WSAStartup() returned error code %d\n",
  58. (unsigned int)GetLastError());
  59. errno = EIO;
  60. return -1;
  61. }
  62. return 0;
  63. }
  64. #endif
  65. static int _modbus_set_slave(modbus_t *ctx, int slave)
  66. {
  67. /* Broadcast address is 0 (MODBUS_BROADCAST_ADDRESS) */
  68. if (slave >= 0 && slave <= 247) {
  69. ctx->slave = slave;
  70. } else if (slave == MODBUS_TCP_SLAVE) {
  71. /* The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to
  72. * restore the default value. */
  73. ctx->slave = slave;
  74. } else {
  75. errno = EINVAL;
  76. return -1;
  77. }
  78. return 0;
  79. }
  80. /* Builds a TCP request header */
  81. static int _modbus_tcp_build_request_basis(modbus_t *ctx, int function,
  82. int addr, int nb,
  83. uint8_t *req)
  84. {
  85. modbus_tcp_t *ctx_tcp = ctx->backend_data;
  86. /* Increase transaction ID */
  87. if (ctx_tcp->t_id < UINT16_MAX)
  88. ctx_tcp->t_id++;
  89. else
  90. ctx_tcp->t_id = 0;
  91. req[0] = ctx_tcp->t_id >> 8;
  92. req[1] = ctx_tcp->t_id & 0x00ff;
  93. /* Protocol Modbus */
  94. req[2] = 0;
  95. req[3] = 0;
  96. /* Length will be defined later by set_req_length_tcp at offsets 4
  97. and 5 */
  98. req[6] = ctx->slave;
  99. req[7] = function;
  100. req[8] = addr >> 8;
  101. req[9] = addr & 0x00ff;
  102. req[10] = nb >> 8;
  103. req[11] = nb & 0x00ff;
  104. return _MODBUS_TCP_PRESET_REQ_LENGTH;
  105. }
  106. /* Builds a TCP response header */
  107. static int _modbus_tcp_build_response_basis(sft_t *sft, uint8_t *rsp)
  108. {
  109. /* Extract from MODBUS Messaging on TCP/IP Implementation
  110. Guide V1.0b (page 23/46):
  111. The transaction identifier is used to associate the future
  112. response with the request. */
  113. rsp[0] = sft->t_id >> 8;
  114. rsp[1] = sft->t_id & 0x00ff;
  115. /* Protocol Modbus */
  116. rsp[2] = 0;
  117. rsp[3] = 0;
  118. /* Length will be set later by send_msg (4 and 5) */
  119. /* The slave ID is copied from the indication */
  120. rsp[6] = sft->slave;
  121. rsp[7] = sft->function;
  122. return _MODBUS_TCP_PRESET_RSP_LENGTH;
  123. }
  124. static int _modbus_tcp_prepare_response_tid(const uint8_t *req, int *req_length)
  125. {
  126. return (req[0] << 8) + req[1];
  127. }
  128. static int _modbus_tcp_send_msg_pre(uint8_t *req, int req_length)
  129. {
  130. /* Substract the header length to the message length */
  131. int mbap_length = req_length - 6;
  132. req[4] = mbap_length >> 8;
  133. req[5] = mbap_length & 0x00FF;
  134. return req_length;
  135. }
  136. static ssize_t _modbus_tcp_send(modbus_t *ctx, const uint8_t *req, int req_length)
  137. {
  138. /* MSG_NOSIGNAL
  139. Requests not to send SIGPIPE on errors on stream oriented
  140. sockets when the other end breaks the connection. The EPIPE
  141. error is still returned. */
  142. return send(ctx->s, (const char *)req, req_length, MSG_NOSIGNAL);
  143. }
  144. static int _modbus_tcp_receive(modbus_t *ctx, uint8_t *req) {
  145. return _modbus_receive_msg(ctx, req, MSG_INDICATION);
  146. }
  147. static ssize_t _modbus_tcp_recv(modbus_t *ctx, uint8_t *rsp, int rsp_length) {
  148. return recv(ctx->s, (char *)rsp, rsp_length, 0);
  149. }
  150. static int _modbus_tcp_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length)
  151. {
  152. return msg_length;
  153. }
  154. static int _modbus_tcp_pre_check_confirmation(modbus_t *ctx, const uint8_t *req,
  155. const uint8_t *rsp, int rsp_length)
  156. {
  157. /* Check transaction ID */
  158. if (req[0] != rsp[0] || req[1] != rsp[1]) {
  159. if (ctx->debug) {
  160. fprintf(stderr, "Invalid transaction ID received 0x%X (not 0x%X)\n",
  161. (rsp[0] << 8) + rsp[1], (req[0] << 8) + req[1]);
  162. }
  163. errno = EMBBADDATA;
  164. return -1;
  165. }
  166. /* Check protocol ID */
  167. if (rsp[2] != 0x0 && rsp[3] != 0x0) {
  168. if (ctx->debug) {
  169. fprintf(stderr, "Invalid protocol ID received 0x%X (not 0x0)\n",
  170. (rsp[2] << 8) + rsp[3]);
  171. }
  172. errno = EMBBADDATA;
  173. return -1;
  174. }
  175. return 0;
  176. }
  177. static int _modbus_tcp_set_ipv4_options(int s)
  178. {
  179. int rc;
  180. int option;
  181. /* Set the TCP no delay flag */
  182. /* SOL_TCP = IPPROTO_TCP */
  183. option = 1;
  184. rc = setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
  185. (const void *)&option, sizeof(int));
  186. if (rc == -1) {
  187. return -1;
  188. }
  189. /* If the OS does not offer SOCK_NONBLOCK, fall back to setting FIONBIO to
  190. * make sockets non-blocking */
  191. /* Do not care about the return value, this is optional */
  192. #if !defined(SOCK_NONBLOCK) && defined(FIONBIO)
  193. #ifdef OS_WIN32
  194. {
  195. /* Setting FIONBIO expects an unsigned long according to MSDN */
  196. u_long loption = 1;
  197. ioctlsocket(s, FIONBIO, &loption);
  198. }
  199. #else
  200. option = 1;
  201. ioctl(s, FIONBIO, &option);
  202. #endif
  203. #endif
  204. #ifndef OS_WIN32
  205. /**
  206. * Cygwin defines IPTOS_LOWDELAY but can't handle that flag so it's
  207. * necessary to workaround that problem.
  208. **/
  209. /* Set the IP low delay option */
  210. option = IPTOS_LOWDELAY;
  211. rc = setsockopt(s, IPPROTO_IP, IP_TOS,
  212. (const void *)&option, sizeof(int));
  213. if (rc == -1) {
  214. return -1;
  215. }
  216. #endif
  217. return 0;
  218. }
  219. static int _connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen,
  220. const struct timeval *ro_tv)
  221. {
  222. int rc = connect(sockfd, addr, addrlen);
  223. #ifdef OS_WIN32
  224. int wsaError = 0;
  225. if (rc == -1) {
  226. wsaError = WSAGetLastError();
  227. }
  228. if (wsaError == WSAEWOULDBLOCK || wsaError == WSAEINPROGRESS) {
  229. #else
  230. if (rc == -1 && errno == EINPROGRESS) {
  231. #endif
  232. fd_set wset;
  233. int optval;
  234. socklen_t optlen = sizeof(optval);
  235. struct timeval tv = *ro_tv;
  236. /* Wait to be available in writing */
  237. FD_ZERO(&wset);
  238. FD_SET(sockfd, &wset);
  239. rc = select(sockfd + 1, NULL, &wset, NULL, &tv);
  240. if (rc <= 0) {
  241. /* Timeout or fail */
  242. return -1;
  243. }
  244. /* The connection is established if SO_ERROR and optval are set to 0 */
  245. rc = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&optval, &optlen);
  246. if (rc == 0 && optval == 0) {
  247. return 0;
  248. } else {
  249. errno = ECONNREFUSED;
  250. return -1;
  251. }
  252. }
  253. return rc;
  254. }
  255. /* Establishes a modbus TCP connection with a Modbus server. */
  256. static int _modbus_tcp_connect(modbus_t *ctx)
  257. {
  258. int rc;
  259. /* Specialized version of sockaddr for Internet socket address (same size) */
  260. struct sockaddr_in addr;
  261. modbus_tcp_t *ctx_tcp = ctx->backend_data;
  262. int flags = SOCK_STREAM;
  263. #ifdef OS_WIN32
  264. if (_modbus_tcp_init_win32() == -1) {
  265. return -1;
  266. }
  267. #endif
  268. #ifdef SOCK_CLOEXEC
  269. flags |= SOCK_CLOEXEC;
  270. #endif
  271. #ifdef SOCK_NONBLOCK
  272. flags |= SOCK_NONBLOCK;
  273. #endif
  274. ctx->s = socket(PF_INET, flags, 0);
  275. if (ctx->s == -1) {
  276. return -1;
  277. }
  278. rc = _modbus_tcp_set_ipv4_options(ctx->s);
  279. if (rc == -1) {
  280. close(ctx->s);
  281. ctx->s = -1;
  282. return -1;
  283. }
  284. if (ctx->debug) {
  285. printf("Connecting to %s:%d\n", ctx_tcp->ip, ctx_tcp->port);
  286. }
  287. addr.sin_family = AF_INET;
  288. addr.sin_port = htons(ctx_tcp->port);
  289. addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip);
  290. rc = _connect(ctx->s, (struct sockaddr *)&addr, sizeof(addr), &ctx->response_timeout);
  291. if (rc == -1) {
  292. close(ctx->s);
  293. ctx->s = -1;
  294. return -1;
  295. }
  296. return 0;
  297. }
  298. /* Establishes a modbus TCP PI connection with a Modbus server. */
  299. static int _modbus_tcp_pi_connect(modbus_t *ctx)
  300. {
  301. int rc;
  302. struct addrinfo *ai_list;
  303. struct addrinfo *ai_ptr;
  304. struct addrinfo ai_hints;
  305. modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
  306. #ifdef OS_WIN32
  307. if (_modbus_tcp_init_win32() == -1) {
  308. return -1;
  309. }
  310. #endif
  311. memset(&ai_hints, 0, sizeof(ai_hints));
  312. #ifdef AI_ADDRCONFIG
  313. ai_hints.ai_flags |= AI_ADDRCONFIG;
  314. #endif
  315. ai_hints.ai_family = AF_UNSPEC;
  316. ai_hints.ai_socktype = SOCK_STREAM;
  317. ai_hints.ai_addr = NULL;
  318. ai_hints.ai_canonname = NULL;
  319. ai_hints.ai_next = NULL;
  320. ai_list = NULL;
  321. rc = getaddrinfo(ctx_tcp_pi->node, ctx_tcp_pi->service,
  322. &ai_hints, &ai_list);
  323. if (rc != 0) {
  324. if (ctx->debug) {
  325. fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
  326. }
  327. errno = ECONNREFUSED;
  328. return -1;
  329. }
  330. for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
  331. int flags = ai_ptr->ai_socktype;
  332. int s;
  333. #ifdef SOCK_CLOEXEC
  334. flags |= SOCK_CLOEXEC;
  335. #endif
  336. #ifdef SOCK_NONBLOCK
  337. flags |= SOCK_NONBLOCK;
  338. #endif
  339. s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
  340. if (s < 0)
  341. continue;
  342. if (ai_ptr->ai_family == AF_INET)
  343. _modbus_tcp_set_ipv4_options(s);
  344. if (ctx->debug) {
  345. printf("Connecting to [%s]:%s\n", ctx_tcp_pi->node, ctx_tcp_pi->service);
  346. }
  347. rc = _connect(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen, &ctx->response_timeout);
  348. if (rc == -1) {
  349. close(s);
  350. continue;
  351. }
  352. ctx->s = s;
  353. break;
  354. }
  355. freeaddrinfo(ai_list);
  356. if (ctx->s < 0) {
  357. return -1;
  358. }
  359. return 0;
  360. }
  361. /* Closes the network connection and socket in TCP mode */
  362. static void _modbus_tcp_close(modbus_t *ctx)
  363. {
  364. if (ctx->s != -1) {
  365. shutdown(ctx->s, SHUT_RDWR);
  366. close(ctx->s);
  367. ctx->s = -1;
  368. }
  369. }
  370. static int _modbus_tcp_flush(modbus_t *ctx)
  371. {
  372. int rc;
  373. int rc_sum = 0;
  374. do {
  375. /* Extract the garbage from the socket */
  376. char devnull[MODBUS_TCP_MAX_ADU_LENGTH];
  377. #ifndef OS_WIN32
  378. rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, MSG_DONTWAIT);
  379. #else
  380. /* On Win32, it's a bit more complicated to not wait */
  381. fd_set rset;
  382. struct timeval tv;
  383. tv.tv_sec = 0;
  384. tv.tv_usec = 0;
  385. FD_ZERO(&rset);
  386. FD_SET(ctx->s, &rset);
  387. rc = select(ctx->s+1, &rset, NULL, NULL, &tv);
  388. if (rc == -1) {
  389. return -1;
  390. }
  391. if (rc == 1) {
  392. /* There is data to flush */
  393. rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, 0);
  394. }
  395. #endif
  396. if (rc > 0) {
  397. rc_sum += rc;
  398. }
  399. } while (rc == MODBUS_TCP_MAX_ADU_LENGTH);
  400. return rc_sum;
  401. }
  402. /* Listens for any request from one or many modbus masters in TCP */
  403. int modbus_tcp_listen(modbus_t *ctx, int nb_connection)
  404. {
  405. int new_s;
  406. int enable;
  407. struct sockaddr_in addr;
  408. modbus_tcp_t *ctx_tcp;
  409. if (ctx == NULL) {
  410. errno = EINVAL;
  411. return -1;
  412. }
  413. ctx_tcp = ctx->backend_data;
  414. #ifdef OS_WIN32
  415. if (_modbus_tcp_init_win32() == -1) {
  416. return -1;
  417. }
  418. #endif
  419. new_s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  420. if (new_s == -1) {
  421. return -1;
  422. }
  423. enable = 1;
  424. if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR,
  425. (char *)&enable, sizeof(enable)) == -1) {
  426. close(new_s);
  427. return -1;
  428. }
  429. memset(&addr, 0, sizeof(addr));
  430. addr.sin_family = AF_INET;
  431. /* If the modbus port is < to 1024, we need the setuid root. */
  432. addr.sin_port = htons(ctx_tcp->port);
  433. if (ctx_tcp->ip[0] == '0') {
  434. /* Listen any addresses */
  435. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  436. } else {
  437. /* Listen only specified IP address */
  438. addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip);
  439. }
  440. if (bind(new_s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
  441. close(new_s);
  442. return -1;
  443. }
  444. if (listen(new_s, nb_connection) == -1) {
  445. close(new_s);
  446. return -1;
  447. }
  448. return new_s;
  449. }
  450. int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection)
  451. {
  452. int rc;
  453. struct addrinfo *ai_list;
  454. struct addrinfo *ai_ptr;
  455. struct addrinfo ai_hints;
  456. const char *node;
  457. const char *service;
  458. int new_s;
  459. modbus_tcp_pi_t *ctx_tcp_pi;
  460. if (ctx == NULL) {
  461. errno = EINVAL;
  462. return -1;
  463. }
  464. ctx_tcp_pi = ctx->backend_data;
  465. #ifdef OS_WIN32
  466. if (_modbus_tcp_init_win32() == -1) {
  467. return -1;
  468. }
  469. #endif
  470. if (ctx_tcp_pi->node[0] == 0) {
  471. node = NULL; /* == any */
  472. } else {
  473. node = ctx_tcp_pi->node;
  474. }
  475. if (ctx_tcp_pi->service[0] == 0) {
  476. service = "502";
  477. } else {
  478. service = ctx_tcp_pi->service;
  479. }
  480. memset(&ai_hints, 0, sizeof (ai_hints));
  481. /* If node is not NULL, than the AI_PASSIVE flag is ignored. */
  482. ai_hints.ai_flags |= AI_PASSIVE;
  483. #ifdef AI_ADDRCONFIG
  484. ai_hints.ai_flags |= AI_ADDRCONFIG;
  485. #endif
  486. ai_hints.ai_family = AF_UNSPEC;
  487. ai_hints.ai_socktype = SOCK_STREAM;
  488. ai_hints.ai_addr = NULL;
  489. ai_hints.ai_canonname = NULL;
  490. ai_hints.ai_next = NULL;
  491. ai_list = NULL;
  492. rc = getaddrinfo(node, service, &ai_hints, &ai_list);
  493. if (rc != 0) {
  494. if (ctx->debug) {
  495. fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
  496. }
  497. errno = ECONNREFUSED;
  498. return -1;
  499. }
  500. new_s = -1;
  501. for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
  502. int s;
  503. s = socket(ai_ptr->ai_family, ai_ptr->ai_socktype,
  504. ai_ptr->ai_protocol);
  505. if (s < 0) {
  506. if (ctx->debug) {
  507. perror("socket");
  508. }
  509. continue;
  510. } else {
  511. int enable = 1;
  512. rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
  513. (void *)&enable, sizeof (enable));
  514. if (rc != 0) {
  515. close(s);
  516. if (ctx->debug) {
  517. perror("setsockopt");
  518. }
  519. continue;
  520. }
  521. }
  522. rc = bind(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
  523. if (rc != 0) {
  524. close(s);
  525. if (ctx->debug) {
  526. perror("bind");
  527. }
  528. continue;
  529. }
  530. rc = listen(s, nb_connection);
  531. if (rc != 0) {
  532. close(s);
  533. if (ctx->debug) {
  534. perror("listen");
  535. }
  536. continue;
  537. }
  538. new_s = s;
  539. break;
  540. }
  541. freeaddrinfo(ai_list);
  542. if (new_s < 0) {
  543. return -1;
  544. }
  545. return new_s;
  546. }
  547. int modbus_tcp_accept(modbus_t *ctx, int *s)
  548. {
  549. struct sockaddr_in addr;
  550. socklen_t addrlen;
  551. if (ctx == NULL) {
  552. errno = EINVAL;
  553. return -1;
  554. }
  555. addrlen = sizeof(addr);
  556. #ifdef HAVE_ACCEPT4
  557. /* Inherit socket flags and use accept4 call */
  558. ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
  559. #else
  560. ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
  561. #endif
  562. if (ctx->s == -1) {
  563. return -1;
  564. }
  565. if (ctx->debug) {
  566. printf("The client connection from %s is accepted\n",
  567. inet_ntoa(addr.sin_addr));
  568. }
  569. return ctx->s;
  570. }
  571. int modbus_tcp_pi_accept(modbus_t *ctx, int *s)
  572. {
  573. struct sockaddr_storage addr;
  574. socklen_t addrlen;
  575. if (ctx == NULL) {
  576. errno = EINVAL;
  577. return -1;
  578. }
  579. addrlen = sizeof(addr);
  580. #ifdef HAVE_ACCEPT4
  581. /* Inherit socket flags and use accept4 call */
  582. ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
  583. #else
  584. ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
  585. #endif
  586. if (ctx->s == -1) {
  587. return -1;
  588. }
  589. if (ctx->debug) {
  590. printf("The client connection is accepted.\n");
  591. }
  592. return ctx->s;
  593. }
  594. static int _modbus_tcp_select(modbus_t *ctx, fd_set *rset, struct timeval *tv, int length_to_read)
  595. {
  596. int s_rc;
  597. while ((s_rc = select(ctx->s+1, rset, NULL, NULL, tv)) == -1) {
  598. if (errno == EINTR) {
  599. if (ctx->debug) {
  600. fprintf(stderr, "A non blocked signal was caught\n");
  601. }
  602. /* Necessary after an error */
  603. FD_ZERO(rset);
  604. FD_SET(ctx->s, rset);
  605. } else {
  606. return -1;
  607. }
  608. }
  609. if (s_rc == 0) {
  610. errno = ETIMEDOUT;
  611. return -1;
  612. }
  613. return s_rc;
  614. }
  615. static void _modbus_tcp_free(modbus_t *ctx) {
  616. free(ctx->backend_data);
  617. free(ctx);
  618. }
  619. const modbus_backend_t _modbus_tcp_backend = {
  620. _MODBUS_BACKEND_TYPE_TCP,
  621. _MODBUS_TCP_HEADER_LENGTH,
  622. _MODBUS_TCP_CHECKSUM_LENGTH,
  623. MODBUS_TCP_MAX_ADU_LENGTH,
  624. _modbus_set_slave,
  625. _modbus_tcp_build_request_basis,
  626. _modbus_tcp_build_response_basis,
  627. _modbus_tcp_prepare_response_tid,
  628. _modbus_tcp_send_msg_pre,
  629. _modbus_tcp_send,
  630. _modbus_tcp_receive,
  631. _modbus_tcp_recv,
  632. _modbus_tcp_check_integrity,
  633. _modbus_tcp_pre_check_confirmation,
  634. _modbus_tcp_connect,
  635. _modbus_tcp_close,
  636. _modbus_tcp_flush,
  637. _modbus_tcp_select,
  638. _modbus_tcp_free
  639. };
  640. const modbus_backend_t _modbus_tcp_pi_backend = {
  641. _MODBUS_BACKEND_TYPE_TCP,
  642. _MODBUS_TCP_HEADER_LENGTH,
  643. _MODBUS_TCP_CHECKSUM_LENGTH,
  644. MODBUS_TCP_MAX_ADU_LENGTH,
  645. _modbus_set_slave,
  646. _modbus_tcp_build_request_basis,
  647. _modbus_tcp_build_response_basis,
  648. _modbus_tcp_prepare_response_tid,
  649. _modbus_tcp_send_msg_pre,
  650. _modbus_tcp_send,
  651. _modbus_tcp_receive,
  652. _modbus_tcp_recv,
  653. _modbus_tcp_check_integrity,
  654. _modbus_tcp_pre_check_confirmation,
  655. _modbus_tcp_pi_connect,
  656. _modbus_tcp_close,
  657. _modbus_tcp_flush,
  658. _modbus_tcp_select,
  659. _modbus_tcp_free
  660. };
  661. modbus_t* modbus_new_tcp(const char *ip, int port)
  662. {
  663. modbus_t *ctx;
  664. modbus_tcp_t *ctx_tcp;
  665. size_t dest_size;
  666. size_t ret_size;
  667. #if defined(OS_BSD)
  668. /* MSG_NOSIGNAL is unsupported on *BSD so we install an ignore
  669. handler for SIGPIPE. */
  670. struct sigaction sa;
  671. sa.sa_handler = SIG_IGN;
  672. if (sigaction(SIGPIPE, &sa, NULL) < 0) {
  673. /* The debug flag can't be set here... */
  674. fprintf(stderr, "Coud not install SIGPIPE handler.\n");
  675. return NULL;
  676. }
  677. #endif
  678. ctx = (modbus_t *)malloc(sizeof(modbus_t));
  679. if (ctx == NULL) {
  680. return NULL;
  681. }
  682. _modbus_init_common(ctx);
  683. /* Could be changed after to reach a remote serial Modbus device */
  684. ctx->slave = MODBUS_TCP_SLAVE;
  685. ctx->backend = &_modbus_tcp_backend;
  686. ctx->backend_data = (modbus_tcp_t *)malloc(sizeof(modbus_tcp_t));
  687. if (ctx->backend_data == NULL) {
  688. modbus_free(ctx);
  689. errno = ENOMEM;
  690. return NULL;
  691. }
  692. ctx_tcp = (modbus_tcp_t *)ctx->backend_data;
  693. if (ip != NULL) {
  694. dest_size = sizeof(char) * 16;
  695. ret_size = strlcpy(ctx_tcp->ip, ip, dest_size);
  696. if (ret_size == 0) {
  697. fprintf(stderr, "The IP string is empty\n");
  698. modbus_free(ctx);
  699. errno = EINVAL;
  700. return NULL;
  701. }
  702. if (ret_size >= dest_size) {
  703. fprintf(stderr, "The IP string has been truncated\n");
  704. modbus_free(ctx);
  705. errno = EINVAL;
  706. return NULL;
  707. }
  708. } else {
  709. ctx_tcp->ip[0] = '0';
  710. }
  711. ctx_tcp->port = port;
  712. ctx_tcp->t_id = 0;
  713. return ctx;
  714. }
  715. modbus_t* modbus_new_tcp_pi(const char *node, const char *service)
  716. {
  717. modbus_t *ctx;
  718. modbus_tcp_pi_t *ctx_tcp_pi;
  719. size_t dest_size;
  720. size_t ret_size;
  721. ctx = (modbus_t *)malloc(sizeof(modbus_t));
  722. if (ctx == NULL) {
  723. return NULL;
  724. }
  725. _modbus_init_common(ctx);
  726. /* Could be changed after to reach a remote serial Modbus device */
  727. ctx->slave = MODBUS_TCP_SLAVE;
  728. ctx->backend = &_modbus_tcp_pi_backend;
  729. ctx->backend_data = (modbus_tcp_pi_t *)malloc(sizeof(modbus_tcp_pi_t));
  730. if (ctx->backend_data == NULL) {
  731. modbus_free(ctx);
  732. errno = ENOMEM;
  733. return NULL;
  734. }
  735. ctx_tcp_pi = (modbus_tcp_pi_t *)ctx->backend_data;
  736. if (node == NULL) {
  737. /* The node argument can be empty to indicate any hosts */
  738. ctx_tcp_pi->node[0] = 0;
  739. } else {
  740. dest_size = sizeof(char) * _MODBUS_TCP_PI_NODE_LENGTH;
  741. ret_size = strlcpy(ctx_tcp_pi->node, node, dest_size);
  742. if (ret_size == 0) {
  743. fprintf(stderr, "The node string is empty\n");
  744. modbus_free(ctx);
  745. errno = EINVAL;
  746. return NULL;
  747. }
  748. if (ret_size >= dest_size) {
  749. fprintf(stderr, "The node string has been truncated\n");
  750. modbus_free(ctx);
  751. errno = EINVAL;
  752. return NULL;
  753. }
  754. }
  755. if (service != NULL) {
  756. dest_size = sizeof(char) * _MODBUS_TCP_PI_SERVICE_LENGTH;
  757. ret_size = strlcpy(ctx_tcp_pi->service, service, dest_size);
  758. } else {
  759. /* Empty service is not allowed, error catched below. */
  760. ret_size = 0;
  761. }
  762. if (ret_size == 0) {
  763. fprintf(stderr, "The service string is empty\n");
  764. modbus_free(ctx);
  765. errno = EINVAL;
  766. return NULL;
  767. }
  768. if (ret_size >= dest_size) {
  769. fprintf(stderr, "The service string has been truncated\n");
  770. modbus_free(ctx);
  771. errno = EINVAL;
  772. return NULL;
  773. }
  774. ctx_tcp_pi->t_id = 0;
  775. return ctx;
  776. }