networklayer_tcp.c 21 KB

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