networklayer_tcp.c 20 KB

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