networklayer_tcp.c 19 KB

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