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