networklayer_tcp.c 9.4 KB

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