networklayer_tcp.c 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 <stdio.h>
  23. #include <errno.h> // errno, EINTR
  24. #include <memory.h> // memset
  25. #include <fcntl.h> // fcntl
  26. #include "networklayer_tcp.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. *newlayer = malloc(sizeof(NetworklayerTCP));
  49. if(newlayer == UA_NULL)
  50. return UA_ERROR;
  51. (*newlayer)->localConf = localConf;
  52. (*newlayer)->port = port;
  53. (*newlayer)->connectionsSize = 0;
  54. (*newlayer)->connections = UA_NULL;
  55. return UA_SUCCESS;
  56. }
  57. // copy the array of connections, but _loose_ one. This does not close the
  58. // actual socket.
  59. UA_Int32 NetworklayerTCP_remove(NetworklayerTCP *layer, UA_Int32 sockfd) {
  60. UA_UInt32 index;
  61. for(index = 0;index < layer->connectionsSize;index++) {
  62. if(layer->connections[index].sockfd == sockfd)
  63. break;
  64. }
  65. UA_Connection_deleteMembers(&layer->connections[index].connection);
  66. TCPConnection *newconnections;
  67. newconnections = malloc(sizeof(TCPConnection) * (layer->connectionsSize-1));
  68. memcpy(newconnections, &layer->connections, sizeof(TCPConnection) * index);
  69. memcpy(&newconnections[index], &layer->connections[index+1],
  70. sizeof(TCPConnection) * (layer->connectionsSize - index - 1));
  71. layer->connections = newconnections;
  72. layer->connectionsSize--;
  73. return UA_SUCCESS;
  74. }
  75. void NetworklayerTCP_delete(NetworklayerTCP *layer) {
  76. for(UA_UInt32 index = 0;index < layer->connectionsSize;index++) {
  77. shutdown(layer->connections[index].sockfd, 2);
  78. UA_Connection_deleteMembers(&layer->connections[index].connection);
  79. CLOSESOCKET(layer->connections[index].sockfd);
  80. }
  81. free(layer->connections);
  82. free(layer);
  83. }
  84. /** Callback function */
  85. void closeCallback(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 writeCallback(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_buf.stringsSize , (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->connectionsSize++;
  141. layer->connections = realloc(layer->connections, sizeof(TCPConnection) * layer->connectionsSize);
  142. TCPConnection *newconnection = &layer->connections[layer->connectionsSize-1];
  143. newconnection->sockfd = newsockfd;
  144. struct TCPConnectionHandle *callbackhandle;
  145. callbackhandle = malloc(sizeof(struct TCPConnectionHandle));
  146. callbackhandle->layer = layer;
  147. callbackhandle->sockfd = newsockfd;
  148. UA_Connection_init(&newconnection->connection, layer->localConf, callbackhandle,
  149. (UA_Connection_closeCallback)closeCallback, (UA_Connection_writeCallback)writeCallback);
  150. return UA_SUCCESS;
  151. }
  152. UA_Int32 setNonBlocking(int sockid) {
  153. #ifdef WIN32
  154. u_long iMode = 1;
  155. int opts = IOCTLSOCKET(sockid, FIONBIO, &iMode);
  156. if (opts != NO_ERROR){
  157. printf("ioctlsocket failed with error: %ld\n", opts);
  158. return - 1;
  159. }
  160. return 0;
  161. #else
  162. int opts = fcntl(sockid,F_GETFL);
  163. if (opts < 0) {
  164. perror("fcntl(F_GETFL)");
  165. return -1;
  166. }
  167. opts = (opts | O_NONBLOCK);
  168. if (fcntl(sockid,F_SETFL,opts) < 0) {
  169. perror("fcntl(F_SETFL)");
  170. return -1;
  171. }
  172. return 0;
  173. #endif
  174. }
  175. void readConnection(NetworklayerTCP *layer, UA_Server *server, TCPConnection *entry) {
  176. UA_ByteString readBuffer;
  177. readBuffer.data = malloc(layer->localConf.recvBufferSize);
  178. #ifdef WIN32
  179. readBuffer.length = recv(entry->sockfd, (char *)readBuffer.data,
  180. layer->localConf.recvBufferSize, 0);
  181. #else
  182. readBuffer.length = read(entry->sockfd, readBuffer.data, layer->localConf.recvBufferSize);
  183. #endif
  184. if (errno != 0) {
  185. shutdown(entry->sockfd,2);
  186. CLOSESOCKET(entry->sockfd);
  187. NetworklayerTCP_remove(layer, entry->sockfd);
  188. } else {
  189. UA_Server_processBinaryMessage(server, &entry->connection, &readBuffer);
  190. }
  191. UA_ByteString_deleteMembers(&readBuffer);
  192. }
  193. void worksocks(NetworklayerTCP *layer, UA_Server *server, UA_UInt32 workamount) {
  194. // accept new connections
  195. if(FD_ISSET(layer->serversockfd,&layer->fdset)) {
  196. struct sockaddr_in cli_addr;
  197. socklen_t cli_len = sizeof(cli_addr);
  198. int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
  199. if (newsockfd >= 0) {
  200. setNonBlocking(newsockfd);
  201. NetworklayerTCP_add(layer, newsockfd);
  202. }
  203. workamount--;
  204. }
  205. // read from established sockets
  206. for(UA_UInt32 i=0;i<layer->connectionsSize && workamount > 0;i++) {
  207. if(FD_ISSET(layer->connections[i].sockfd, &layer->fdset)) {
  208. readConnection(layer, server, &layer->connections[i]);
  209. workamount--;
  210. }
  211. }
  212. }
  213. // after every select, reset the set of sockets we want to listen on
  214. void setFDSet(NetworklayerTCP *layer) {
  215. FD_ZERO(&layer->fdset);
  216. FD_SET(layer->serversockfd, &layer->fdset);
  217. layer->highestfd = layer->serversockfd;
  218. for(UA_UInt32 i=0;i<layer->connectionsSize;i++) {
  219. FD_SET(layer->connections[i].sockfd, &layer->fdset);
  220. if(layer->connections[i].sockfd > layer->highestfd)
  221. layer->highestfd = layer->connections[i].sockfd;
  222. }
  223. layer->highestfd++;
  224. }
  225. UA_Int32 NetworkLayerTCP_run(NetworklayerTCP *layer, UA_Server *server, struct timeval tv,
  226. void(*worker)(UA_Server*), UA_Boolean *running) {
  227. #ifdef WIN32
  228. WORD wVersionRequested;
  229. WSADATA wsaData;
  230. wVersionRequested = MAKEWORD(2, 2);
  231. WSAStartup(wVersionRequested, &wsaData);
  232. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == INVALID_SOCKET) {
  233. printf("ERROR opening socket, code: %d\n", WSAGetLastError());
  234. return UA_ERROR;
  235. }
  236. #else
  237. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  238. perror("ERROR opening socket");
  239. return UA_ERROR;
  240. }
  241. #endif
  242. struct sockaddr_in serv_addr;
  243. memset((void *)&serv_addr, sizeof(serv_addr), 1);
  244. serv_addr.sin_family = AF_INET;
  245. serv_addr.sin_addr.s_addr = INADDR_ANY;
  246. serv_addr.sin_port = htons(layer->port);
  247. int optval = 1;
  248. if(setsockopt(layer->serversockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
  249. perror("setsockopt");
  250. close(layer->serversockfd);
  251. return UA_ERROR;
  252. }
  253. if(bind(layer->serversockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  254. perror("binding");
  255. close(layer->serversockfd);
  256. return UA_ERROR;
  257. }
  258. #define MAXBACKLOG 10
  259. setNonBlocking(layer->serversockfd);
  260. listen(layer->serversockfd, 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 = (resultsize == 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. }