networklayer_tcp.c 19 KB

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