networklayer_tcp.c 20 KB

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