modbus-tcp.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. /*
  2. * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
  3. *
  4. * SPDX-License-Identifier: LGPL-2.1-or-later
  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. /* Subtract 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 < 0) {
  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 >= 0) {
  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. int flags;
  408. struct sockaddr_in addr;
  409. modbus_tcp_t *ctx_tcp;
  410. if (ctx == NULL) {
  411. errno = EINVAL;
  412. return -1;
  413. }
  414. ctx_tcp = ctx->backend_data;
  415. #ifdef OS_WIN32
  416. if (_modbus_tcp_init_win32() == -1) {
  417. return -1;
  418. }
  419. #endif
  420. flags = SOCK_STREAM;
  421. #ifdef SOCK_CLOEXEC
  422. flags |= SOCK_CLOEXEC;
  423. #endif
  424. new_s = socket(PF_INET, flags, IPPROTO_TCP);
  425. if (new_s == -1) {
  426. return -1;
  427. }
  428. enable = 1;
  429. if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR,
  430. (char *)&enable, sizeof(enable)) == -1) {
  431. close(new_s);
  432. return -1;
  433. }
  434. memset(&addr, 0, sizeof(addr));
  435. addr.sin_family = AF_INET;
  436. /* If the modbus port is < to 1024, we need the setuid root. */
  437. addr.sin_port = htons(ctx_tcp->port);
  438. if (ctx_tcp->ip[0] == '0') {
  439. /* Listen any addresses */
  440. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  441. } else {
  442. /* Listen only specified IP address */
  443. addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip);
  444. }
  445. if (bind(new_s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
  446. close(new_s);
  447. return -1;
  448. }
  449. if (listen(new_s, nb_connection) == -1) {
  450. close(new_s);
  451. return -1;
  452. }
  453. return new_s;
  454. }
  455. int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection)
  456. {
  457. int rc;
  458. struct addrinfo *ai_list;
  459. struct addrinfo *ai_ptr;
  460. struct addrinfo ai_hints;
  461. const char *node;
  462. const char *service;
  463. int new_s;
  464. modbus_tcp_pi_t *ctx_tcp_pi;
  465. if (ctx == NULL) {
  466. errno = EINVAL;
  467. return -1;
  468. }
  469. ctx_tcp_pi = ctx->backend_data;
  470. #ifdef OS_WIN32
  471. if (_modbus_tcp_init_win32() == -1) {
  472. return -1;
  473. }
  474. #endif
  475. if (ctx_tcp_pi->node[0] == 0) {
  476. node = NULL; /* == any */
  477. } else {
  478. node = ctx_tcp_pi->node;
  479. }
  480. if (ctx_tcp_pi->service[0] == 0) {
  481. service = "502";
  482. } else {
  483. service = ctx_tcp_pi->service;
  484. }
  485. memset(&ai_hints, 0, sizeof (ai_hints));
  486. /* If node is not NULL, than the AI_PASSIVE flag is ignored. */
  487. ai_hints.ai_flags |= AI_PASSIVE;
  488. #ifdef AI_ADDRCONFIG
  489. ai_hints.ai_flags |= AI_ADDRCONFIG;
  490. #endif
  491. ai_hints.ai_family = AF_UNSPEC;
  492. ai_hints.ai_socktype = SOCK_STREAM;
  493. ai_hints.ai_addr = NULL;
  494. ai_hints.ai_canonname = NULL;
  495. ai_hints.ai_next = NULL;
  496. ai_list = NULL;
  497. rc = getaddrinfo(node, service, &ai_hints, &ai_list);
  498. if (rc != 0) {
  499. if (ctx->debug) {
  500. fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
  501. }
  502. errno = ECONNREFUSED;
  503. return -1;
  504. }
  505. new_s = -1;
  506. for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
  507. int flags = ai_ptr->ai_socktype;
  508. int s;
  509. #ifdef SOCK_CLOEXEC
  510. flags |= SOCK_CLOEXEC;
  511. #endif
  512. s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
  513. if (s < 0) {
  514. if (ctx->debug) {
  515. perror("socket");
  516. }
  517. continue;
  518. } else {
  519. int enable = 1;
  520. rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
  521. (void *)&enable, sizeof (enable));
  522. if (rc != 0) {
  523. close(s);
  524. if (ctx->debug) {
  525. perror("setsockopt");
  526. }
  527. continue;
  528. }
  529. }
  530. rc = bind(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
  531. if (rc != 0) {
  532. close(s);
  533. if (ctx->debug) {
  534. perror("bind");
  535. }
  536. continue;
  537. }
  538. rc = listen(s, nb_connection);
  539. if (rc != 0) {
  540. close(s);
  541. if (ctx->debug) {
  542. perror("listen");
  543. }
  544. continue;
  545. }
  546. new_s = s;
  547. break;
  548. }
  549. freeaddrinfo(ai_list);
  550. if (new_s < 0) {
  551. return -1;
  552. }
  553. return new_s;
  554. }
  555. int modbus_tcp_accept(modbus_t *ctx, int *s)
  556. {
  557. struct sockaddr_in addr;
  558. socklen_t addrlen;
  559. if (ctx == NULL) {
  560. errno = EINVAL;
  561. return -1;
  562. }
  563. addrlen = sizeof(addr);
  564. #ifdef HAVE_ACCEPT4
  565. /* Inherit socket flags and use accept4 call */
  566. ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
  567. #else
  568. ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
  569. #endif
  570. if (ctx->s < 0) {
  571. return -1;
  572. }
  573. if (ctx->debug) {
  574. printf("The client connection from %s is accepted\n",
  575. inet_ntoa(addr.sin_addr));
  576. }
  577. return ctx->s;
  578. }
  579. int modbus_tcp_pi_accept(modbus_t *ctx, int *s)
  580. {
  581. struct sockaddr_storage addr;
  582. socklen_t addrlen;
  583. if (ctx == NULL) {
  584. errno = EINVAL;
  585. return -1;
  586. }
  587. addrlen = sizeof(addr);
  588. #ifdef HAVE_ACCEPT4
  589. /* Inherit socket flags and use accept4 call */
  590. ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC);
  591. #else
  592. ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen);
  593. #endif
  594. if (ctx->s < 0) {
  595. return -1;
  596. }
  597. if (ctx->debug) {
  598. printf("The client connection is accepted.\n");
  599. }
  600. return ctx->s;
  601. }
  602. static int _modbus_tcp_select(modbus_t *ctx, fd_set *rset, struct timeval *tv, int length_to_read)
  603. {
  604. int s_rc;
  605. while ((s_rc = select(ctx->s+1, rset, NULL, NULL, tv)) == -1) {
  606. if (errno == EINTR) {
  607. if (ctx->debug) {
  608. fprintf(stderr, "A non blocked signal was caught\n");
  609. }
  610. /* Necessary after an error */
  611. FD_ZERO(rset);
  612. FD_SET(ctx->s, rset);
  613. } else {
  614. return -1;
  615. }
  616. }
  617. if (s_rc == 0) {
  618. errno = ETIMEDOUT;
  619. return -1;
  620. }
  621. return s_rc;
  622. }
  623. static void _modbus_tcp_free(modbus_t *ctx) {
  624. if (ctx->backend_data) {
  625. free(ctx->backend_data);
  626. }
  627. free(ctx);
  628. }
  629. static void _modbus_tcp_pi_free(modbus_t *ctx) {
  630. if (ctx->backend_data) {
  631. modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
  632. free(ctx_tcp_pi->node);
  633. free(ctx_tcp_pi->service);
  634. free(ctx->backend_data);
  635. }
  636. free(ctx);
  637. }
  638. const modbus_backend_t _modbus_tcp_backend = {
  639. _MODBUS_BACKEND_TYPE_TCP,
  640. _MODBUS_TCP_HEADER_LENGTH,
  641. _MODBUS_TCP_CHECKSUM_LENGTH,
  642. MODBUS_TCP_MAX_ADU_LENGTH,
  643. _modbus_set_slave,
  644. _modbus_tcp_build_request_basis,
  645. _modbus_tcp_build_response_basis,
  646. _modbus_tcp_prepare_response_tid,
  647. _modbus_tcp_send_msg_pre,
  648. _modbus_tcp_send,
  649. _modbus_tcp_receive,
  650. _modbus_tcp_recv,
  651. _modbus_tcp_check_integrity,
  652. _modbus_tcp_pre_check_confirmation,
  653. _modbus_tcp_connect,
  654. _modbus_tcp_close,
  655. _modbus_tcp_flush,
  656. _modbus_tcp_select,
  657. _modbus_tcp_free
  658. };
  659. const modbus_backend_t _modbus_tcp_pi_backend = {
  660. _MODBUS_BACKEND_TYPE_TCP,
  661. _MODBUS_TCP_HEADER_LENGTH,
  662. _MODBUS_TCP_CHECKSUM_LENGTH,
  663. MODBUS_TCP_MAX_ADU_LENGTH,
  664. _modbus_set_slave,
  665. _modbus_tcp_build_request_basis,
  666. _modbus_tcp_build_response_basis,
  667. _modbus_tcp_prepare_response_tid,
  668. _modbus_tcp_send_msg_pre,
  669. _modbus_tcp_send,
  670. _modbus_tcp_receive,
  671. _modbus_tcp_recv,
  672. _modbus_tcp_check_integrity,
  673. _modbus_tcp_pre_check_confirmation,
  674. _modbus_tcp_pi_connect,
  675. _modbus_tcp_close,
  676. _modbus_tcp_flush,
  677. _modbus_tcp_select,
  678. _modbus_tcp_pi_free
  679. };
  680. modbus_t* modbus_new_tcp(const char *ip, int port)
  681. {
  682. modbus_t *ctx;
  683. modbus_tcp_t *ctx_tcp;
  684. size_t dest_size;
  685. size_t ret_size;
  686. #if defined(OS_BSD)
  687. /* MSG_NOSIGNAL is unsupported on *BSD so we install an ignore
  688. handler for SIGPIPE. */
  689. struct sigaction sa;
  690. sa.sa_handler = SIG_IGN;
  691. if (sigaction(SIGPIPE, &sa, NULL) < 0) {
  692. /* The debug flag can't be set here... */
  693. fprintf(stderr, "Could not install SIGPIPE handler.\n");
  694. return NULL;
  695. }
  696. #endif
  697. ctx = (modbus_t *)malloc(sizeof(modbus_t));
  698. if (ctx == NULL) {
  699. return NULL;
  700. }
  701. _modbus_init_common(ctx);
  702. /* Could be changed after to reach a remote serial Modbus device */
  703. ctx->slave = MODBUS_TCP_SLAVE;
  704. ctx->backend = &_modbus_tcp_backend;
  705. ctx->backend_data = (modbus_tcp_t *)malloc(sizeof(modbus_tcp_t));
  706. if (ctx->backend_data == NULL) {
  707. modbus_free(ctx);
  708. errno = ENOMEM;
  709. return NULL;
  710. }
  711. ctx_tcp = (modbus_tcp_t *)ctx->backend_data;
  712. if (ip != NULL) {
  713. dest_size = sizeof(char) * 16;
  714. ret_size = strlcpy(ctx_tcp->ip, ip, dest_size);
  715. if (ret_size == 0) {
  716. fprintf(stderr, "The IP string is empty\n");
  717. modbus_free(ctx);
  718. errno = EINVAL;
  719. return NULL;
  720. }
  721. if (ret_size >= dest_size) {
  722. fprintf(stderr, "The IP string has been truncated\n");
  723. modbus_free(ctx);
  724. errno = EINVAL;
  725. return NULL;
  726. }
  727. } else {
  728. ctx_tcp->ip[0] = '0';
  729. }
  730. ctx_tcp->port = port;
  731. ctx_tcp->t_id = 0;
  732. return ctx;
  733. }
  734. modbus_t* modbus_new_tcp_pi(const char *node, const char *service)
  735. {
  736. modbus_t *ctx;
  737. modbus_tcp_pi_t *ctx_tcp_pi;
  738. ctx = (modbus_t *)malloc(sizeof(modbus_t));
  739. if (ctx == NULL) {
  740. return NULL;
  741. }
  742. _modbus_init_common(ctx);
  743. /* Could be changed after to reach a remote serial Modbus device */
  744. ctx->slave = MODBUS_TCP_SLAVE;
  745. ctx->backend = &_modbus_tcp_pi_backend;
  746. ctx->backend_data = (modbus_tcp_pi_t *)malloc(sizeof(modbus_tcp_pi_t));
  747. if (ctx->backend_data == NULL) {
  748. modbus_free(ctx);
  749. errno = ENOMEM;
  750. return NULL;
  751. }
  752. ctx_tcp_pi = (modbus_tcp_pi_t *)ctx->backend_data;
  753. ctx_tcp_pi->node = NULL;
  754. ctx_tcp_pi->service = NULL;
  755. if (node != NULL) {
  756. ctx_tcp_pi->node = strdup(node);
  757. } else {
  758. /* The node argument can be empty to indicate any hosts */
  759. ctx_tcp_pi->node = strdup("");
  760. }
  761. if (ctx_tcp_pi->node == NULL) {
  762. modbus_free(ctx);
  763. errno = ENOMEM;
  764. return NULL;
  765. }
  766. if (service != NULL && service[0] != '\0') {
  767. ctx_tcp_pi->service = strdup(service);
  768. } else {
  769. /* Default Modbus port number */
  770. ctx_tcp_pi->service = strdup("502");
  771. }
  772. if (ctx_tcp_pi->service == NULL) {
  773. modbus_free(ctx);
  774. errno = ENOMEM;
  775. return NULL;
  776. }
  777. ctx_tcp_pi->t_id = 0;
  778. return ctx;
  779. }