networklayer_tcp.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. #include <stdlib.h> // malloc, free
  6. #ifdef _WIN32
  7. #include <malloc.h>
  8. #include <winsock2.h>
  9. #include <sys/types.h>
  10. #include <windows.h>
  11. #include <ws2tcpip.h>
  12. #define CLOSESOCKET(S) closesocket(S)
  13. #else
  14. #include <sys/select.h>
  15. #include <netinet/in.h>
  16. #include <sys/socketvar.h>
  17. #include <sys/ioctl.h>
  18. #include <unistd.h> // read, write, close
  19. #include <arpa/inet.h>
  20. #define CLOSESOCKET(S) close(S)
  21. #endif
  22. #include <stdio.h>
  23. #include <errno.h> // errno, EINTR
  24. #include <fcntl.h> // fcntl
  25. #include "networklayer_tcp.h" // UA_MULTITHREADING is defined in here
  26. #ifdef UA_MULTITHREADING
  27. #include <urcu/uatomic.h>
  28. #endif
  29. #define MAXBACKLOG 100
  30. struct Networklayer_TCP;
  31. /* Forwarded to the server as a (UA_Connection) and used for callbacks back into
  32. the networklayer */
  33. typedef struct {
  34. UA_Connection connection;
  35. UA_Int32 sockfd;
  36. struct NetworkLayerTCP *layer;
  37. } TCPConnection;
  38. /* Internal mapping of sockets to connections */
  39. typedef struct {
  40. TCPConnection *connection;
  41. #ifdef _WIN32
  42. UA_UInt32 sockfd;
  43. #else
  44. UA_Int32 sockfd;
  45. #endif
  46. } ConnectionLink;
  47. typedef struct NetworkLayerTCP {
  48. UA_ConnectionConfig conf;
  49. fd_set fdset;
  50. #ifdef _WIN32
  51. UA_UInt32 serversockfd;
  52. UA_UInt32 highestfd;
  53. #else
  54. UA_Int32 serversockfd;
  55. UA_Int32 highestfd;
  56. #endif
  57. UA_UInt16 conLinksSize;
  58. ConnectionLink *conLinks;
  59. UA_UInt32 port;
  60. /* We remove the connection links only in the main thread. Attach
  61. to-be-deleted links with atomic operations */
  62. struct deleteLink {
  63. #ifdef _WIN32
  64. UA_UInt32 sockfd;
  65. #else
  66. UA_Int32 sockfd;
  67. #endif
  68. struct deleteLink *next;
  69. } *deleteLinkList;
  70. } NetworkLayerTCP;
  71. static UA_StatusCode setNonBlocking(int sockid) {
  72. #ifdef _WIN32
  73. u_long iMode = 1;
  74. if(ioctlsocket(sockid, FIONBIO, &iMode) != NO_ERROR)
  75. return UA_STATUSCODE_BADINTERNALERROR;
  76. #else
  77. int opts = fcntl(sockid,F_GETFL);
  78. if(opts < 0 || fcntl(sockid,F_SETFL,opts|O_NONBLOCK) < 0)
  79. return UA_STATUSCODE_BADINTERNALERROR;
  80. #endif
  81. return UA_STATUSCODE_GOOD;
  82. }
  83. static void freeConnectionCallback(UA_Server *server, TCPConnection *connection) {
  84. free(connection);
  85. }
  86. // after every select, reset the set of sockets we want to listen on
  87. static void setFDSet(NetworkLayerTCP *layer) {
  88. FD_ZERO(&layer->fdset);
  89. FD_SET(layer->serversockfd, &layer->fdset);
  90. layer->highestfd = layer->serversockfd;
  91. for(UA_Int32 i=0;i<layer->conLinksSize;i++) {
  92. FD_SET(layer->conLinks[i].sockfd, &layer->fdset);
  93. if(layer->conLinks[i].sockfd > layer->highestfd)
  94. layer->highestfd = layer->conLinks[i].sockfd;
  95. }
  96. }
  97. // the callbacks are thread-safe if UA_MULTITHREADING is defined
  98. void closeConnection(TCPConnection *handle);
  99. void writeCallback(TCPConnection *handle, UA_ByteStringArray gather_buf);
  100. static UA_StatusCode NetworkLayerTCP_add(NetworkLayerTCP *layer, UA_Int32 newsockfd) {
  101. setNonBlocking(newsockfd);
  102. TCPConnection *c = malloc(sizeof(TCPConnection));
  103. if(!c)
  104. return UA_STATUSCODE_BADINTERNALERROR;
  105. c->sockfd = newsockfd;
  106. c->layer = layer;
  107. c->connection.state = UA_CONNECTION_OPENING;
  108. c->connection.localConf = layer->conf;
  109. c->connection.channel = UA_NULL;
  110. c->connection.close = (void (*)(void*))closeConnection;
  111. c->connection.write = (void (*)(void*, UA_ByteStringArray))writeCallback;
  112. layer->conLinks = realloc(layer->conLinks, sizeof(ConnectionLink)*(layer->conLinksSize+1));
  113. if(!layer->conLinks) {
  114. free(c);
  115. return UA_STATUSCODE_BADINTERNALERROR;
  116. }
  117. layer->conLinks[layer->conLinksSize].connection = c;
  118. layer->conLinks[layer->conLinksSize].sockfd = newsockfd;
  119. layer->conLinksSize++;
  120. return UA_STATUSCODE_GOOD;
  121. }
  122. // Takes the linked list of closed connections and returns the work for the server loop
  123. static UA_UInt32 batchDeleteLinks(NetworkLayerTCP *layer, UA_WorkItem **returnWork) {
  124. UA_WorkItem *work = malloc(sizeof(UA_WorkItem)*layer->conLinksSize);
  125. if (!work) {
  126. *returnWork = NULL;
  127. return 0;
  128. }
  129. #ifdef UA_MULTITHREADING
  130. struct deleteLink *d = uatomic_xchg(&layer->deleteLinkList, UA_NULL);
  131. #else
  132. struct deleteLink *d = layer->deleteLinkList;
  133. layer->deleteLinkList = UA_NULL;
  134. #endif
  135. UA_UInt32 count = 0;
  136. while(d) {
  137. UA_Int32 i;
  138. for(i = 0;i<layer->conLinksSize;i++) {
  139. if(layer->conLinks[i].sockfd == d->sockfd)
  140. break;
  141. }
  142. if(i < layer->conLinksSize) {
  143. TCPConnection *c = layer->conLinks[i].connection;
  144. layer->conLinksSize--;
  145. layer->conLinks[i] = layer->conLinks[layer->conLinksSize];
  146. work[count] = (UA_WorkItem)
  147. {.type = UA_WORKITEMTYPE_DELAYEDMETHODCALL,
  148. .work.methodCall = {.data = c,
  149. .method = (void (*)(UA_Server*,void*))freeConnectionCallback} };
  150. }
  151. struct deleteLink *oldd = d;
  152. d = d->next;
  153. free(oldd);
  154. count++;
  155. }
  156. *returnWork = work;
  157. return count;
  158. }
  159. #ifdef UA_MULTITHREADING
  160. void closeConnection(TCPConnection *handle) {
  161. if(uatomic_xchg(&handle->connection.state, UA_CONNECTION_CLOSING) == UA_CONNECTION_CLOSING)
  162. return;
  163. UA_Connection_detachSecureChannel(&handle->connection);
  164. shutdown(handle->sockfd,2);
  165. CLOSESOCKET(handle->sockfd);
  166. // Remove the link later in the main thread
  167. struct deleteLink *d = malloc(sizeof(struct deleteLink));
  168. d->sockfd = handle->sockfd;
  169. while(1) {
  170. d->next = handle->layer->deleteLinkList;
  171. if(uatomic_cmpxchg(&handle->layer->deleteLinkList, d->next, d) == d->next)
  172. break;
  173. }
  174. }
  175. #else
  176. void closeConnection(TCPConnection *handle) {
  177. struct deleteLink *d = malloc(sizeof(struct deleteLink));
  178. if(!d)
  179. return;
  180. if(handle->connection.state == UA_CONNECTION_CLOSING)
  181. return;
  182. handle->connection.state = UA_CONNECTION_CLOSING;
  183. UA_Connection_detachSecureChannel(&handle->connection);
  184. shutdown(handle->sockfd,2);
  185. CLOSESOCKET(handle->sockfd);
  186. // Remove the link later in the main thread
  187. d->sockfd = handle->sockfd;
  188. d->next = handle->layer->deleteLinkList;
  189. handle->layer->deleteLinkList = d;
  190. }
  191. #endif
  192. /** Accesses only the sockfd in the handle. Can be run from parallel threads. */
  193. void writeCallback(TCPConnection *handle, UA_ByteStringArray gather_buf) {
  194. UA_UInt32 total_len = 0, nWritten = 0;
  195. #ifdef _WIN32
  196. LPWSABUF buf = _alloca(gather_buf.stringsSize * sizeof(WSABUF));
  197. int result = 0;
  198. for(UA_UInt32 i = 0; i<gather_buf.stringsSize; i++) {
  199. buf[i].buf = (char*)gather_buf.strings[i].data;
  200. buf[i].len = gather_buf.strings[i].length;
  201. total_len += gather_buf.strings[i].length;
  202. }
  203. while(nWritten < total_len) {
  204. UA_UInt32 n = 0;
  205. do {
  206. result = WSASend(handle->sockfd, buf, gather_buf.stringsSize ,
  207. (LPDWORD)&n, 0, NULL, NULL);
  208. if(result != 0)
  209. printf("Error WSASend, code: %d \n", WSAGetLastError());
  210. } while(errno == EINTR);
  211. nWritten += n;
  212. }
  213. #else
  214. struct iovec iov[gather_buf.stringsSize];
  215. for(UA_UInt32 i=0;i<gather_buf.stringsSize;i++) {
  216. iov[i] = (struct iovec) {.iov_base = gather_buf.strings[i].data,
  217. .iov_len = gather_buf.strings[i].length};
  218. total_len += gather_buf.strings[i].length;
  219. }
  220. struct msghdr message = {.msg_name = NULL, .msg_namelen = 0, .msg_iov = iov,
  221. .msg_iovlen = gather_buf.stringsSize, .msg_control = NULL,
  222. .msg_controllen = 0, .msg_flags = 0};
  223. while (nWritten < total_len) {
  224. UA_Int32 n = 0;
  225. do {
  226. n = sendmsg(handle->sockfd, &message, 0);
  227. } while (n == -1L && errno == EINTR);
  228. nWritten += n;
  229. }
  230. #endif
  231. }
  232. static UA_StatusCode NetworkLayerTCP_start(NetworkLayerTCP *layer) {
  233. #ifdef _WIN32
  234. WORD wVersionRequested;
  235. WSADATA wsaData;
  236. wVersionRequested = MAKEWORD(2, 2);
  237. WSAStartup(wVersionRequested, &wsaData);
  238. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == INVALID_SOCKET) {
  239. printf("ERROR opening socket, code: %d\n", WSAGetLastError());
  240. return UA_STATUSCODE_BADINTERNALERROR;
  241. }
  242. #else
  243. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  244. perror("ERROR opening socket");
  245. return UA_STATUSCODE_BADINTERNALERROR;
  246. }
  247. #endif
  248. const struct sockaddr_in serv_addr = {
  249. .sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  250. .sin_port = htons(layer->port), .sin_zero = {0}};
  251. int optval = 1;
  252. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  253. SO_REUSEADDR, (const char *)&optval,
  254. sizeof(optval)) == -1) {
  255. perror("setsockopt");
  256. CLOSESOCKET(layer->serversockfd);
  257. return UA_STATUSCODE_BADINTERNALERROR;
  258. }
  259. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  260. sizeof(serv_addr)) < 0) {
  261. perror("binding");
  262. CLOSESOCKET(layer->serversockfd);
  263. return UA_STATUSCODE_BADINTERNALERROR;
  264. }
  265. setNonBlocking(layer->serversockfd);
  266. listen(layer->serversockfd, MAXBACKLOG);
  267. printf("Listening for TCP connections on %s:%d\n",
  268. inet_ntoa(serv_addr.sin_addr),
  269. ntohs(serv_addr.sin_port));
  270. return UA_STATUSCODE_GOOD;
  271. }
  272. static UA_Int32 NetworkLayerTCP_getWork(NetworkLayerTCP *layer, UA_WorkItem **workItems,
  273. UA_UInt16 timeout) {
  274. UA_WorkItem *items = UA_NULL;
  275. UA_Int32 itemsCount = batchDeleteLinks(layer, &items);
  276. setFDSet(layer);
  277. struct timeval tmptv = {0, timeout};
  278. UA_Int32 resultsize = select(layer->highestfd+1, &layer->fdset, NULL, NULL, &tmptv);
  279. if(resultsize < 0) {
  280. *workItems = items;
  281. return itemsCount;
  282. }
  283. // accept new connections (can only be a single one)
  284. if(FD_ISSET(layer->serversockfd,&layer->fdset)) {
  285. resultsize--;
  286. struct sockaddr_in cli_addr;
  287. socklen_t cli_len = sizeof(cli_addr);
  288. int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
  289. if (newsockfd >= 0)
  290. NetworkLayerTCP_add(layer, newsockfd);
  291. }
  292. items = realloc(items, sizeof(UA_WorkItem)*(itemsCount+resultsize));
  293. // read from established sockets
  294. UA_Int32 j = itemsCount;
  295. UA_ByteString buf = { -1, NULL};
  296. for(UA_Int32 i=0;i<layer->conLinksSize && j<itemsCount+resultsize;i++) {
  297. if(!(FD_ISSET(layer->conLinks[i].sockfd, &layer->fdset)))
  298. continue;
  299. if(!buf.data) {
  300. buf.data = malloc(sizeof(UA_Byte) * layer->conf.recvBufferSize);
  301. if(!buf.data)
  302. break;
  303. }
  304. #ifdef _WIN32
  305. buf.length = recv(layer->conLinks[i].sockfd, (char *)buf.data,
  306. layer->conf.recvBufferSize, 0);
  307. #else
  308. buf.length = read(layer->conLinks[i].sockfd, buf.data, layer->conf.recvBufferSize);
  309. #endif
  310. if (buf.length <= 0) {
  311. closeConnection(layer->conLinks[i].connection); // work is returned in the next iteration
  312. } else {
  313. items[j].type = UA_WORKITEMTYPE_BINARYNETWORKMESSAGE;
  314. items[j].work.binaryNetworkMessage.message = buf;
  315. items[j].work.binaryNetworkMessage.connection = &layer->conLinks[i].connection->connection;
  316. buf.data = NULL;
  317. j++;
  318. }
  319. }
  320. if(buf.data)
  321. free(buf.data);
  322. if(j == 0) {
  323. free(items);
  324. *workItems = NULL;
  325. } else
  326. *workItems = items;
  327. return j;
  328. }
  329. static UA_Int32 NetworkLayerTCP_stop(NetworkLayerTCP * layer, UA_WorkItem **workItems) {
  330. for(UA_Int32 index = 0;index < layer->conLinksSize;index++)
  331. closeConnection(layer->conLinks[index].connection);
  332. #ifdef _WIN32
  333. WSACleanup();
  334. #endif
  335. return batchDeleteLinks(layer, workItems);
  336. }
  337. static void NetworkLayerTCP_delete(NetworkLayerTCP *layer) {
  338. free(layer->conLinks);
  339. free(layer);
  340. }
  341. UA_NetworkLayer NetworkLayerTCP_new(UA_ConnectionConfig conf, UA_UInt32 port) {
  342. NetworkLayerTCP *tcplayer = malloc(sizeof(NetworkLayerTCP));
  343. tcplayer->conf = conf;
  344. tcplayer->conLinksSize = 0;
  345. tcplayer->conLinks = NULL;
  346. tcplayer->port = port;
  347. tcplayer->deleteLinkList = UA_NULL;
  348. UA_NetworkLayer nl;
  349. nl.nlHandle = tcplayer;
  350. nl.start = (UA_StatusCode (*)(void*))NetworkLayerTCP_start;
  351. nl.getWork = (UA_Int32 (*)(void*, UA_WorkItem**, UA_UInt16)) NetworkLayerTCP_getWork;
  352. nl.stop = (UA_Int32 (*)(void*, UA_WorkItem**)) NetworkLayerTCP_stop;
  353. nl.delete = (void (*)(void*))NetworkLayerTCP_delete;
  354. return nl;
  355. }