networklayer_tcp.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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 NOT_AMALGATED
  6. # define _XOPEN_SOURCE 500 //some users need this for some reason
  7. # include <stdlib.h> // malloc, free
  8. # include <string.h> // memset
  9. #endif
  10. #ifdef _WIN32
  11. # include <malloc.h>
  12. # include <winsock2.h>
  13. # include <ws2tcpip.h>
  14. # define CLOSESOCKET(S) closesocket(S)
  15. #else
  16. # include <fcntl.h>
  17. # include <sys/select.h>
  18. # include <netinet/in.h>
  19. # include <netinet/tcp.h>
  20. # include <sys/ioctl.h>
  21. # include <netdb.h> //gethostbyname for the client
  22. # include <unistd.h> // read, write, close
  23. # include <arpa/inet.h>
  24. # define CLOSESOCKET(S) close(S)
  25. #endif
  26. #include "networklayer_tcp.h" // UA_MULTITHREADING is defined in here
  27. #ifdef UA_MULTITHREADING
  28. # include <urcu/uatomic.h>
  29. #endif
  30. /* with a space, so the include is not removed during amalgamation */
  31. # include <errno.h>
  32. /****************************/
  33. /* Generic Socket Functions */
  34. /****************************/
  35. static UA_StatusCode socket_write(UA_Connection *connection, const UA_ByteString *buf) {
  36. if(buf->length < 0)
  37. return UA_STATUSCODE_BADINTERNALERROR;
  38. UA_Int32 nWritten = 0;
  39. while (nWritten < buf->length) {
  40. UA_Int32 n = 0;
  41. do {
  42. #ifdef _WIN32
  43. n = send((SOCKET)connection->sockfd, (const char*)buf->data, buf->length, 0);
  44. if(n < 0 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK)
  45. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  46. #else
  47. n = send(connection->sockfd, (const char*)buf->data, buf->length, MSG_NOSIGNAL);
  48. if(n == -1L && errno != EINTR && errno != EAGAIN)
  49. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  50. #endif
  51. } while (n == -1L);
  52. nWritten += n;
  53. }
  54. return UA_STATUSCODE_GOOD;
  55. }
  56. static UA_StatusCode socket_recv(UA_Connection *connection, UA_ByteString *response, UA_UInt32 timeout) {
  57. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  58. if(response->data == NULL)
  59. retval = connection->getBuffer(connection, response, connection->localConf.recvBufferSize);
  60. if(retval != UA_STATUSCODE_GOOD)
  61. return retval;
  62. struct timeval tmptv = {0, timeout * 1000};
  63. if(0 != setsockopt(connection->sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tmptv, sizeof(struct timeval))){
  64. return UA_STATUSCODE_BADINTERNALERROR;
  65. }
  66. int ret = recv(connection->sockfd, (char*)response->data, response->length, 0);
  67. if(ret == 0) {
  68. connection->releaseBuffer(connection, response);
  69. connection->close(connection);
  70. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  71. } else if(ret < 0) {
  72. #ifdef _WIN32
  73. if(WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK) {
  74. #else
  75. if (errno == EAGAIN) {
  76. #endif
  77. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  78. }
  79. connection->releaseBuffer(connection, response);
  80. connection->close(connection);
  81. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  82. }
  83. response->length = ret;
  84. *response = UA_Connection_completeMessages(connection, *response);
  85. return UA_STATUSCODE_GOOD;
  86. }
  87. static void socket_close(UA_Connection *connection) {
  88. connection->state = UA_CONNECTION_CLOSED;
  89. shutdown(connection->sockfd,2);
  90. CLOSESOCKET(connection->sockfd);
  91. }
  92. static UA_StatusCode socket_set_nonblocking(UA_Int32 sockfd) {
  93. #ifdef _WIN32
  94. u_long iMode = 1;
  95. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  96. return UA_STATUSCODE_BADINTERNALERROR;
  97. #else
  98. int opts = fcntl(sockfd, F_GETFL);
  99. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  100. return UA_STATUSCODE_BADINTERNALERROR;
  101. #endif
  102. return UA_STATUSCODE_GOOD;
  103. }
  104. /*****************************/
  105. /* Generic Buffer Management */
  106. /*****************************/
  107. static UA_StatusCode GetMallocedBuffer(UA_Connection *connection, UA_ByteString *buf, size_t minSize) {
  108. return UA_ByteString_newMembers(buf, minSize);
  109. }
  110. static void ReleaseMallocedBuffer(UA_Connection *connection, UA_ByteString *buf) {
  111. UA_ByteString_deleteMembers(buf);
  112. }
  113. /***************************/
  114. /* Server NetworkLayer TCP */
  115. /***************************/
  116. /**
  117. * For the multithreaded mode, assume a single thread that periodically "gets work" from the network
  118. * layer. In addition, several worker threads are asynchronously calling into the callbacks of the
  119. * UA_Connection that holds a single connection.
  120. *
  121. * Creating a connection: When "GetWork" encounters a new connection, it creates a UA_Connection
  122. * with the socket information. This is added to the mappings array that links sockets to
  123. * UA_Connection structs.
  124. *
  125. * Reading data: In "GetWork", we listen on the sockets in the mappings array. If data arrives (or
  126. * the connection closes), a WorkItem is created that carries the work and a pointer to the
  127. * connection.
  128. *
  129. * Closing a connection: Closing can happen in two ways. Either it is triggered by the server in an
  130. * asynchronous callback. Or the connection is close by the client and this is detected in
  131. * "GetWork". The server needs to do some internal cleanups (close attached securechannels, etc.).
  132. * So even when a closed connection is detected in "GetWork", we trigger the server to close the
  133. * connection (with a WorkItem) and continue from the callback.
  134. *
  135. * - Server calls close-callback: We close the socket, set the connection-state to closed and add
  136. * the connection to a linked list from which it is deleted later. The connection cannot be freed
  137. * right away since other threads might still be using it.
  138. *
  139. * - GetWork: We remove the connection from the mappings array. In the non-multithreaded case, the
  140. * connection is freed. For multithreading, we return a workitem that is delayed, i.e. that is
  141. * called only after all workitems created before are finished in all threads. This workitems
  142. * contains a callback that goes through the linked list of connections to be freed.
  143. *
  144. */
  145. #define MAXBACKLOG 100
  146. typedef struct {
  147. /* config */
  148. UA_Logger *logger;
  149. UA_UInt32 port;
  150. UA_String discoveryUrl;
  151. UA_ConnectionConfig conf; /* todo: rename to localconf. */
  152. /* open sockets and connections */
  153. fd_set fdset;
  154. UA_Int32 serversockfd;
  155. UA_Int32 highestfd;
  156. size_t mappingsSize;
  157. struct ConnectionMapping {
  158. UA_Connection *connection;
  159. UA_Int32 sockfd;
  160. } *mappings;
  161. /* to-be-deleted connections */
  162. struct DeleteList {
  163. struct DeleteList *next;
  164. UA_Connection *connection;
  165. } *deletes;
  166. } ServerNetworkLayerTCP;
  167. /* after every select, we need to reset the sockets we want to listen on */
  168. static void setFDSet(ServerNetworkLayerTCP *layer) {
  169. FD_ZERO(&layer->fdset);
  170. #ifdef _WIN32
  171. FD_SET((UA_UInt32)layer->serversockfd, &layer->fdset);
  172. #else
  173. FD_SET(layer->serversockfd, &layer->fdset);
  174. #endif
  175. layer->highestfd = layer->serversockfd;
  176. for(size_t i = 0; i < layer->mappingsSize; i++) {
  177. #ifdef _WIN32
  178. FD_SET((UA_UInt32)layer->mappings[i].sockfd, &layer->fdset);
  179. #else
  180. FD_SET(layer->mappings[i].sockfd, &layer->fdset);
  181. #endif
  182. if(layer->mappings[i].sockfd > layer->highestfd)
  183. layer->highestfd = layer->mappings[i].sockfd;
  184. }
  185. }
  186. /* callback triggered from the server */
  187. static void ServerNetworkLayerTCP_closeConnection(UA_Connection *connection) {
  188. #ifdef UA_MULTITHREADING
  189. if(uatomic_xchg(&connection->state, UA_CONNECTION_CLOSED) == UA_CONNECTION_CLOSED)
  190. return;
  191. #else
  192. if(connection->state == UA_CONNECTION_CLOSED)
  193. return;
  194. connection->state = UA_CONNECTION_CLOSED;
  195. #endif
  196. socket_close(connection);
  197. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)connection->handle;
  198. struct DeleteList *d = malloc(sizeof(struct DeleteList));
  199. if(!d){
  200. return;
  201. }
  202. d->connection = connection;
  203. #ifdef UA_MULTITHREADING
  204. while(1) {
  205. d->next = layer->deletes;
  206. if(uatomic_cmpxchg(&layer->deletes, d->next, d) == d->next)
  207. break;
  208. }
  209. #else
  210. d->next = layer->deletes;
  211. layer->deletes = d;
  212. #endif
  213. }
  214. /* call only from the single networking thread */
  215. static UA_StatusCode ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd) {
  216. UA_Connection *c = malloc(sizeof(UA_Connection));
  217. if(!c)
  218. return UA_STATUSCODE_BADINTERNALERROR;
  219. UA_Connection_init(c);
  220. c->sockfd = newsockfd;
  221. c->handle = layer;
  222. c->localConf = layer->conf;
  223. c->write = socket_write;
  224. c->close = ServerNetworkLayerTCP_closeConnection;
  225. c->getBuffer = GetMallocedBuffer;
  226. c->releaseBuffer = ReleaseMallocedBuffer;
  227. c->state = UA_CONNECTION_OPENING;
  228. struct ConnectionMapping *nm =
  229. realloc(layer->mappings, sizeof(struct ConnectionMapping)*(layer->mappingsSize+1));
  230. if(!nm) {
  231. free(c);
  232. return UA_STATUSCODE_BADINTERNALERROR;
  233. }
  234. layer->mappings = nm;
  235. layer->mappings[layer->mappingsSize] = (struct ConnectionMapping){c, newsockfd};
  236. layer->mappingsSize++;
  237. return UA_STATUSCODE_GOOD;
  238. }
  239. static UA_StatusCode ServerNetworkLayerTCP_start(ServerNetworkLayerTCP *layer, UA_Logger *logger) {
  240. layer->logger = logger;
  241. #ifdef _WIN32
  242. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
  243. UA_LOG_WARNING((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Error opening socket, code: %d",
  244. WSAGetLastError());
  245. return UA_STATUSCODE_BADINTERNALERROR;
  246. }
  247. #else
  248. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  249. UA_LOG_WARNING((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Error opening socket");
  250. return UA_STATUSCODE_BADINTERNALERROR;
  251. }
  252. #endif
  253. const struct sockaddr_in serv_addr =
  254. {.sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  255. .sin_port = htons(layer->port), .sin_zero = {0}};
  256. int optval = 1;
  257. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  258. SO_REUSEADDR, (const char *)&optval,
  259. sizeof(optval)) == -1) {
  260. UA_LOG_WARNING((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Error during setting of socket options");
  261. CLOSESOCKET(layer->serversockfd);
  262. return UA_STATUSCODE_BADINTERNALERROR;
  263. }
  264. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  265. sizeof(serv_addr)) < 0) {
  266. UA_LOG_WARNING((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Error during socket binding");
  267. CLOSESOCKET(layer->serversockfd);
  268. return UA_STATUSCODE_BADINTERNALERROR;
  269. }
  270. socket_set_nonblocking(layer->serversockfd);
  271. listen(layer->serversockfd, MAXBACKLOG);
  272. UA_LOG_INFO((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Listening on %.*s",
  273. layer->discoveryUrl.length, layer->discoveryUrl.data);
  274. return UA_STATUSCODE_GOOD;
  275. }
  276. /* delayed callback that frees old connections */
  277. static void freeConnections(UA_Server *server, struct DeleteList *d) {
  278. while(d) {
  279. UA_Connection_deleteMembers(d->connection);
  280. free(d->connection);
  281. struct DeleteList *old = d;
  282. d = d->next;
  283. free(old);
  284. }
  285. }
  286. /* remove the closed sockets from the mappings array */
  287. static void removeMappings(ServerNetworkLayerTCP *layer, struct DeleteList *d) {
  288. while(d) {
  289. size_t i = 0;
  290. for(; i < layer->mappingsSize; i++) {
  291. if(layer->mappings[i].sockfd == d->connection->sockfd)
  292. break;
  293. }
  294. if(i >= layer->mappingsSize)
  295. continue;
  296. layer->mappingsSize--;
  297. layer->mappings[i] = layer->mappings[layer->mappingsSize];
  298. d = d->next;
  299. }
  300. }
  301. static UA_Int32 ServerNetworkLayerTCP_getWork(ServerNetworkLayerTCP *layer, UA_WorkItem **workItems,
  302. UA_UInt16 timeout) {
  303. struct DeleteList *deletes;
  304. #ifdef UA_MULTITHREADING
  305. deletes = uatomic_xchg(&layer->deletes, NULL);
  306. #else
  307. deletes = layer->deletes;
  308. layer->deletes = NULL;
  309. #endif
  310. removeMappings(layer, deletes);
  311. setFDSet(layer);
  312. struct timeval tmptv = {0, timeout};
  313. UA_Int32 resultsize = select(layer->highestfd+1, &layer->fdset, NULL, NULL, &tmptv);
  314. UA_WorkItem *items;
  315. if(resultsize < 0 || !(items = malloc(sizeof(UA_WorkItem)*(resultsize+1)))) {
  316. /* abort .. reattach the deletes so that they get deleted eventually.. */
  317. #ifdef UA_MULTITHREADING
  318. struct DeleteList *last_delete = deletes;
  319. while(last_delete->next != NULL)
  320. last_delete = last_delete->next;
  321. while(1) {
  322. last_delete->next = layer->deletes;
  323. if(uatomic_cmpxchg(&layer->deletes, last_delete->next, deletes) == last_delete->next)
  324. break;
  325. }
  326. #else
  327. layer->deletes = deletes;
  328. #endif
  329. *workItems = NULL;
  330. return 0;
  331. }
  332. /* accept new connections (can only be a single one) */
  333. if(FD_ISSET(layer->serversockfd, &layer->fdset)) {
  334. resultsize--;
  335. struct sockaddr_in cli_addr;
  336. socklen_t cli_len = sizeof(cli_addr);
  337. int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
  338. int i = 1;
  339. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY, (void *)&i, sizeof(i));
  340. if (newsockfd >= 0) {
  341. socket_set_nonblocking(newsockfd);
  342. ServerNetworkLayerTCP_add(layer, newsockfd);
  343. }
  344. }
  345. /* read from established sockets */
  346. UA_Int32 j = 0;
  347. UA_ByteString buf = UA_BYTESTRING_NULL;
  348. for(size_t i = 0; i < layer->mappingsSize && j < resultsize; i++) {
  349. if(!(FD_ISSET(layer->mappings[i].sockfd, &layer->fdset)))
  350. continue;
  351. if(!buf.data) {
  352. buf.data = malloc(sizeof(UA_Byte) * layer->conf.recvBufferSize);
  353. buf.length = layer->conf.recvBufferSize;
  354. if(!buf.data)
  355. break;
  356. }
  357. if(socket_recv(layer->mappings[i].connection, &buf, 0) == UA_STATUSCODE_GOOD) {
  358. items[j].type = UA_WORKITEMTYPE_BINARYMESSAGE;
  359. items[j].work.binaryMessage.message = buf;
  360. items[j].work.binaryMessage.connection = layer->mappings[i].connection;
  361. buf.data = NULL;
  362. } else {
  363. items[j].type = UA_WORKITEMTYPE_CLOSECONNECTION;
  364. items[j].work.closeConnection = layer->mappings[i].connection;
  365. }
  366. j++;
  367. }
  368. /* add the delayed work that frees the connections */
  369. if(deletes) {
  370. items[j].type = UA_WORKITEMTYPE_DELAYEDMETHODCALL;
  371. items[j].work.methodCall.data = deletes;
  372. items[j].work.methodCall.method = (void (*)(UA_Server *server, void *data))freeConnections;
  373. j++;
  374. }
  375. /* free the array if there is no work */
  376. if(j == 0) {
  377. free(items);
  378. *workItems = NULL;
  379. } else
  380. *workItems = items;
  381. return j;
  382. }
  383. static UA_Int32 ServerNetworkLayerTCP_stop(ServerNetworkLayerTCP *layer, UA_WorkItem **workItems) {
  384. struct DeleteList *deletes;
  385. #ifdef UA_MULTITHREADING
  386. deletes = uatomic_xchg(&layer->deletes, NULL);
  387. #else
  388. deletes = layer->deletes;
  389. layer->deletes = NULL;
  390. #endif
  391. removeMappings(layer, deletes);
  392. UA_WorkItem *items = malloc(sizeof(UA_WorkItem) * layer->mappingsSize);
  393. if(!items)
  394. return 0;
  395. for(size_t i = 0; i < layer->mappingsSize; i++) {
  396. items[i].type = UA_WORKITEMTYPE_CLOSECONNECTION;
  397. items[i].work.closeConnection = layer->mappings[i].connection;
  398. }
  399. #ifdef _WIN32
  400. WSACleanup();
  401. #endif
  402. *workItems = items;
  403. return layer->mappingsSize;
  404. }
  405. /* run only when the server is stopped */
  406. static void ServerNetworkLayerTCP_delete(ServerNetworkLayerTCP *layer) {
  407. UA_String_deleteMembers(&layer->discoveryUrl);
  408. removeMappings(layer, layer->deletes);
  409. freeConnections(NULL, layer->deletes);
  410. for(size_t i = 0; i < layer->mappingsSize; i++)
  411. free(layer->mappings[i].connection);
  412. free(layer->mappings);
  413. free(layer);
  414. }
  415. UA_ServerNetworkLayer ServerNetworkLayerTCP_new(UA_ConnectionConfig conf, UA_UInt32 port) {
  416. #ifdef _WIN32
  417. WORD wVersionRequested;
  418. WSADATA wsaData;
  419. wVersionRequested = MAKEWORD(2, 2);
  420. WSAStartup(wVersionRequested, &wsaData);
  421. #endif
  422. UA_ServerNetworkLayer nl;
  423. UA_ServerNetworkLayer_init(&nl);
  424. ServerNetworkLayerTCP *layer = malloc(sizeof(ServerNetworkLayerTCP));
  425. if(!layer){
  426. return nl;
  427. }
  428. layer->conf = conf;
  429. layer->mappingsSize = 0;
  430. layer->mappings = NULL;
  431. layer->port = port;
  432. layer->deletes = NULL;
  433. char hostname[256];
  434. gethostname(hostname, 255);
  435. UA_String_copyprintf("opc.tcp://%s:%d", &layer->discoveryUrl, hostname, port);
  436. nl.nlHandle = layer;
  437. nl.start = (UA_StatusCode (*)(void*, UA_Logger *logger))ServerNetworkLayerTCP_start;
  438. nl.getWork = (UA_Int32 (*)(void*, UA_WorkItem**, UA_UInt16))ServerNetworkLayerTCP_getWork;
  439. nl.stop = (UA_Int32 (*)(void*, UA_WorkItem**))ServerNetworkLayerTCP_stop;
  440. nl.free = (void (*)(void*))ServerNetworkLayerTCP_delete;
  441. nl.discoveryUrl = &layer->discoveryUrl;
  442. return nl;
  443. }
  444. /***************************/
  445. /* Client NetworkLayer TCP */
  446. /***************************/
  447. UA_Connection ClientNetworkLayerTCP_connect(char *endpointUrl, UA_Logger *logger) {
  448. UA_Connection connection;
  449. UA_Connection_init(&connection);
  450. size_t urlLength = strlen(endpointUrl);
  451. if(urlLength < 11 || urlLength >= 512) {
  452. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Server url size invalid");
  453. return connection;
  454. }
  455. if(strncmp(endpointUrl, "opc.tcp://", 10) != 0) {
  456. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Server url does not begin with opc.tcp://");
  457. return connection;
  458. }
  459. UA_UInt16 portpos = 9;
  460. UA_UInt16 port = 0;
  461. for(;portpos < urlLength-1; portpos++) {
  462. if(endpointUrl[portpos] == ':') {
  463. port = atoi(&endpointUrl[portpos+1]);
  464. break;
  465. }
  466. }
  467. if(port == 0) {
  468. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Port invalid");
  469. return connection;
  470. }
  471. char hostname[512];
  472. for(int i=10; i < portpos; i++)
  473. hostname[i-10] = endpointUrl[i];
  474. hostname[portpos-10] = 0;
  475. #ifdef _WIN32
  476. WORD wVersionRequested;
  477. WSADATA wsaData;
  478. wVersionRequested = MAKEWORD(2, 2);
  479. WSAStartup(wVersionRequested, &wsaData);
  480. if((connection.sockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
  481. #else
  482. if((connection.sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  483. #endif
  484. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Could not create socket");
  485. return connection;
  486. }
  487. struct hostent *server = gethostbyname(hostname);
  488. if(server == NULL) {
  489. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "DNS lookup of %s failed", hostname);
  490. return connection;
  491. }
  492. struct sockaddr_in server_addr;
  493. memset(&server_addr, 0, sizeof(server_addr));
  494. memcpy((char *)&server_addr.sin_addr.s_addr, (char *)server->h_addr_list[0], server->h_length);
  495. server_addr.sin_family = AF_INET;
  496. server_addr.sin_port = htons(port);
  497. if(connect(connection.sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
  498. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Connection failed");
  499. return connection;
  500. }
  501. connection.state = UA_CONNECTION_OPENING;
  502. //socket_set_nonblocking(connection.sockfd);
  503. connection.write = socket_write;
  504. connection.recv = socket_recv;
  505. connection.close = socket_close;
  506. connection.getBuffer = GetMallocedBuffer;
  507. connection.releaseBuffer = ReleaseMallocedBuffer;
  508. return connection;
  509. }