networklayer_tcp.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /*
  2. * This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  3. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  4. */
  5. #ifdef NOT_AMALGATED
  6. # define _XOPEN_SOURCE 500 //some users need this for some reason
  7. # define __USE_BSD
  8. # include <stdlib.h> // malloc, free
  9. # include <stdio.h>
  10. # include <string.h> // memset
  11. #endif
  12. #ifdef _WIN32
  13. # include <malloc.h>
  14. # include <winsock2.h>
  15. # include <sys/types.h>
  16. # include <windows.h>
  17. # include <ws2tcpip.h>
  18. # define CLOSESOCKET(S) closesocket(S)
  19. #else
  20. # include <sys/select.h>
  21. # include <netinet/in.h>
  22. # include <netinet/tcp.h>
  23. # include <sys/ioctl.h>
  24. # include <netdb.h> //gethostbyname for the client
  25. # include <unistd.h> // read, write, close
  26. # include <arpa/inet.h>
  27. # define CLOSESOCKET(S) close(S)
  28. #endif
  29. #include "networklayer_tcp.h" // UA_MULTITHREADING is defined in here
  30. #ifdef UA_MULTITHREADING
  31. # include <urcu/uatomic.h>
  32. #endif
  33. /* with a space so amalgamation does not remove the includes */
  34. # include <errno.h> // errno, EINTR
  35. # include <fcntl.h> // fcntl
  36. struct ServerNetworklayer_TCP;
  37. /* Forwarded to the server as a (UA_Connection) and used for callbacks back into
  38. the networklayer */
  39. typedef struct {
  40. UA_Connection connection;
  41. UA_Int32 sockfd;
  42. void *layer;
  43. } TCPConnection;
  44. /***************************/
  45. /* Server NetworkLayer TCP */
  46. /***************************/
  47. #define MAXBACKLOG 100
  48. /* Internal mapping of sockets to connections */
  49. typedef struct {
  50. TCPConnection *connection;
  51. #ifdef _WIN32
  52. UA_UInt32 sockfd;
  53. #else
  54. UA_Int32 sockfd;
  55. #endif
  56. } ConnectionLink;
  57. typedef struct ServerNetworkLayerTCP {
  58. UA_ConnectionConfig conf;
  59. fd_set fdset;
  60. #ifdef _WIN32
  61. UA_UInt32 serversockfd;
  62. UA_UInt32 highestfd;
  63. #else
  64. UA_Int32 serversockfd;
  65. UA_Int32 highestfd;
  66. #endif
  67. UA_UInt16 conLinksSize;
  68. ConnectionLink *conLinks;
  69. UA_UInt32 port;
  70. UA_String discoveryUrl;
  71. /* We remove the connection links only in the main thread. Attach
  72. to-be-deleted links with atomic operations */
  73. struct deleteLink {
  74. #ifdef _WIN32
  75. UA_UInt32 sockfd;
  76. #else
  77. UA_Int32 sockfd;
  78. #endif
  79. struct deleteLink *next;
  80. } *deleteLinkList;
  81. } ServerNetworkLayerTCP;
  82. typedef struct ClientNetworkLayerTCP {
  83. fd_set read_fds;
  84. #ifdef _WIN32
  85. UA_UInt32 sockfd;
  86. #else
  87. UA_Int32 sockfd;
  88. #endif
  89. } ClientNetworkLayerTCP;
  90. static UA_StatusCode setNonBlocking(int sockid) {
  91. #ifdef _WIN32
  92. u_long iMode = 1;
  93. if(ioctlsocket(sockid, FIONBIO, &iMode) != NO_ERROR)
  94. return UA_STATUSCODE_BADINTERNALERROR;
  95. #else
  96. int opts = fcntl(sockid,F_GETFL);
  97. if(opts < 0 || fcntl(sockid,F_SETFL,opts|O_NONBLOCK) < 0)
  98. return UA_STATUSCODE_BADINTERNALERROR;
  99. #endif
  100. return UA_STATUSCODE_GOOD;
  101. }
  102. static void freeConnectionCallback(UA_Server *server, TCPConnection *connection) {
  103. free(connection);
  104. }
  105. // after every select, reset the set of sockets we want to listen on
  106. static void setFDSet(ServerNetworkLayerTCP *layer) {
  107. FD_ZERO(&layer->fdset);
  108. FD_SET(layer->serversockfd, &layer->fdset);
  109. layer->highestfd = layer->serversockfd;
  110. for(UA_Int32 i=0;i<layer->conLinksSize;i++) {
  111. FD_SET(layer->conLinks[i].sockfd, &layer->fdset);
  112. if(layer->conLinks[i].sockfd > layer->highestfd)
  113. layer->highestfd = layer->conLinks[i].sockfd;
  114. }
  115. }
  116. // the callbacks are thread-safe if UA_MULTITHREADING is defined
  117. void closeConnection(TCPConnection *handle);
  118. void writeCallback(TCPConnection *handle, UA_ByteStringArray gather_buf);
  119. static UA_StatusCode ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd) {
  120. setNonBlocking(newsockfd);
  121. TCPConnection *c = malloc(sizeof(TCPConnection));
  122. if(!c)
  123. return UA_STATUSCODE_BADINTERNALERROR;
  124. c->sockfd = newsockfd;
  125. c->layer = layer;
  126. c->connection.state = UA_CONNECTION_OPENING;
  127. c->connection.localConf = layer->conf;
  128. c->connection.channel = (void*)0;
  129. c->connection.close = (void (*)(void*))closeConnection;
  130. c->connection.write = (void (*)(void*, UA_ByteStringArray))writeCallback;
  131. layer->conLinks = realloc(layer->conLinks, sizeof(ConnectionLink)*(layer->conLinksSize+1));
  132. if(!layer->conLinks) {
  133. free(c);
  134. return UA_STATUSCODE_BADINTERNALERROR;
  135. }
  136. layer->conLinks[layer->conLinksSize].connection = c;
  137. layer->conLinks[layer->conLinksSize].sockfd = newsockfd;
  138. layer->conLinksSize++;
  139. return UA_STATUSCODE_GOOD;
  140. }
  141. /* Removes all connections from the network layer. Returns the work items to close them properly. */
  142. static UA_UInt32 removeAllConnections(ServerNetworkLayerTCP *layer, UA_WorkItem **returnWork) {
  143. UA_WorkItem *work;
  144. if (layer->conLinksSize <= 0 || !(work = malloc(sizeof(UA_WorkItem)*layer->conLinksSize))) {
  145. *returnWork = NULL;
  146. return 0;
  147. }
  148. #ifdef UA_MULTITHREADING
  149. struct deleteLink *d = uatomic_xchg(&layer->deleteLinkList, (void*)0);
  150. #else
  151. struct deleteLink *d = layer->deleteLinkList;
  152. layer->deleteLinkList = (void*)0;
  153. #endif
  154. UA_UInt32 count = 0;
  155. while(d) {
  156. UA_Int32 i;
  157. for(i = 0;i<layer->conLinksSize;i++) {
  158. if(layer->conLinks[i].sockfd == d->sockfd)
  159. break;
  160. }
  161. if(i < layer->conLinksSize) {
  162. TCPConnection *c = layer->conLinks[i].connection;
  163. layer->conLinksSize--;
  164. layer->conLinks[i] = layer->conLinks[layer->conLinksSize];
  165. work[count] = (UA_WorkItem)
  166. {.type = UA_WORKITEMTYPE_DELAYEDMETHODCALL,
  167. .work.methodCall = {.data = c,
  168. .method = (void (*)(UA_Server*,void*))freeConnectionCallback} };
  169. }
  170. struct deleteLink *oldd = d;
  171. d = d->next;
  172. free(oldd);
  173. count++;
  174. }
  175. *returnWork = work;
  176. return count;
  177. }
  178. #ifdef UA_MULTITHREADING
  179. void closeConnection(TCPConnection *handle) {
  180. if(uatomic_xchg(&handle->connection.state, UA_CONNECTION_CLOSING) == UA_CONNECTION_CLOSING)
  181. return;
  182. UA_Connection_detachSecureChannel(&handle->connection);
  183. shutdown(handle->sockfd,2);
  184. CLOSESOCKET(handle->sockfd);
  185. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)handle->layer;
  186. // Remove the link later in the main thread
  187. struct deleteLink *d = malloc(sizeof(struct deleteLink));
  188. d->sockfd = handle->sockfd;
  189. while(1) {
  190. d->next = layer->deleteLinkList;
  191. if(uatomic_cmpxchg(&layer->deleteLinkList, d->next, d) == d->next)
  192. break;
  193. }
  194. }
  195. #else
  196. void closeConnection(TCPConnection *handle) {
  197. if(handle->connection.state == UA_CONNECTION_CLOSING)
  198. return;
  199. struct deleteLink *d = malloc(sizeof(struct deleteLink));
  200. if(!d)
  201. return;
  202. handle->connection.state = UA_CONNECTION_CLOSING;
  203. UA_Connection_detachSecureChannel(&handle->connection);
  204. shutdown(handle->sockfd,2);
  205. CLOSESOCKET(handle->sockfd);
  206. // Remove the link later in the main thread
  207. d->sockfd = handle->sockfd;
  208. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)handle->layer;
  209. d->next = layer->deleteLinkList;
  210. layer->deleteLinkList = d;
  211. }
  212. #endif
  213. /** Accesses only the sockfd in the handle. Can be run from parallel threads. */
  214. void writeCallback(TCPConnection *handle, UA_ByteStringArray gather_buf) {
  215. UA_UInt32 total_len = 0, nWritten = 0;
  216. #ifdef _WIN32
  217. LPWSABUF buf = _alloca(gather_buf.stringsSize * sizeof(WSABUF));
  218. memset(buf, 0, sizeof(gather_buf.stringsSize * sizeof(WSABUF)));
  219. int result = 0;
  220. for(UA_UInt32 i = 0; i<gather_buf.stringsSize; i++) {
  221. buf[i].buf = (char*)gather_buf.strings[i].data;
  222. buf[i].len = gather_buf.strings[i].length;
  223. total_len += gather_buf.strings[i].length;
  224. }
  225. while(nWritten < total_len) {
  226. UA_UInt32 n = 0;
  227. do {
  228. result = WSASend(handle->sockfd, buf, gather_buf.stringsSize ,
  229. (LPDWORD)&n, 0, NULL, NULL);
  230. if(result != 0)
  231. printf("Error WSASend, code: %d \n", WSAGetLastError());
  232. } while(errno == EINTR);
  233. nWritten += n;
  234. }
  235. #else
  236. struct iovec iov[gather_buf.stringsSize];
  237. memset(iov, 0, sizeof(struct iovec)*gather_buf.stringsSize);
  238. for(UA_UInt32 i=0;i<gather_buf.stringsSize;i++) {
  239. iov[i].iov_base = gather_buf.strings[i].data;
  240. iov[i].iov_len = gather_buf.strings[i].length;
  241. total_len += gather_buf.strings[i].length;
  242. }
  243. struct msghdr message;
  244. memset(&message, 0, sizeof(message));
  245. message.msg_iov = iov;
  246. message.msg_iovlen = gather_buf.stringsSize;
  247. while (nWritten < total_len) {
  248. UA_Int32 n = 0;
  249. do {
  250. n = sendmsg(handle->sockfd, &message, 0);
  251. } while (n == -1L && errno == EINTR);
  252. nWritten += n;
  253. }
  254. #endif
  255. }
  256. static UA_StatusCode ServerNetworkLayerTCP_start(ServerNetworkLayerTCP *layer, UA_Logger *logger) {
  257. #ifdef _WIN32
  258. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == INVALID_SOCKET) {
  259. printf("ERROR opening socket, code: %d\n", WSAGetLastError());
  260. return UA_STATUSCODE_BADINTERNALERROR;
  261. }
  262. #else
  263. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  264. perror("ERROR opening socket");
  265. return UA_STATUSCODE_BADINTERNALERROR;
  266. }
  267. #endif
  268. const struct sockaddr_in serv_addr = {
  269. .sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  270. .sin_port = htons(layer->port), .sin_zero = {0}};
  271. int optval = 1;
  272. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  273. SO_REUSEADDR, (const char *)&optval,
  274. sizeof(optval)) == -1) {
  275. perror("setsockopt");
  276. CLOSESOCKET(layer->serversockfd);
  277. return UA_STATUSCODE_BADINTERNALERROR;
  278. }
  279. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  280. sizeof(serv_addr)) < 0) {
  281. perror("binding");
  282. CLOSESOCKET(layer->serversockfd);
  283. return UA_STATUSCODE_BADINTERNALERROR;
  284. }
  285. setNonBlocking(layer->serversockfd);
  286. listen(layer->serversockfd, MAXBACKLOG);
  287. char msg[256];
  288. sprintf(msg, "Listening on %.*s\n", layer->discoveryUrl.length, layer->discoveryUrl.data);
  289. UA_LOG_INFO((*logger), UA_LOGGERCATEGORY_SERVER, msg);
  290. return UA_STATUSCODE_GOOD;
  291. }
  292. static UA_Int32 ServerNetworkLayerTCP_getWork(ServerNetworkLayerTCP *layer, UA_WorkItem **workItems,
  293. UA_UInt16 timeout) {
  294. UA_WorkItem *items = (void*)0;
  295. UA_Int32 itemsCount = removeAllConnections(layer, &items);
  296. setFDSet(layer);
  297. struct timeval tmptv = {0, timeout};
  298. UA_Int32 resultsize = select(layer->highestfd+1, &layer->fdset, NULL, NULL, &tmptv);
  299. if(resultsize < 0) {
  300. *workItems = items;
  301. return itemsCount;
  302. }
  303. // accept new connections (can only be a single one)
  304. if(FD_ISSET(layer->serversockfd,&layer->fdset)) {
  305. resultsize--;
  306. struct sockaddr_in cli_addr;
  307. socklen_t cli_len = sizeof(cli_addr);
  308. int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
  309. int i = 1;
  310. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY, (void *)&i, sizeof(i));
  311. if (newsockfd >= 0)
  312. ServerNetworkLayerTCP_add(layer, newsockfd);
  313. }
  314. items = realloc(items, sizeof(UA_WorkItem)*(itemsCount+resultsize));
  315. // read from established sockets
  316. UA_Int32 j = itemsCount;
  317. UA_ByteString buf = { -1, NULL};
  318. for(UA_Int32 i=0;i<layer->conLinksSize && j<itemsCount+resultsize;i++) {
  319. if(!(FD_ISSET(layer->conLinks[i].sockfd, &layer->fdset)))
  320. continue;
  321. if(!buf.data) {
  322. buf.data = malloc(sizeof(UA_Byte) * layer->conf.recvBufferSize);
  323. if(!buf.data)
  324. break;
  325. }
  326. #ifdef _WIN32
  327. buf.length = recv(layer->conLinks[i].sockfd, (char *)buf.data,
  328. layer->conf.recvBufferSize, 0);
  329. #else
  330. buf.length = read(layer->conLinks[i].sockfd, buf.data, layer->conf.recvBufferSize);
  331. #endif
  332. if (buf.length <= 0) {
  333. closeConnection(layer->conLinks[i].connection); // work is returned in the next iteration
  334. } else {
  335. items[j].type = UA_WORKITEMTYPE_BINARYNETWORKMESSAGE;
  336. items[j].work.binaryNetworkMessage.message = buf;
  337. items[j].work.binaryNetworkMessage.connection = &layer->conLinks[i].connection->connection;
  338. buf.data = NULL;
  339. j++;
  340. }
  341. }
  342. if(buf.data)
  343. free(buf.data);
  344. if(j == 0) {
  345. free(items);
  346. *workItems = NULL;
  347. } else
  348. *workItems = items;
  349. return j;
  350. }
  351. static UA_Int32 ServerNetworkLayerTCP_stop(ServerNetworkLayerTCP * layer, UA_WorkItem **workItems) {
  352. for(UA_Int32 index = 0;index < layer->conLinksSize;index++)
  353. closeConnection(layer->conLinks[index].connection);
  354. #ifdef _WIN32
  355. WSACleanup();
  356. #endif
  357. return removeAllConnections(layer, workItems);
  358. }
  359. static void ServerNetworkLayerTCP_delete(ServerNetworkLayerTCP *layer) {
  360. UA_String_deleteMembers(&layer->discoveryUrl);
  361. for(UA_Int32 i=0;i<layer->conLinksSize;++i){
  362. free(layer->conLinks[i].connection);
  363. }
  364. free(layer->conLinks);
  365. free(layer);
  366. }
  367. UA_ServerNetworkLayer ServerNetworkLayerTCP_new(UA_ConnectionConfig conf, UA_UInt32 port) {
  368. #ifdef _WIN32
  369. WORD wVersionRequested;
  370. WSADATA wsaData;
  371. wVersionRequested = MAKEWORD(2, 2);
  372. WSAStartup(wVersionRequested, &wsaData);
  373. #endif
  374. ServerNetworkLayerTCP *tcplayer = malloc(sizeof(ServerNetworkLayerTCP));
  375. tcplayer->conf = conf;
  376. tcplayer->conLinksSize = 0;
  377. tcplayer->conLinks = NULL;
  378. tcplayer->port = port;
  379. tcplayer->deleteLinkList = (void*)0;
  380. char hostname[256];
  381. gethostname(hostname, 255);
  382. UA_String_copyprintf("opc.tcp://%s:%d", &tcplayer->discoveryUrl, hostname, port);
  383. UA_ServerNetworkLayer nl;
  384. nl.nlHandle = tcplayer;
  385. nl.start = (UA_StatusCode (*)(void*, UA_Logger *logger))ServerNetworkLayerTCP_start;
  386. nl.getWork = (UA_Int32 (*)(void*, UA_WorkItem**, UA_UInt16))ServerNetworkLayerTCP_getWork;
  387. nl.stop = (UA_Int32 (*)(void*, UA_WorkItem**))ServerNetworkLayerTCP_stop;
  388. nl.free = (void (*)(void*))ServerNetworkLayerTCP_delete;
  389. nl.discoveryUrl = &tcplayer->discoveryUrl;
  390. return nl;
  391. }
  392. /***************************/
  393. /* Client NetworkLayer TCP */
  394. /***************************/
  395. static UA_StatusCode ClientNetworkLayerTCP_connect(const UA_String endpointUrl, ClientNetworkLayerTCP *resultHandle) {
  396. if(endpointUrl.length < 11 || endpointUrl.length >= 512) {
  397. printf("server url size invalid\n");
  398. return UA_STATUSCODE_BADINTERNALERROR;
  399. }
  400. if(strncmp((char*)endpointUrl.data, "opc.tcp://", 10) != 0) {
  401. printf("server url does not begin with opc.tcp://\n");
  402. return UA_STATUSCODE_BADINTERNALERROR;
  403. }
  404. //this is somewhat ugly, but atoi needs a c string
  405. char cstringEndpointUrl[endpointUrl.length+1];
  406. memset(cstringEndpointUrl, 0, endpointUrl.length+1);
  407. memcpy(cstringEndpointUrl, endpointUrl.data, endpointUrl.length);
  408. cstringEndpointUrl[endpointUrl.length+1] = '0';
  409. UA_UInt16 portpos = 9;
  410. UA_UInt16 port = 0;
  411. for(;portpos < endpointUrl.length; portpos++) {
  412. if(endpointUrl.data[portpos] == ':') {
  413. port = atoi(&cstringEndpointUrl[portpos+1]);
  414. break;
  415. }
  416. }
  417. if(port == 0) {
  418. printf("port invalid");
  419. return UA_STATUSCODE_BADINTERNALERROR;
  420. }
  421. char hostname[512];
  422. for(int i=10; i < portpos; i++)
  423. hostname[i-10] = endpointUrl.data[i];
  424. hostname[portpos-10] = 0;
  425. #ifdef _WIN32
  426. UA_UInt32 sock = 0;
  427. #else
  428. UA_Int32 sock = 0;
  429. #endif
  430. #ifdef _WIN32
  431. WORD wVersionRequested;
  432. WSADATA wsaData;
  433. wVersionRequested = MAKEWORD(2, 2);
  434. WSAStartup(wVersionRequested, &wsaData);
  435. if((sock = socket(PF_INET, SOCK_STREAM,0)) == INVALID_SOCKET) {
  436. #else
  437. if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  438. #endif
  439. printf("Could not create socket\n");
  440. return UA_STATUSCODE_BADINTERNALERROR;
  441. }
  442. struct hostent *server;
  443. server = gethostbyname(hostname);
  444. if (server == NULL) {
  445. printf("DNS lookup of %s failed\n", hostname);
  446. return UA_STATUSCODE_BADINTERNALERROR;
  447. }
  448. struct sockaddr_in server_addr;
  449. memset(&server_addr, 0, sizeof(server_addr));
  450. memcpy((char *)&server_addr.sin_addr.s_addr,
  451. (char *)server->h_addr_list[0],
  452. server->h_length);
  453. server_addr.sin_family = AF_INET;
  454. server_addr.sin_port = htons(port);
  455. if(connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
  456. printf("Connect failed.\n");
  457. return UA_STATUSCODE_BADINTERNALERROR;
  458. }
  459. //if(setNonBlocking(*sock) != UA_STATUSCODE_GOOD) {
  460. // printf("Could not switch to nonblocking.\n");
  461. // FINALLY
  462. // return UA_STATUSCODE_BADINTERNALERROR;
  463. //}
  464. resultHandle->sockfd = sock;
  465. return UA_STATUSCODE_GOOD;
  466. }
  467. static void ClientNetworkLayerTCP_disconnect(ClientNetworkLayerTCP* handle) {
  468. CLOSESOCKET(handle->sockfd);
  469. #ifdef _WIN32
  470. WSACleanup();
  471. #endif
  472. }
  473. static UA_StatusCode ClientNetworkLayerTCP_send(ClientNetworkLayerTCP *handle, UA_ByteStringArray gather_buf) {
  474. UA_UInt32 total_len = 0, nWritten = 0;
  475. #ifdef _WIN32
  476. LPWSABUF buf = _alloca(gather_buf.stringsSize * sizeof(WSABUF));
  477. int result = 0;
  478. for(UA_UInt32 i = 0; i<gather_buf.stringsSize; i++) {
  479. buf[i].buf = (char*)gather_buf.strings[i].data;
  480. buf[i].len = gather_buf.strings[i].length;
  481. total_len += gather_buf.strings[i].length;
  482. }
  483. while(nWritten < total_len) {
  484. UA_UInt32 n = 0;
  485. do {
  486. result = WSASend(handle->sockfd, buf, gather_buf.stringsSize ,
  487. (LPDWORD)&n, 0, NULL, NULL);
  488. if(result != 0)
  489. printf("Error WSASend, code: %d \n", WSAGetLastError());
  490. } while(errno == EINTR);
  491. nWritten += n;
  492. }
  493. #else
  494. struct iovec iov[gather_buf.stringsSize];
  495. for(UA_UInt32 i=0;i<gather_buf.stringsSize;i++) {
  496. iov[i] = (struct iovec) {.iov_base = gather_buf.strings[i].data,
  497. .iov_len = gather_buf.strings[i].length};
  498. total_len += gather_buf.strings[i].length;
  499. }
  500. struct msghdr message = {.msg_name = NULL, .msg_namelen = 0, .msg_iov = iov,
  501. .msg_iovlen = gather_buf.stringsSize, .msg_control = NULL,
  502. .msg_controllen = 0, .msg_flags = 0};
  503. while (nWritten < total_len) {
  504. int n = sendmsg(handle->sockfd, &message, 0);
  505. if(n <= -1)
  506. return UA_STATUSCODE_BADINTERNALERROR;
  507. nWritten += n;
  508. }
  509. #endif
  510. return UA_STATUSCODE_GOOD;
  511. }
  512. static UA_StatusCode
  513. ClientNetworkLayerTCP_awaitResponse(ClientNetworkLayerTCP *handle, UA_ByteString *response,
  514. UA_UInt32 timeout) {
  515. struct timeval tmptv = {0, timeout};
  516. setsockopt(handle->sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tmptv,sizeof(struct timeval));
  517. int ret = recv(handle->sockfd, (char*)response->data, response->length, 0);
  518. if(ret <= -1)
  519. return UA_STATUSCODE_BADINTERNALERROR;
  520. if(ret == 0)
  521. return UA_STATUSCODE_BADSERVERNOTCONNECTED;
  522. response->length = ret;
  523. return UA_STATUSCODE_GOOD;
  524. }
  525. static void ClientNetworkLayerTCP_delete(ClientNetworkLayerTCP *layer) {
  526. if(layer)
  527. free(layer);
  528. }
  529. UA_ClientNetworkLayer ClientNetworkLayerTCP_new(UA_ConnectionConfig conf) {
  530. ClientNetworkLayerTCP *tcplayer = malloc(sizeof(ClientNetworkLayerTCP));
  531. tcplayer->sockfd = 0;
  532. UA_ClientNetworkLayer layer;
  533. layer.nlHandle = tcplayer;
  534. layer.connect = (UA_StatusCode (*)(const UA_String, void**)) ClientNetworkLayerTCP_connect;
  535. layer.disconnect = (void (*)(void*)) ClientNetworkLayerTCP_disconnect;
  536. layer.delete = (void (*)(void*)) ClientNetworkLayerTCP_delete;
  537. layer.send = (UA_StatusCode (*)(void*, UA_ByteStringArray)) ClientNetworkLayerTCP_send;
  538. layer.awaitResponse = (UA_StatusCode (*)(void*, UA_ByteString *, UA_UInt32))ClientNetworkLayerTCP_awaitResponse;
  539. return layer;
  540. }