networklayer_tcp.c 13 KB

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