networklayer_tcp.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. typedef struct TCPConnection {
  27. UA_Int32 sockfd;
  28. UA_Connection connection;
  29. } TCPConnection;
  30. struct NetworklayerTCP {
  31. UA_ConnectionConfig localConf;
  32. UA_UInt32 port;
  33. fd_set fdset;
  34. UA_Int32 serversockfd;
  35. UA_Int32 highestfd;
  36. UA_UInt32 connectionsSize;
  37. TCPConnection *connections;
  38. };
  39. /** This structure is stored in the UA_Connection for callbacks into the
  40. network layer. */
  41. typedef struct TCPConnectionHandle {
  42. UA_Int32 sockfd;
  43. NetworklayerTCP *layer;
  44. } TCPConnectionHandle;
  45. UA_Int32 NetworklayerTCP_new(NetworklayerTCP **newlayer, UA_ConnectionConfig localConf,
  46. UA_UInt32 port) {
  47. *newlayer = malloc(sizeof(NetworklayerTCP));
  48. if(newlayer == UA_NULL)
  49. return UA_ERROR;
  50. (*newlayer)->localConf = localConf;
  51. (*newlayer)->port = port;
  52. (*newlayer)->connectionsSize = 0;
  53. (*newlayer)->connections = UA_NULL;
  54. return UA_SUCCESS;
  55. }
  56. // copy the array of connections, but _loose_ one. This does not close the
  57. // actual socket.
  58. UA_Int32 NetworklayerTCP_remove(NetworklayerTCP *layer, UA_Int32 sockfd) {
  59. UA_UInt32 index;
  60. for(index = 0;index < layer->connectionsSize;index++) {
  61. if(layer->connections[index].sockfd == sockfd)
  62. break;
  63. }
  64. UA_Connection_deleteMembers(&layer->connections[index].connection);
  65. TCPConnection *newconnections;
  66. newconnections = malloc(sizeof(TCPConnection) * (layer->connectionsSize-1));
  67. memcpy(newconnections, &layer->connections, sizeof(TCPConnection) * index);
  68. memcpy(&newconnections[index], &layer->connections[index+1],
  69. sizeof(TCPConnection) * (layer->connectionsSize - index - 1));
  70. layer->connections = newconnections;
  71. layer->connectionsSize--;
  72. return UA_SUCCESS;
  73. }
  74. void NetworklayerTCP_delete(NetworklayerTCP *layer) {
  75. for(UA_UInt32 index = 0;index < layer->connectionsSize;index++) {
  76. shutdown(layer->connections[index].sockfd, 2);
  77. UA_Connection_deleteMembers(&layer->connections[index].connection);
  78. CLOSESOCKET(layer->connections[index].sockfd);
  79. }
  80. free(layer->connections);
  81. free(layer);
  82. }
  83. /** Callback function */
  84. void closeCallback(TCPConnectionHandle *handle) {
  85. shutdown(handle->sockfd,2);
  86. CLOSESOCKET(handle->sockfd);
  87. NetworklayerTCP_remove(handle->layer, handle->sockfd);
  88. }
  89. /** Callback function */
  90. UA_Int32 writeCallback(TCPConnectionHandle *handle, UA_ByteStringArray gather_buf) {
  91. UA_UInt32 total_len = 0;
  92. UA_UInt32 nWritten = 0;
  93. #ifdef WIN32
  94. LPWSABUF buf = malloc(gather_buf.stringsSize * sizeof(WSABUF));
  95. int result = 0;
  96. for(UA_UInt32 i = 0; i<gather_buf.stringsSize; i++) {
  97. buf[i].buf = gather_buf.strings[i].data;
  98. buf[i].len = gather_buf.strings[i].length;
  99. total_len += gather_buf.strings[i].length;
  100. }
  101. while (nWritten < total_len) {
  102. UA_UInt32 n=0;
  103. do {
  104. result = WSASend(handle->sockfd, buf, gather_buf.stringsSize , (LPDWORD)&n, 0, NULL, NULL);
  105. if(result != 0)
  106. printf("NL_TCP_Writer - Error WSASend, code: %d \n", WSAGetLastError());
  107. } while (errno == EINTR);
  108. nWritten += n;
  109. }
  110. free(buf);
  111. #else
  112. struct iovec iov[gather_buf.stringsSize];
  113. for(UA_UInt32 i=0;i<gather_buf.stringsSize;i++) {
  114. iov[i].iov_base = gather_buf.strings[i].data;
  115. iov[i].iov_len = gather_buf.strings[i].length;
  116. total_len += gather_buf.strings[i].length;
  117. }
  118. struct msghdr message = {.msg_name = UA_NULL, .msg_namelen = 0, .msg_iov = iov,
  119. .msg_iovlen = gather_buf.stringsSize, .msg_control = UA_NULL,
  120. .msg_controllen = 0, .msg_flags = 0};
  121. while (nWritten < total_len) {
  122. UA_Int32 n = 0;
  123. do {
  124. n = sendmsg(handle->sockfd, &message, 0);
  125. } while (n == -1L && errno == EINTR);
  126. if (n >= 0) {
  127. // TODO: handle incompletely send messages
  128. /* nWritten += n; */
  129. break;
  130. } else {
  131. // TODO: error handling
  132. break;
  133. }
  134. }
  135. #endif
  136. return UA_SUCCESS;
  137. }
  138. UA_Int32 NetworklayerTCP_add(NetworklayerTCP *layer, UA_Int32 newsockfd) {
  139. layer->connectionsSize++;
  140. layer->connections = realloc(layer->connections, sizeof(TCPConnection) * layer->connectionsSize);
  141. TCPConnection *newconnection = &layer->connections[layer->connectionsSize-1];
  142. newconnection->sockfd = newsockfd;
  143. struct TCPConnectionHandle *callbackhandle;
  144. callbackhandle = malloc(sizeof(struct TCPConnectionHandle));
  145. callbackhandle->layer = layer;
  146. callbackhandle->sockfd = newsockfd;
  147. UA_Connection_init(&newconnection->connection, layer->localConf, callbackhandle,
  148. (UA_Connection_closeCallback)closeCallback, (UA_Connection_writeCallback)writeCallback);
  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. readBuffer.data = malloc(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. layer->highestfd++;
  223. }
  224. UA_Int32 NetworkLayerTCP_run(NetworklayerTCP *layer, UA_Server *server, struct timeval tv,
  225. void(*worker)(UA_Server*), UA_Boolean *running) {
  226. #ifdef WIN32
  227. WORD wVersionRequested;
  228. WSADATA wsaData;
  229. wVersionRequested = MAKEWORD(2, 2);
  230. WSAStartup(wVersionRequested, &wsaData);
  231. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == INVALID_SOCKET) {
  232. printf("ERROR opening socket, code: %d\n", WSAGetLastError());
  233. return UA_ERROR;
  234. }
  235. #else
  236. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  237. perror("ERROR opening socket");
  238. return UA_ERROR;
  239. }
  240. #endif
  241. struct sockaddr_in serv_addr;
  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(layer->serversockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
  248. perror("setsockopt");
  249. close(layer->serversockfd);
  250. return UA_ERROR;
  251. }
  252. if(bind(layer->serversockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  253. perror("binding");
  254. close(layer->serversockfd);
  255. return UA_ERROR;
  256. }
  257. #define MAXBACKLOG 10
  258. setNonBlocking(layer->serversockfd);
  259. listen(layer->serversockfd, MAXBACKLOG);
  260. while (*running) {
  261. setFDSet(layer);
  262. struct timeval tmptv = tv;
  263. UA_Int32 resultsize = select(layer->highestfd, &layer->fdset, UA_NULL, UA_NULL, &tmptv);
  264. if (resultsize <= 0) {
  265. #ifdef WIN32
  266. UA_Int32 err = (resultsize == SOCKET_ERROR) ? WSAGetLastError() : 0;
  267. switch (err) {
  268. case WSANOTINITIALISED:
  269. case WSAEFAULT:
  270. case WSAENETDOWN:
  271. case WSAEINVAL:
  272. case WSAEINTR:
  273. case WSAEINPROGRESS:
  274. case WSAENOTSOCK:
  275. #else
  276. UA_Int32 err = errno;
  277. switch (err) {
  278. case EBADF:
  279. case EINTR:
  280. case EINVAL:
  281. #endif
  282. // todo: handle errors
  283. printf("UA_Stack_msgLoop - result=%d, errno={%d,%s}\n", resultsize, errno, strerror(errno));
  284. break;
  285. default:
  286. // timeout
  287. worker(server);
  288. }
  289. } else { // activity on listener or client socket
  290. worksocks(layer, server, resultsize);
  291. worker(server);
  292. }
  293. }
  294. #ifdef WIN32
  295. WSACleanup();
  296. #endif
  297. return UA_SUCCESS;
  298. }