modbus-tcp.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. // addr.sin_addr.s_addr = INADDR_ANY;
  291. rc = _connect(ctx->s, (struct sockaddr *)&addr, sizeof(addr), &ctx->response_timeout);
  292. if (rc == -1) {
  293. close(ctx->s);
  294. ctx->s = -1;
  295. return -1;
  296. }
  297. return 0;
  298. }
  299. /* Establishes a modbus TCP PI connection with a Modbus server. */
  300. static int _modbus_tcp_pi_connect(modbus_t *ctx)
  301. {
  302. int rc;
  303. struct addrinfo *ai_list;
  304. struct addrinfo *ai_ptr;
  305. struct addrinfo ai_hints;
  306. modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
  307. #ifdef OS_WIN32
  308. if (_modbus_tcp_init_win32() == -1) {
  309. return -1;
  310. }
  311. #endif
  312. memset(&ai_hints, 0, sizeof(ai_hints));
  313. #ifdef AI_ADDRCONFIG
  314. ai_hints.ai_flags |= AI_ADDRCONFIG;
  315. #endif
  316. ai_hints.ai_family = AF_UNSPEC;
  317. ai_hints.ai_socktype = SOCK_STREAM;
  318. ai_hints.ai_addr = NULL;
  319. ai_hints.ai_canonname = NULL;
  320. ai_hints.ai_next = NULL;
  321. ai_list = NULL;
  322. rc = getaddrinfo(ctx_tcp_pi->node, ctx_tcp_pi->service,
  323. &ai_hints, &ai_list);
  324. if (rc != 0) {
  325. if (ctx->debug) {
  326. fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
  327. }
  328. errno = ECONNREFUSED;
  329. return -1;
  330. }
  331. for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
  332. int flags = ai_ptr->ai_socktype;
  333. int s;
  334. #ifdef SOCK_CLOEXEC
  335. flags |= SOCK_CLOEXEC;
  336. #endif
  337. #ifdef SOCK_NONBLOCK
  338. flags |= SOCK_NONBLOCK;
  339. #endif
  340. s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
  341. if (s < 0)
  342. continue;
  343. if (ai_ptr->ai_family == AF_INET)
  344. _modbus_tcp_set_ipv4_options(s);
  345. if (ctx->debug) {
  346. printf("Connecting to [%s]:%s\n", ctx_tcp_pi->node, ctx_tcp_pi->service);
  347. }
  348. rc = _connect(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen, &ctx->response_timeout);
  349. if (rc == -1) {
  350. close(s);
  351. continue;
  352. }
  353. ctx->s = s;
  354. break;
  355. }
  356. freeaddrinfo(ai_list);
  357. if (ctx->s < 0) {
  358. return -1;
  359. }
  360. return 0;
  361. }
  362. /* Closes the network connection and socket in TCP mode */
  363. static void _modbus_tcp_close(modbus_t *ctx)
  364. {
  365. if (ctx->s != -1) {
  366. shutdown(ctx->s, SHUT_RDWR);
  367. close(ctx->s);
  368. ctx->s = -1;
  369. }
  370. }
  371. static int _modbus_tcp_flush(modbus_t *ctx)
  372. {
  373. int rc;
  374. int rc_sum = 0;
  375. do {
  376. /* Extract the garbage from the socket */
  377. char devnull[MODBUS_TCP_MAX_ADU_LENGTH];
  378. #ifndef OS_WIN32
  379. rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, MSG_DONTWAIT);
  380. #else
  381. /* On Win32, it's a bit more complicated to not wait */
  382. fd_set rset;
  383. struct timeval tv;
  384. tv.tv_sec = 0;
  385. tv.tv_usec = 0;
  386. FD_ZERO(&rset);
  387. FD_SET(ctx->s, &rset);
  388. rc = select(ctx->s+1, &rset, NULL, NULL, &tv);
  389. if (rc == -1) {
  390. return -1;
  391. }
  392. if (rc == 1) {
  393. /* There is data to flush */
  394. rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, 0);
  395. }
  396. #endif
  397. if (rc > 0) {
  398. rc_sum += rc;
  399. }
  400. } while (rc == MODBUS_TCP_MAX_ADU_LENGTH);
  401. return rc_sum;
  402. }
  403. /* Listens for any request from one or many modbus masters in TCP */
  404. int modbus_tcp_listen(modbus_t *ctx, int nb_connection)
  405. {
  406. int new_s;
  407. int enable;
  408. int flags;
  409. struct sockaddr_in addr;
  410. modbus_tcp_t *ctx_tcp;
  411. if (ctx == NULL) {
  412. errno = EINVAL;
  413. return -1;
  414. }
  415. ctx_tcp = ctx->backend_data;
  416. #ifdef OS_WIN32
  417. if (_modbus_tcp_init_win32() == -1) {
  418. return -1;
  419. }
  420. #endif
  421. flags = SOCK_STREAM;
  422. #ifdef SOCK_CLOEXEC
  423. flags |= SOCK_CLOEXEC;
  424. #endif
  425. new_s = socket(PF_INET, flags, IPPROTO_TCP);
  426. if (new_s == -1) {
  427. return -1;
  428. }
  429. enable = 1;
  430. if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR,
  431. (char *)&enable, sizeof(enable)) == -1) {
  432. close(new_s);
  433. return -1;
  434. }
  435. memset(&addr, 0, sizeof(addr));
  436. addr.sin_family = AF_INET;
  437. /* If the modbus port is < to 1024, we need the setuid root. */
  438. addr.sin_port = htons(ctx_tcp->port);
  439. if (ctx_tcp->ip[0] == '0') {
  440. /* Listen any addresses */
  441. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  442. } else {
  443. /* Listen only specified IP address */
  444. addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip);
  445. }
  446. if (bind(new_s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
  447. close(new_s);
  448. return -1;
  449. }
  450. if (listen(new_s, nb_connection) == -1) {
  451. close(new_s);
  452. return -1;
  453. }
  454. return new_s;
  455. }
  456. int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection)
  457. {
  458. int rc;
  459. struct addrinfo *ai_list;
  460. struct addrinfo *ai_ptr;
  461. struct addrinfo ai_hints;
  462. const char *node;
  463. const char *service;
  464. int new_s;
  465. modbus_tcp_pi_t *ctx_tcp_pi;
  466. if (ctx == NULL) {
  467. errno = EINVAL;
  468. return -1;
  469. }
  470. ctx_tcp_pi = ctx->backend_data;
  471. #ifdef OS_WIN32
  472. if (_modbus_tcp_init_win32() == -1) {
  473. return -1;
  474. }
  475. #endif
  476. if (ctx_tcp_pi->node[0] == 0) {
  477. node = NULL; /* == any */
  478. } else {
  479. node = ctx_tcp_pi->node;
  480. }
  481. if (ctx_tcp_pi->service[0] == 0) {
  482. service = "502";
  483. } else {
  484. service = ctx_tcp_pi->service;
  485. }
  486. memset(&ai_hints, 0, sizeof (ai_hints));
  487. /* If node is not NULL, than the AI_PASSIVE flag is ignored. */
  488. ai_hints.ai_flags |= AI_PASSIVE;
  489. #ifdef AI_ADDRCONFIG
  490. ai_hints.ai_flags |= AI_ADDRCONFIG;
  491. #endif
  492. ai_hints.ai_family = AF_UNSPEC;
  493. ai_hints.ai_socktype = SOCK_STREAM;
  494. ai_hints.ai_addr = NULL;
  495. ai_hints.ai_canonname = NULL;
  496. ai_hints.ai_next = NULL;
  497. ai_list = NULL;
  498. rc = getaddrinfo(node, service, &ai_hints, &ai_list);
  499. if (rc != 0) {
  500. if (ctx->debug) {
  501. fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
  502. }
  503. errno = ECONNREFUSED;
  504. return -1;
  505. }
  506. new_s = -1;
  507. for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
  508. int flags = ai_ptr->ai_socktype;
  509. int s;
  510. #ifdef SOCK_CLOEXEC
  511. flags |= SOCK_CLOEXEC;
  512. #endif
  513. s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
  514. if (s < 0) {
  515. if (ctx->debug) {
  516. perror("socket");
  517. }
  518. continue;
  519. } else {
  520. int enable = 1;
  521. rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
  522. (void *)&enable, sizeof (enable));
  523. if (rc != 0) {
  524. close(s);
  525. if (ctx->debug) {
  526. perror("setsockopt");
  527. }
  528. continue;
  529. }
  530. }
  531. rc = bind(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
  532. if (rc != 0) {
  533. close(s);
  534. if (ctx->debug) {
  535. perror("bind");
  536. }
  537. continue;
  538. }
  539. rc = listen(s, nb_connection);
  540. if (rc != 0) {
  541. close(s);
  542. if (ctx->debug) {
  543. perror("listen");
  544. }
  545. continue;
  546. }
  547. new_s = s;
  548. break;
  549. }
  550. freeaddrinfo(ai_list);
  551. if (new_s < 0) {
  552. return -1;
  553. }
  554. return new_s;
  555. }
  556. int modbus_tcp_accept(modbus_t *ctx, int *s)
  557. {
  558. struct sockaddr_in addr;
  559. socklen_t addrlen;
  560. if (ctx == NULL) {
  561. errno = EINVAL;
  562. return -1;
  563. }
  564. addrlen = sizeof(addr);
  565. #ifdef HAVE_ACCEPT4
  566. /* Inherit socket flags and use accept4 call */
  567. ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
  568. #else
  569. ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
  570. #endif
  571. if (ctx->s == -1) {
  572. return -1;
  573. }
  574. if (ctx->debug) {
  575. printf("The client connection from %s is accepted\n",
  576. inet_ntoa(addr.sin_addr));
  577. }
  578. return ctx->s;
  579. }
  580. int modbus_tcp_pi_accept(modbus_t *ctx, int *s)
  581. {
  582. struct sockaddr_storage addr;
  583. socklen_t addrlen;
  584. if (ctx == NULL) {
  585. errno = EINVAL;
  586. return -1;
  587. }
  588. addrlen = sizeof(addr);
  589. #ifdef HAVE_ACCEPT4
  590. /* Inherit socket flags and use accept4 call */
  591. ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
  592. #else
  593. ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
  594. #endif
  595. if (ctx->s == -1) {
  596. return -1;
  597. }
  598. if (ctx->debug) {
  599. printf("The client connection is accepted.\n");
  600. }
  601. return ctx->s;
  602. }
  603. static int _modbus_tcp_select(modbus_t *ctx, fd_set *rset, struct timeval *tv, int length_to_read)
  604. {
  605. int s_rc;
  606. while ((s_rc = select(ctx->s+1, rset, NULL, NULL, tv)) == -1) {
  607. if (errno == EINTR) {
  608. if (ctx->debug) {
  609. fprintf(stderr, "A non blocked signal was caught\n");
  610. }
  611. /* Necessary after an error */
  612. FD_ZERO(rset);
  613. FD_SET(ctx->s, rset);
  614. } else {
  615. return -1;
  616. }
  617. }
  618. if (s_rc == 0) {
  619. errno = ETIMEDOUT;
  620. return -1;
  621. }
  622. return s_rc;
  623. }
  624. static void _modbus_tcp_free(modbus_t *ctx) {
  625. free(ctx->backend_data);
  626. free(ctx);
  627. }
  628. const modbus_backend_t _modbus_tcp_backend = {
  629. _MODBUS_BACKEND_TYPE_TCP,
  630. _MODBUS_TCP_HEADER_LENGTH,
  631. _MODBUS_TCP_CHECKSUM_LENGTH,
  632. MODBUS_TCP_MAX_ADU_LENGTH,
  633. _modbus_set_slave,
  634. _modbus_tcp_build_request_basis,
  635. _modbus_tcp_build_response_basis,
  636. _modbus_tcp_prepare_response_tid,
  637. _modbus_tcp_send_msg_pre,
  638. _modbus_tcp_send,
  639. _modbus_tcp_receive,
  640. _modbus_tcp_recv,
  641. _modbus_tcp_check_integrity,
  642. _modbus_tcp_pre_check_confirmation,
  643. _modbus_tcp_connect,
  644. _modbus_tcp_close,
  645. _modbus_tcp_flush,
  646. _modbus_tcp_select,
  647. _modbus_tcp_free
  648. };
  649. const modbus_backend_t _modbus_tcp_pi_backend = {
  650. _MODBUS_BACKEND_TYPE_TCP,
  651. _MODBUS_TCP_HEADER_LENGTH,
  652. _MODBUS_TCP_CHECKSUM_LENGTH,
  653. MODBUS_TCP_MAX_ADU_LENGTH,
  654. _modbus_set_slave,
  655. _modbus_tcp_build_request_basis,
  656. _modbus_tcp_build_response_basis,
  657. _modbus_tcp_prepare_response_tid,
  658. _modbus_tcp_send_msg_pre,
  659. _modbus_tcp_send,
  660. _modbus_tcp_receive,
  661. _modbus_tcp_recv,
  662. _modbus_tcp_check_integrity,
  663. _modbus_tcp_pre_check_confirmation,
  664. _modbus_tcp_pi_connect,
  665. _modbus_tcp_close,
  666. _modbus_tcp_flush,
  667. _modbus_tcp_select,
  668. _modbus_tcp_free
  669. };
  670. modbus_t* modbus_new_tcp(const char *ip, int port)
  671. {
  672. modbus_t *ctx;
  673. modbus_tcp_t *ctx_tcp;
  674. size_t dest_size;
  675. size_t ret_size;
  676. #if defined(OS_BSD)
  677. /* MSG_NOSIGNAL is unsupported on *BSD so we install an ignore
  678. handler for SIGPIPE. */
  679. struct sigaction sa;
  680. sa.sa_handler = SIG_IGN;
  681. if (sigaction(SIGPIPE, &sa, NULL) < 0) {
  682. /* The debug flag can't be set here... */
  683. fprintf(stderr, "Could not install SIGPIPE handler.\n");
  684. return NULL;
  685. }
  686. #endif
  687. ctx = (modbus_t *)malloc(sizeof(modbus_t));
  688. if (ctx == NULL) {
  689. return NULL;
  690. }
  691. _modbus_init_common(ctx);
  692. /* Could be changed after to reach a remote serial Modbus device */
  693. ctx->slave = MODBUS_TCP_SLAVE;
  694. ctx->backend = &_modbus_tcp_backend;
  695. ctx->backend_data = (modbus_tcp_t *)malloc(sizeof(modbus_tcp_t));
  696. if (ctx->backend_data == NULL) {
  697. modbus_free(ctx);
  698. errno = ENOMEM;
  699. return NULL;
  700. }
  701. ctx_tcp = (modbus_tcp_t *)ctx->backend_data;
  702. if (ip != NULL) {
  703. dest_size = sizeof(char) * 16;
  704. ret_size = strlcpy(ctx_tcp->ip, ip, dest_size);
  705. if (ret_size == 0) {
  706. fprintf(stderr, "The IP string is empty\n");
  707. modbus_free(ctx);
  708. errno = EINVAL;
  709. return NULL;
  710. }
  711. if (ret_size >= dest_size) {
  712. fprintf(stderr, "The IP string has been truncated\n");
  713. modbus_free(ctx);
  714. errno = EINVAL;
  715. return NULL;
  716. }
  717. } else {
  718. ctx_tcp->ip[0] = '0';
  719. }
  720. ctx_tcp->port = port;
  721. ctx_tcp->t_id = 0;
  722. return ctx;
  723. }
  724. modbus_t* modbus_new_tcp_pi(const char *node, const char *service)
  725. {
  726. modbus_t *ctx;
  727. modbus_tcp_pi_t *ctx_tcp_pi;
  728. size_t dest_size;
  729. size_t ret_size;
  730. ctx = (modbus_t *)malloc(sizeof(modbus_t));
  731. if (ctx == NULL) {
  732. return NULL;
  733. }
  734. _modbus_init_common(ctx);
  735. /* Could be changed after to reach a remote serial Modbus device */
  736. ctx->slave = MODBUS_TCP_SLAVE;
  737. ctx->backend = &_modbus_tcp_pi_backend;
  738. ctx->backend_data = (modbus_tcp_pi_t *)malloc(sizeof(modbus_tcp_pi_t));
  739. if (ctx->backend_data == NULL) {
  740. modbus_free(ctx);
  741. errno = ENOMEM;
  742. return NULL;
  743. }
  744. ctx_tcp_pi = (modbus_tcp_pi_t *)ctx->backend_data;
  745. if (node == NULL) {
  746. /* The node argument can be empty to indicate any hosts */
  747. ctx_tcp_pi->node[0] = 0;
  748. } else {
  749. dest_size = sizeof(char) * _MODBUS_TCP_PI_NODE_LENGTH;
  750. ret_size = strlcpy(ctx_tcp_pi->node, node, dest_size);
  751. if (ret_size == 0) {
  752. fprintf(stderr, "The node string is empty\n");
  753. modbus_free(ctx);
  754. errno = EINVAL;
  755. return NULL;
  756. }
  757. if (ret_size >= dest_size) {
  758. fprintf(stderr, "The node string has been truncated\n");
  759. modbus_free(ctx);
  760. errno = EINVAL;
  761. return NULL;
  762. }
  763. }
  764. if (service != NULL) {
  765. dest_size = sizeof(char) * _MODBUS_TCP_PI_SERVICE_LENGTH;
  766. ret_size = strlcpy(ctx_tcp_pi->service, service, dest_size);
  767. } else {
  768. /* Empty service is not allowed, error catched below. */
  769. ret_size = 0;
  770. }
  771. if (ret_size == 0) {
  772. fprintf(stderr, "The service string is empty\n");
  773. modbus_free(ctx);
  774. errno = EINVAL;
  775. return NULL;
  776. }
  777. if (ret_size >= dest_size) {
  778. fprintf(stderr, "The service string has been truncated\n");
  779. modbus_free(ctx);
  780. errno = EINVAL;
  781. return NULL;
  782. }
  783. ctx_tcp_pi->t_id = 0;
  784. return ctx;
  785. }