networklayer_tcp.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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 = -1;
  81. return UA_STATUSCODE_BADOUTOFMEMORY; /* not enough memory retry */
  82. }
  83. if(timeout > 0) {
  84. /* currently, only the client uses timeouts */
  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_BADCONNECTIONCLOSED;
  90. }
  91. }
  92. int ret = recv(connection->sockfd, (char*)response->data, connection->localConf.recvBufferSize, 0);
  93. if(ret == 0) {
  94. /* server has closed the connection */
  95. UA_ByteString_deleteMembers(response);
  96. socket_close(connection);
  97. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  98. } else if(ret < 0) {
  99. UA_ByteString_deleteMembers(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_BADINTERNALERROR; /* 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. /* open sockets and connections */
  170. fd_set fdset;
  171. UA_Int32 serversockfd;
  172. UA_Int32 highestfd;
  173. size_t mappingsSize;
  174. struct ConnectionMapping {
  175. UA_Connection *connection;
  176. UA_Int32 sockfd;
  177. } *mappings;
  178. } ServerNetworkLayerTCP;
  179. static UA_StatusCode
  180. ServerNetworkLayerGetSendBuffer(UA_Connection *connection, size_t length, UA_ByteString *buf) {
  181. if(length > connection->remoteConf.recvBufferSize)
  182. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  183. *buf = UA_ByteString_withSize(length);
  184. if(buf->data == NULL)
  185. return UA_STATUSCODE_BADOUTOFMEMORY;
  186. return UA_STATUSCODE_GOOD;
  187. }
  188. static void
  189. ServerNetworkLayerReleaseSendBuffer(UA_Connection *connection, UA_ByteString *buf) {
  190. UA_ByteString_deleteMembers(buf);
  191. }
  192. static void
  193. ServerNetworkLayerReleaseRecvBuffer(UA_Connection *connection, UA_ByteString *buf) {
  194. UA_ByteString_deleteMembers(buf);
  195. }
  196. /* after every select, we need to reset the sockets we want to listen on */
  197. static void setFDSet(ServerNetworkLayerTCP *layer) {
  198. FD_ZERO(&layer->fdset);
  199. FD_SET((UA_UInt32)layer->serversockfd, &layer->fdset);
  200. layer->highestfd = layer->serversockfd;
  201. for(size_t i = 0; i < layer->mappingsSize; i++) {
  202. FD_SET((UA_UInt32)layer->mappings[i].sockfd, &layer->fdset);
  203. if(layer->mappings[i].sockfd > layer->highestfd)
  204. layer->highestfd = layer->mappings[i].sockfd;
  205. }
  206. }
  207. /* callback triggered from the server */
  208. static void ServerNetworkLayerTCP_closeConnection(UA_Connection *connection) {
  209. #ifdef UA_MULTITHREADING
  210. if(uatomic_xchg(&connection->state, UA_CONNECTION_CLOSED) == UA_CONNECTION_CLOSED)
  211. return;
  212. #else
  213. if(connection->state == UA_CONNECTION_CLOSED)
  214. return;
  215. connection->state = UA_CONNECTION_CLOSED;
  216. #endif
  217. ServerNetworkLayerTCP *layer = connection->handle;
  218. UA_LOG_INFO(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "Closing the Connection %i",
  219. connection->sockfd);
  220. /* only "shutdown" here. this triggers the select, where the socket is
  221. "closed" in the mainloop */
  222. shutdown(connection->sockfd, 2);
  223. }
  224. /* call only from the single networking thread */
  225. static UA_StatusCode ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd) {
  226. UA_Connection *c = malloc(sizeof(UA_Connection));
  227. if(!c)
  228. return UA_STATUSCODE_BADINTERNALERROR;
  229. struct sockaddr_in addr;
  230. socklen_t addrlen = sizeof(struct sockaddr_in);
  231. getsockname(newsockfd, (struct sockaddr*)&addr, &addrlen);
  232. UA_LOG_INFO(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "New Connection %i over TCP from %s:%d",
  233. newsockfd, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
  234. UA_Connection_init(c);
  235. c->sockfd = newsockfd;
  236. c->handle = layer;
  237. c->localConf = layer->conf;
  238. c->send = socket_write;
  239. c->close = ServerNetworkLayerTCP_closeConnection;
  240. c->getSendBuffer = ServerNetworkLayerGetSendBuffer;
  241. c->releaseSendBuffer = ServerNetworkLayerReleaseSendBuffer;
  242. c->releaseRecvBuffer = ServerNetworkLayerReleaseRecvBuffer;
  243. c->state = UA_CONNECTION_OPENING;
  244. struct ConnectionMapping *nm;
  245. nm = realloc(layer->mappings, sizeof(struct ConnectionMapping)*(layer->mappingsSize+1));
  246. if(!nm) {
  247. UA_LOG_ERROR(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "No memory for a new Connection");
  248. free(c);
  249. return UA_STATUSCODE_BADINTERNALERROR;
  250. }
  251. layer->mappings = nm;
  252. layer->mappings[layer->mappingsSize] = (struct ConnectionMapping){c, newsockfd};
  253. layer->mappingsSize++;
  254. return UA_STATUSCODE_GOOD;
  255. }
  256. static UA_StatusCode ServerNetworkLayerTCP_start(ServerNetworkLayerTCP *layer, UA_Logger logger) {
  257. layer->layer.logger = logger;
  258. #ifdef _WIN32
  259. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
  260. UA_LOG_WARNING(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "Error opening socket, code: %d",
  261. WSAGetLastError());
  262. return UA_STATUSCODE_BADINTERNALERROR;
  263. }
  264. #else
  265. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  266. UA_LOG_WARNING(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "Error opening socket");
  267. return UA_STATUSCODE_BADINTERNALERROR;
  268. }
  269. #endif
  270. const struct sockaddr_in serv_addr =
  271. {.sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  272. .sin_port = htons(layer->port), .sin_zero = {0}};
  273. int optval = 1;
  274. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  275. SO_REUSEADDR, (const char *)&optval,
  276. sizeof(optval)) == -1) {
  277. UA_LOG_WARNING(layer->layer.logger, UA_LOGCATEGORY_NETWORK,
  278. "Error during setting of socket options");
  279. CLOSESOCKET(layer->serversockfd);
  280. return UA_STATUSCODE_BADINTERNALERROR;
  281. }
  282. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  283. sizeof(serv_addr)) < 0) {
  284. UA_LOG_WARNING(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "Error during socket binding");
  285. CLOSESOCKET(layer->serversockfd);
  286. return UA_STATUSCODE_BADINTERNALERROR;
  287. }
  288. socket_set_nonblocking(layer->serversockfd);
  289. listen(layer->serversockfd, MAXBACKLOG);
  290. UA_LOG_INFO(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "TCP network layer listening on %.*s",
  291. layer->layer.discoveryUrl.length, layer->layer.discoveryUrl.data);
  292. return UA_STATUSCODE_GOOD;
  293. }
  294. static size_t
  295. ServerNetworkLayerTCP_getJobs(ServerNetworkLayerTCP *layer, UA_Job **jobs, UA_UInt16 timeout) {
  296. setFDSet(layer);
  297. struct timeval tmptv = {0, timeout};
  298. UA_Int32 resultsize;
  299. resultsize = select(layer->highestfd+1, &layer->fdset, NULL, NULL, &tmptv);
  300. if(resultsize < 0) {
  301. *jobs = NULL;
  302. return 0;
  303. }
  304. /* accept new connections (can only be a single one) */
  305. if(FD_ISSET(layer->serversockfd, &layer->fdset)) {
  306. resultsize--;
  307. struct sockaddr_in cli_addr;
  308. socklen_t cli_len = sizeof(cli_addr);
  309. int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
  310. int i = 1;
  311. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY, (void *)&i, sizeof(i));
  312. if(newsockfd >= 0) {
  313. socket_set_nonblocking(newsockfd);
  314. ServerNetworkLayerTCP_add(layer, newsockfd);
  315. }
  316. }
  317. /* alloc enough space for a cleanup-connection and free-connection job per resulted socket */
  318. if(resultsize == 0)
  319. return 0;
  320. UA_Job *js = malloc(sizeof(UA_Job) * resultsize * 2);
  321. if(!js)
  322. return 0;
  323. /* read from established sockets */
  324. size_t j = 0;
  325. UA_ByteString buf = UA_BYTESTRING_NULL;
  326. for(size_t i = 0; i < layer->mappingsSize && j < (size_t)resultsize; i++) {
  327. if(!(FD_ISSET(layer->mappings[i].sockfd, &layer->fdset)))
  328. continue;
  329. UA_StatusCode retval = socket_recv(layer->mappings[i].connection, &buf, 0);
  330. if(retval == UA_STATUSCODE_GOOD) {
  331. js[j] = UA_Connection_completeMessages(layer->mappings[i].connection, buf);
  332. j++;
  333. } else if (retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  334. UA_Connection *c = layer->mappings[i].connection;
  335. /* the socket was closed from remote */
  336. js[j].type = UA_JOBTYPE_DETACHCONNECTION;
  337. js[j].job.closeConnection = layer->mappings[i].connection;
  338. layer->mappings[i] = layer->mappings[layer->mappingsSize-1];
  339. layer->mappingsSize--;
  340. j++;
  341. js[j].type = UA_JOBTYPE_METHODCALL_DELAYED;
  342. js[j].job.methodCall.method = FreeConnectionCallback;
  343. js[j].job.methodCall.data = c;
  344. j++;
  345. }
  346. }
  347. if(j == 0) {
  348. free(js);
  349. js = NULL;
  350. }
  351. *jobs = js;
  352. return j;
  353. }
  354. static size_t
  355. ServerNetworkLayerTCP_stop(ServerNetworkLayerTCP *layer, UA_Job **jobs) {
  356. UA_LOG_INFO(layer->layer.logger, UA_LOGCATEGORY_NETWORK,
  357. "Shutting down the TCP network layer with %d open connection(s)", layer->mappingsSize);
  358. shutdown(layer->serversockfd,2);
  359. CLOSESOCKET(layer->serversockfd);
  360. UA_Job *items = malloc(sizeof(UA_Job) * layer->mappingsSize * 2);
  361. if(!items)
  362. return 0;
  363. for(size_t i = 0; i < layer->mappingsSize; i++) {
  364. socket_close(layer->mappings[i].connection);
  365. items[i*2].type = UA_JOBTYPE_DETACHCONNECTION;
  366. items[i*2].job.closeConnection = layer->mappings[i].connection;
  367. items[(i*2)+1].type = UA_JOBTYPE_METHODCALL_DELAYED;
  368. items[(i*2)+1].job.methodCall.method = FreeConnectionCallback;
  369. items[(i*2)+1].job.methodCall.data = layer->mappings[i].connection;
  370. }
  371. #ifdef _WIN32
  372. WSACleanup();
  373. #endif
  374. *jobs = items;
  375. return layer->mappingsSize*2;
  376. }
  377. /* run only when the server is stopped */
  378. static void ServerNetworkLayerTCP_deleteMembers(ServerNetworkLayerTCP *layer) {
  379. free(layer->mappings);
  380. }
  381. UA_ServerNetworkLayer * ServerNetworkLayerTCP_new(UA_ConnectionConfig conf, UA_UInt32 port) {
  382. #ifdef _WIN32
  383. WORD wVersionRequested;
  384. WSADATA wsaData;
  385. wVersionRequested = MAKEWORD(2, 2);
  386. WSAStartup(wVersionRequested, &wsaData);
  387. #endif
  388. ServerNetworkLayerTCP *layer = malloc(sizeof(ServerNetworkLayerTCP));
  389. if(!layer)
  390. return NULL;
  391. memset(layer, 0, sizeof(ServerNetworkLayerTCP));
  392. layer->conf = conf;
  393. layer->mappingsSize = 0;
  394. layer->mappings = NULL;
  395. layer->port = port;
  396. char hostname[256];
  397. if(gethostname(hostname, 255) == 0) {
  398. char discoveryUrl[256];
  399. UA_String str;
  400. #ifndef _MSC_VER
  401. str.length = snprintf(discoveryUrl, 255, "opc.tcp://%s:%d", hostname, port);
  402. #else
  403. str.length = _snprintf_s(discoveryUrl, 255, _TRUNCATE, "opc.tcp://%s:%d", hostname, port);
  404. #endif
  405. str.data = (UA_Byte*)discoveryUrl;
  406. UA_String_copy(&str, &layer->layer.discoveryUrl);
  407. }
  408. layer->layer.start = (UA_StatusCode(*)(UA_ServerNetworkLayer*,UA_Logger))ServerNetworkLayerTCP_start;
  409. layer->layer.getJobs = (size_t(*)(UA_ServerNetworkLayer*,UA_Job**,UA_UInt16))ServerNetworkLayerTCP_getJobs;
  410. layer->layer.stop = (size_t(*)(UA_ServerNetworkLayer*, UA_Job**))ServerNetworkLayerTCP_stop;
  411. layer->layer.deleteMembers = (void(*)(UA_ServerNetworkLayer*))ServerNetworkLayerTCP_deleteMembers;
  412. return &layer->layer;
  413. }
  414. /***************************/
  415. /* Client NetworkLayer TCP */
  416. /***************************/
  417. static UA_StatusCode
  418. ClientNetworkLayerGetBuffer(UA_Connection *connection, size_t length, UA_ByteString *buf) {
  419. if(length > connection->remoteConf.recvBufferSize)
  420. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  421. if(connection->state == UA_CONNECTION_CLOSED)
  422. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  423. *buf = UA_ByteString_withSize(connection->remoteConf.recvBufferSize);
  424. if(buf->data == NULL)
  425. return UA_STATUSCODE_BADOUTOFMEMORY;
  426. return UA_STATUSCODE_GOOD;
  427. }
  428. static void
  429. ClientNetworkLayerReleaseBuffer(UA_Connection *connection, UA_ByteString *buf) {
  430. UA_ByteString_deleteMembers(buf);
  431. }
  432. static void
  433. ClientNetworkLayerClose(UA_Connection *connection) {
  434. #ifdef UA_MULTITHREADING
  435. if(uatomic_xchg(&connection->state, UA_CONNECTION_CLOSED) == UA_CONNECTION_CLOSED)
  436. return;
  437. #else
  438. if(connection->state == UA_CONNECTION_CLOSED)
  439. return;
  440. connection->state = UA_CONNECTION_CLOSED;
  441. #endif
  442. socket_close(connection);
  443. }
  444. /* we have no networklayer. instead, attach the reusable buffer to the handle */
  445. UA_Connection
  446. ClientNetworkLayerTCP_connect(UA_ConnectionConfig localConf, char *endpointUrl, UA_Logger logger) {
  447. UA_Connection connection;
  448. UA_Connection_init(&connection);
  449. connection.localConf = localConf;
  450. size_t urlLength = strlen(endpointUrl);
  451. if(urlLength < 11 || urlLength >= 512) {
  452. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Server url size invalid");
  453. return connection;
  454. }
  455. if(strncmp(endpointUrl, "opc.tcp://", 10) != 0) {
  456. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Server url does not begin with opc.tcp://");
  457. return connection;
  458. }
  459. UA_UInt16 portpos = 9;
  460. UA_UInt16 port;
  461. for(port = 0; portpos < urlLength-1; portpos++) {
  462. if(endpointUrl[portpos] == ':') {
  463. port = atoi(&endpointUrl[portpos+1]);
  464. break;
  465. }
  466. }
  467. if(port == 0) {
  468. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Port invalid");
  469. return connection;
  470. }
  471. char hostname[512];
  472. for(int i=10; i < portpos; i++)
  473. hostname[i-10] = endpointUrl[i];
  474. hostname[portpos-10] = 0;
  475. #ifdef _WIN32
  476. WORD wVersionRequested;
  477. WSADATA wsaData;
  478. wVersionRequested = MAKEWORD(2, 2);
  479. WSAStartup(wVersionRequested, &wsaData);
  480. if((connection.sockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
  481. #else
  482. if((connection.sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  483. #endif
  484. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Could not create socket");
  485. return connection;
  486. }
  487. struct hostent *server = gethostbyname(hostname);
  488. if(!server) {
  489. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "DNS lookup of %s failed", hostname);
  490. return connection;
  491. }
  492. struct sockaddr_in server_addr;
  493. memset(&server_addr, 0, sizeof(server_addr));
  494. memcpy((char *)&server_addr.sin_addr.s_addr, (char *)server->h_addr_list[0], server->h_length);
  495. server_addr.sin_family = AF_INET;
  496. server_addr.sin_port = htons(port);
  497. connection.state = UA_CONNECTION_OPENING;
  498. if(connect(connection.sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
  499. ClientNetworkLayerClose(&connection);
  500. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Connection failed");
  501. return connection;
  502. }
  503. #ifdef SO_NOSIGPIPE
  504. int val = 1;
  505. if(setsockopt(connection.sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&val, sizeof(val)) < 0) {
  506. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Couldn't set SO_NOSIGPIPE");
  507. return connection;
  508. }
  509. #endif
  510. //socket_set_nonblocking(connection.sockfd);
  511. connection.send = socket_write;
  512. connection.recv = socket_recv;
  513. connection.close = ClientNetworkLayerClose;
  514. connection.getSendBuffer = ClientNetworkLayerGetBuffer;
  515. connection.releaseSendBuffer = ClientNetworkLayerReleaseBuffer;
  516. connection.releaseRecvBuffer = ClientNetworkLayerReleaseBuffer;
  517. return connection;
  518. }