networklayer_tcp.c 9.3 KB

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