networklayer_tcp.c 9.4 KB

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