networklayer_tcp.c 20 KB

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