networklayer_tcp.c 12 KB

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