networklayer_tcp.c 20 KB

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