networklayer_tcp.c 21 KB

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