networklayer_tcp.c 19 KB

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