networklayer_tcp.c 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. #ifdef WIN32
  2. #include <winsock2.h>
  3. #include <sys/types.h>
  4. #include <Windows.h>
  5. #include <ws2tcpip.h>
  6. #define CLOSESOCKET(S) closesocket(S)
  7. #define IOCTLSOCKET ioctlsocket
  8. #else
  9. #include <sys/select.h>
  10. #include <sys/socket.h>
  11. #include <netinet/in.h>
  12. #include <sys/socketvar.h>
  13. #include <unistd.h> // read, write, close
  14. #define CLOSESOCKET(S) close(S)
  15. #define IOCTLSOCKET ioctl
  16. #endif /* WIN32 */
  17. #include <stdlib.h> // exit
  18. #include <errno.h> // errno, EINTR
  19. #include <memory.h> // memset
  20. #include <fcntl.h> // fcntl
  21. #include "networklayer_tcp.h"
  22. #include "ua_transport.h"
  23. typedef struct TCPConnection {
  24. UA_Int32 sockfd;
  25. UA_Connection connection;
  26. } TCPConnection;
  27. struct NetworklayerTCP {
  28. UA_ConnectionConfig localConf;
  29. UA_UInt32 port;
  30. fd_set fdset;
  31. UA_Int32 serversockfd;
  32. UA_Int32 highestfd;
  33. UA_UInt32 connectionsSize;
  34. TCPConnection *connections;
  35. };
  36. /** This structure is stored in the UA_Connection for callbacks into the
  37. network layer. */
  38. typedef struct TCPConnectionHandle {
  39. UA_Int32 sockfd;
  40. NetworklayerTCP *layer;
  41. } TCPConnectionHandle;
  42. UA_Int32 NetworklayerTCP_new(NetworklayerTCP **newlayer, UA_ConnectionConfig localConf,
  43. UA_UInt32 port) {
  44. UA_alloc((void**)newlayer, sizeof(NetworklayerTCP));
  45. (*newlayer)->localConf = localConf;
  46. (*newlayer)->port = port;
  47. (*newlayer)->connectionsSize = 0;
  48. (*newlayer)->connections = UA_NULL;
  49. return UA_SUCCESS;
  50. }
  51. // copy the array of connections, but _loose_ one. This does not close the
  52. // actual socket.
  53. UA_Int32 NetworklayerTCP_remove(NetworklayerTCP *layer, UA_Int32 sockfd) {
  54. UA_UInt32 index;
  55. for(index = 0;index < layer->connectionsSize;index++) {
  56. if(layer->connections[index].sockfd == sockfd)
  57. break;
  58. }
  59. UA_Connection_deleteMembers(&layer->connections[index].connection);
  60. TCPConnection *newconnections;
  61. UA_alloc((void**)&newconnections, sizeof(TCPConnection) * (layer->connectionsSize-1));
  62. UA_memcpy(newconnections, &layer->connections, sizeof(TCPConnection) * index);
  63. UA_memcpy(&newconnections[index], &layer->connections[index+1],
  64. sizeof(TCPConnection) * (layer->connectionsSize - index - 1));
  65. layer->connections = newconnections;
  66. layer->connectionsSize--;
  67. return UA_SUCCESS;
  68. }
  69. void NetworklayerTCP_delete(NetworklayerTCP *layer) {
  70. for(UA_UInt32 index = 0;index < layer->connectionsSize;index++) {
  71. shutdown(layer->connections[index].sockfd, 2);
  72. CLOSESOCKET(layer->connections[index].sockfd);
  73. }
  74. UA_free(layer->connections);
  75. UA_free(layer);
  76. }
  77. /** Callback function */
  78. void closeHandle(TCPConnectionHandle *handle) {
  79. shutdown(handle->sockfd,2);
  80. CLOSESOCKET(handle->sockfd);
  81. NetworklayerTCP_remove(handle->layer, handle->sockfd);
  82. }
  83. /** Callback function */
  84. UA_Int32 writeHandle(TCPConnectionHandle *handle, UA_ByteStringArray gather_buf) {
  85. UA_UInt32 total_len = 0;
  86. UA_UInt32 nWritten = 0;
  87. #ifdef WIN32
  88. LPWSABUF buf = malloc(gather_buf.stringsSize * sizeof(WSABUF));
  89. int result = 0;
  90. for(UA_UInt32 i = 0; i<gather_buf.stringsSize; i++) {
  91. buf[i].buf = gather_buf.strings[i].data;
  92. buf[i].len = gather_buf.strings[i].length;
  93. total_len += gather_buf.strings[i].length;
  94. }
  95. while (nWritten < total_len) {
  96. UA_UInt32 n=0;
  97. do {
  98. result = WSASend(handle->sockfd, buf, gather_len , (LPDWORD)&n, 0, NULL, NULL);
  99. if(result != 0)
  100. printf("NL_TCP_Writer - Error WSASend, code: %d \n", WSAGetLastError());
  101. } while (errno == EINTR);
  102. nWritten += n;
  103. }
  104. free(buf);
  105. #else
  106. struct iovec iov[gather_buf.stringsSize];
  107. for(UA_UInt32 i=0;i<gather_buf.stringsSize;i++) {
  108. iov[i].iov_base = gather_buf.strings[i].data;
  109. iov[i].iov_len = gather_buf.strings[i].length;
  110. total_len += gather_buf.strings[i].length;
  111. }
  112. struct msghdr message = {.msg_name = UA_NULL, .msg_namelen = 0, .msg_iov = iov,
  113. .msg_iovlen = gather_buf.stringsSize, .msg_control = UA_NULL,
  114. .msg_controllen = 0, .msg_flags = 0};
  115. while (nWritten < total_len) {
  116. UA_Int32 n = 0;
  117. do {
  118. n = sendmsg(handle->sockfd, &message, 0);
  119. } while (n == -1L && errno == EINTR);
  120. if (n >= 0) {
  121. nWritten += n;
  122. break;
  123. // TODO: handle incompletely send messages
  124. } else {
  125. // TODO: error handling
  126. break;
  127. }
  128. }
  129. #endif
  130. return UA_SUCCESS;
  131. }
  132. UA_Int32 NetworklayerTCP_add(NetworklayerTCP *layer, UA_Int32 newsockfd) {
  133. layer->connections = realloc(layer->connections,
  134. sizeof(TCPConnection) * layer->connectionsSize);
  135. TCPConnection *newconnection = &layer->connections[layer->connectionsSize];
  136. newconnection->sockfd = newsockfd;
  137. layer->connectionsSize++;
  138. struct TCPConnectionHandle *callbackhandle;
  139. UA_alloc((void**)&callbackhandle, sizeof(struct TCPConnectionHandle));
  140. callbackhandle->layer = layer;
  141. callbackhandle->sockfd = newsockfd;
  142. UA_Connection_init(&newconnection->connection, layer->localConf, callbackhandle,
  143. (UA_Int32 (*)(void*))closeHandle,
  144. (UA_Int32 (*)(void*, UA_ByteStringArray*))writeHandle);
  145. return UA_SUCCESS;
  146. }
  147. UA_Int32 setNonBlocking(int sockid) {
  148. #ifdef WIN32
  149. u_long iMode = 1;
  150. int opts = IOCTLSOCKET(sockid, FIONBIO, &iMode);
  151. if (opts != NO_ERROR){
  152. printf("ioctlsocket failed with error: %ld\n", opts);
  153. return - 1;
  154. }
  155. return 0;
  156. #else
  157. int opts = fcntl(sockid,F_GETFL);
  158. if (opts < 0) {
  159. perror("fcntl(F_GETFL)");
  160. return -1;
  161. }
  162. opts = (opts | O_NONBLOCK);
  163. if (fcntl(sockid,F_SETFL,opts) < 0) {
  164. perror("fcntl(F_SETFL)");
  165. return -1;
  166. }
  167. return 0;
  168. #endif
  169. }
  170. void readConnection(NetworklayerTCP *layer, UA_Server *server, TCPConnection *entry) {
  171. UA_ByteString readBuffer;
  172. UA_alloc((void**)&readBuffer.data, layer->localConf.recvBufferSize);
  173. #ifdef WIN32
  174. readBuffer.length = recv(entry->sockfd, (char *)readBuffer.data,
  175. layer->localConf.recvBufferSize, 0);
  176. #else
  177. readBuffer.length = read(entry->sockfd, readBuffer.data, layer->localConf.recvBufferSize);
  178. #endif
  179. if (errno != 0) {
  180. shutdown(entry->sockfd,2);
  181. CLOSESOCKET(entry->sockfd);
  182. NetworklayerTCP_remove(layer, entry->sockfd);
  183. } else {
  184. UA_Server_processBinaryMessage(server, &entry->connection, &readBuffer);
  185. }
  186. UA_ByteString_deleteMembers(&readBuffer);
  187. }
  188. void worksocks(NetworklayerTCP *layer, UA_Server *server, UA_UInt32 workamount) {
  189. // accept new connections
  190. if(FD_ISSET(layer->serversockfd,&layer->fdset)) {
  191. struct sockaddr_in cli_addr;
  192. socklen_t cli_len = sizeof(cli_addr);
  193. int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
  194. if (newsockfd >= 0) {
  195. setNonBlocking(newsockfd);
  196. NetworklayerTCP_add(layer, newsockfd);
  197. }
  198. workamount--;
  199. }
  200. // read from established sockets
  201. for(UA_UInt32 i=0;i<layer->connectionsSize && workamount > 0;i++) {
  202. if(FD_ISSET(layer->connections[i].sockfd, &layer->fdset)) {
  203. readConnection(layer, server, &layer->connections[i]);
  204. workamount--;
  205. }
  206. }
  207. }
  208. // after every select, reset the set of sockets we want to listen on
  209. void setFDSet(NetworklayerTCP *layer) {
  210. FD_ZERO(&layer->fdset);
  211. FD_SET(layer->serversockfd, &layer->fdset);
  212. layer->highestfd = layer->serversockfd;
  213. for(UA_UInt32 i=0;i<layer->connectionsSize;i++) {
  214. FD_SET(layer->connections[i].sockfd, &layer->fdset);
  215. if(layer->connections[i].sockfd > layer->highestfd)
  216. layer->highestfd = layer->connections[i].sockfd;
  217. }
  218. }
  219. UA_Int32 NetworkLayerTCP_run(NetworklayerTCP *layer, UA_Server *server, struct timeval tv,
  220. void(*worker)(UA_Server*), UA_Boolean *running) {
  221. struct sockaddr_in serv_addr;
  222. //UA_String_copyprintf("opc.tcp://localhost:%d/", &(tld->endpointUrl), port);
  223. #ifdef WIN32
  224. unsigned int newsockfd;
  225. WORD wVersionRequested;
  226. WSADATA wsaData;
  227. wVersionRequested = MAKEWORD(2, 2);
  228. WSAStartup(wVersionRequested, &wsaData);
  229. newsockfd = socket(PF_INET, SOCK_STREAM,0);
  230. if (newsockfd == INVALID_SOCKET) {
  231. printf("ERROR opening socket, code: %d\n", WSAGetLastError());
  232. return UA_ERROR;
  233. }
  234. #else
  235. int newsockfd;
  236. newsockfd = socket(PF_INET, SOCK_STREAM, 0);
  237. if (newsockfd < 0) {
  238. perror("ERROR opening socket");
  239. return UA_ERROR;
  240. }
  241. #endif
  242. memset((void *)&serv_addr, sizeof(serv_addr), 1);
  243. serv_addr.sin_family = AF_INET;
  244. serv_addr.sin_addr.s_addr = INADDR_ANY;
  245. serv_addr.sin_port = htons(layer->port);
  246. int optval = 1;
  247. if(setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval,
  248. sizeof(optval)) == -1) {
  249. perror("setsockopt");
  250. close(newsockfd);
  251. return UA_ERROR;
  252. }
  253. if(bind(newsockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  254. perror("binding");
  255. close(newsockfd);
  256. return UA_ERROR;
  257. }
  258. #define MAXBACKLOG 10
  259. setNonBlocking(newsockfd);
  260. listen(newsockfd, MAXBACKLOG);
  261. while (*running) {
  262. setFDSet(layer);
  263. struct timeval tmptv = tv;
  264. UA_Int32 resultsize = select(layer->highestfd, &layer->fdset, UA_NULL, UA_NULL, &tmptv);
  265. if (resultsize <= 0) {
  266. #ifdef WIN32
  267. UA_Int32 err = (result == SOCKET_ERROR) ? WSAGetLastError() : 0;
  268. switch (err) {
  269. case WSANOTINITIALISED:
  270. case WSAEFAULT:
  271. case WSAENETDOWN:
  272. case WSAEINVAL:
  273. case WSAEINTR:
  274. case WSAEINPROGRESS:
  275. case WSAENOTSOCK:
  276. #else
  277. UA_Int32 err = errno;
  278. switch (err) {
  279. case EBADF:
  280. case EINTR:
  281. case EINVAL:
  282. #endif
  283. // todo: handle errors
  284. printf("UA_Stack_msgLoop - result=%d, errno={%d,%s}\n", resultsize, errno, strerror(errno));
  285. break;
  286. default:
  287. // timeout
  288. worker(server);
  289. }
  290. } else { // activity on listener or client socket
  291. worksocks(layer, server, resultsize);
  292. worker(server);
  293. }
  294. }
  295. #ifdef WIN32
  296. WSACleanup();
  297. #endif
  298. return UA_SUCCESS;
  299. }