networklayer_tcp.c 9.5 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 <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. free(layer->connections);
  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. free(layer->connections);
  83. 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_buf.stringsSize , (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. for(UA_UInt32 i=0;i<gather_buf.stringsSize;i++)
  139. free(gather_buf.strings[i].data);
  140. return UA_SUCCESS;
  141. }
  142. UA_Int32 NetworklayerTCP_add(NetworklayerTCP *layer, UA_Int32 newsockfd) {
  143. layer->connectionsSize++;
  144. layer->connections = realloc(layer->connections, sizeof(TCPConnection) * layer->connectionsSize);
  145. TCPConnection *newconnection = &layer->connections[layer->connectionsSize-1];
  146. newconnection->sockfd = newsockfd;
  147. struct TCPConnectionHandle *callbackhandle;
  148. callbackhandle = malloc(sizeof(struct TCPConnectionHandle));
  149. callbackhandle->layer = layer;
  150. callbackhandle->sockfd = newsockfd;
  151. UA_Connection_init(&newconnection->connection, layer->localConf, callbackhandle,
  152. (UA_Connection_closeCallback)closeCallback, (UA_Connection_writeCallback)writeCallback);
  153. return UA_SUCCESS;
  154. }
  155. UA_Int32 setNonBlocking(int sockid) {
  156. #ifdef WIN32
  157. u_long iMode = 1;
  158. int opts = IOCTLSOCKET(sockid, FIONBIO, &iMode);
  159. if (opts != NO_ERROR){
  160. printf("ioctlsocket failed with error: %ld\n", opts);
  161. return - 1;
  162. }
  163. return 0;
  164. #else
  165. int opts = fcntl(sockid,F_GETFL);
  166. if (opts < 0) {
  167. perror("fcntl(F_GETFL)");
  168. return -1;
  169. }
  170. opts = (opts | O_NONBLOCK);
  171. if (fcntl(sockid,F_SETFL,opts) < 0) {
  172. perror("fcntl(F_SETFL)");
  173. return -1;
  174. }
  175. return 0;
  176. #endif
  177. }
  178. void readConnection(NetworklayerTCP *layer, UA_Server *server, TCPConnection *entry) {
  179. UA_ByteString readBuffer;
  180. readBuffer.data = malloc(layer->localConf.recvBufferSize);
  181. #ifdef WIN32
  182. readBuffer.length = recv(entry->sockfd, (char *)readBuffer.data,
  183. layer->localConf.recvBufferSize, 0);
  184. #else
  185. readBuffer.length = read(entry->sockfd, readBuffer.data, layer->localConf.recvBufferSize);
  186. #endif
  187. if (errno != 0) {
  188. shutdown(entry->sockfd,2);
  189. CLOSESOCKET(entry->sockfd);
  190. NetworklayerTCP_remove(layer, entry->sockfd);
  191. } else {
  192. if(readBuffer.length>0){ //data received to process?
  193. UA_Server_processBinaryMessage(server, &entry->connection, &readBuffer);
  194. }
  195. }
  196. UA_ByteString_deleteMembers(&readBuffer);
  197. }
  198. void worksocks(NetworklayerTCP *layer, UA_Server *server, UA_UInt32 workamount) {
  199. // accept new connections
  200. if(FD_ISSET(layer->serversockfd,&layer->fdset)) {
  201. struct sockaddr_in cli_addr;
  202. socklen_t cli_len = sizeof(cli_addr);
  203. int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
  204. if (newsockfd >= 0) {
  205. setNonBlocking(newsockfd);
  206. NetworklayerTCP_add(layer, newsockfd);
  207. }
  208. workamount--;
  209. }
  210. // read from established sockets
  211. for(UA_UInt32 i=0;i<layer->connectionsSize && workamount > 0;i++) {
  212. if(FD_ISSET(layer->connections[i].sockfd, &layer->fdset)) {
  213. readConnection(layer, server, &layer->connections[i]);
  214. workamount--;
  215. }
  216. }
  217. }
  218. // after every select, reset the set of sockets we want to listen on
  219. void setFDSet(NetworklayerTCP *layer) {
  220. FD_ZERO(&layer->fdset);
  221. FD_SET(layer->serversockfd, &layer->fdset);
  222. layer->highestfd = layer->serversockfd;
  223. for(UA_UInt32 i=0;i<layer->connectionsSize;i++) {
  224. FD_SET(layer->connections[i].sockfd, &layer->fdset);
  225. if(layer->connections[i].sockfd > layer->highestfd)
  226. layer->highestfd = layer->connections[i].sockfd;
  227. }
  228. layer->highestfd++;
  229. }
  230. UA_Int32 NetworkLayerTCP_run(NetworklayerTCP *layer, UA_Server *server, struct timeval tv,
  231. void(*worker)(UA_Server*), UA_Boolean *running) {
  232. #ifdef WIN32
  233. WORD wVersionRequested;
  234. WSADATA wsaData;
  235. wVersionRequested = MAKEWORD(2, 2);
  236. WSAStartup(wVersionRequested, &wsaData);
  237. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == INVALID_SOCKET) {
  238. printf("ERROR opening socket, code: %d\n", WSAGetLastError());
  239. return UA_ERROR;
  240. }
  241. #else
  242. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  243. perror("ERROR opening socket");
  244. return UA_ERROR;
  245. }
  246. #endif
  247. struct sockaddr_in serv_addr;
  248. memset((void *)&serv_addr, sizeof(serv_addr), 1);
  249. serv_addr.sin_family = AF_INET;
  250. serv_addr.sin_addr.s_addr = INADDR_ANY;
  251. serv_addr.sin_port = htons(layer->port);
  252. int optval = 1;
  253. if(setsockopt(layer->serversockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
  254. perror("setsockopt");
  255. close(layer->serversockfd);
  256. return UA_ERROR;
  257. }
  258. if(bind(layer->serversockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  259. perror("binding");
  260. close(layer->serversockfd);
  261. return UA_ERROR;
  262. }
  263. #define MAXBACKLOG 10
  264. setNonBlocking(layer->serversockfd);
  265. listen(layer->serversockfd, MAXBACKLOG);
  266. while (*running) {
  267. setFDSet(layer);
  268. struct timeval tmptv = tv;
  269. UA_Int32 resultsize = select(layer->highestfd, &layer->fdset, UA_NULL, UA_NULL, &tmptv);
  270. if (resultsize <= 0) {
  271. #ifdef WIN32
  272. UA_Int32 err = (resultsize == SOCKET_ERROR) ? WSAGetLastError() : 0;
  273. switch (err) {
  274. case WSANOTINITIALISED:
  275. case WSAEFAULT:
  276. case WSAENETDOWN:
  277. case WSAEINVAL:
  278. case WSAEINTR:
  279. case WSAEINPROGRESS:
  280. case WSAENOTSOCK:
  281. #else
  282. UA_Int32 err = errno;
  283. switch (err) {
  284. case EBADF:
  285. case EINTR:
  286. case EINVAL:
  287. #endif
  288. // todo: handle errors
  289. printf("UA_Stack_msgLoop - result=%d, errno={%d,%s}\n", resultsize, errno, strerror(errno));
  290. break;
  291. default:
  292. // timeout
  293. worker(server);
  294. }
  295. } else { // activity on listener or client socket
  296. worksocks(layer, server, resultsize);
  297. worker(server);
  298. }
  299. }
  300. #ifdef WIN32
  301. WSACleanup();
  302. #endif
  303. return UA_SUCCESS;
  304. }