networklayer_tcp.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. /*
  2. * This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  3. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  4. */
  5. #include "networklayer_tcp.h"
  6. #include <stdlib.h> // malloc, free
  7. #include <string.h> // memset
  8. #include <errno.h>
  9. #ifdef _WIN32
  10. # include <malloc.h>
  11. # include <winsock2.h>
  12. # include <ws2tcpip.h>
  13. # define CLOSESOCKET(S) closesocket(S)
  14. #else
  15. # include <fcntl.h>
  16. # include <sys/select.h>
  17. # include <netinet/in.h>
  18. # include <netinet/tcp.h>
  19. # include <sys/ioctl.h>
  20. # include <netdb.h> //gethostbyname for the client
  21. # include <unistd.h> // read, write, close
  22. # include <arpa/inet.h>
  23. # define CLOSESOCKET(S) close(S)
  24. #endif
  25. #ifdef UA_MULTITHREADING
  26. # include <urcu/uatomic.h>
  27. #endif
  28. /****************************/
  29. /* Generic Socket Functions */
  30. /****************************/
  31. static UA_StatusCode socket_write(UA_Connection *connection, UA_ByteString *buf, size_t buflen) {
  32. size_t nWritten = 0;
  33. while (nWritten < buflen) {
  34. UA_Int32 n = 0;
  35. do {
  36. #ifdef _WIN32
  37. n = send((SOCKET)connection->sockfd, (const char*)buf->data, buflen, 0);
  38. if(n < 0 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK)
  39. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  40. #else
  41. n = send(connection->sockfd, (const char*)buf->data, buflen, MSG_NOSIGNAL);
  42. if(n == -1L && errno != EINTR && errno != EAGAIN)
  43. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  44. #endif
  45. } while (n == -1L);
  46. nWritten += n;
  47. }
  48. #ifdef UA_MULTITHREADING
  49. UA_ByteString_deleteMembers(buf);
  50. #endif
  51. return UA_STATUSCODE_GOOD;
  52. }
  53. static UA_StatusCode socket_recv(UA_Connection *connection, UA_ByteString *response, UA_UInt32 timeout) {
  54. response->data = malloc(connection->localConf.recvBufferSize);
  55. if(!response->data)
  56. return UA_STATUSCODE_BADOUTOFMEMORY;
  57. struct timeval tmptv = {0, timeout * 1000};
  58. if(0 != setsockopt(connection->sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tmptv, sizeof(struct timeval))){
  59. free(response->data);
  60. return UA_STATUSCODE_BADINTERNALERROR;
  61. }
  62. int ret = recv(connection->sockfd, (char*)response->data, connection->localConf.recvBufferSize, 0);
  63. if(ret == 0) {
  64. free(response->data);
  65. UA_ByteString_init(response);
  66. return UA_STATUSCODE_GOOD; /* no response -> retry */
  67. } else if(ret < 0) {
  68. free(response->data);
  69. UA_ByteString_init(response);
  70. #ifdef _WIN32
  71. if(WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK) {
  72. #else
  73. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  74. #endif
  75. return UA_STATUSCODE_GOOD; /* retry */
  76. } else {
  77. connection->close(connection);
  78. connection->state = UA_CONNECTION_CLOSED;
  79. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  80. }
  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. if(!buf.data)
  370. continue;
  371. items[j].type = UA_JOBTYPE_BINARYMESSAGE;
  372. items[j].job.binaryMessage.message = buf;
  373. items[j].job.binaryMessage.connection = layer->mappings[i].connection;
  374. buf.data = NULL;
  375. } else {
  376. items[j].type = UA_JOBTYPE_CLOSECONNECTION;
  377. items[j].job.closeConnection = layer->mappings[i].connection;
  378. }
  379. j++;
  380. }
  381. /* add the delayed job that frees the connections */
  382. if(deletes) {
  383. items[j].type = UA_JOBTYPE_DELAYEDMETHODCALL;
  384. items[j].job.methodCall.data = deletes;
  385. items[j].job.methodCall.method = (void (*)(UA_Server *server, void *data))freeConnections;
  386. j++;
  387. }
  388. /* free the array if there is no job */
  389. if(j == 0) {
  390. free(items);
  391. *jobs = NULL;
  392. } else
  393. *jobs = items;
  394. return j;
  395. }
  396. static UA_Int32 ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Job **jobs) {
  397. ServerNetworkLayerTCP *layer = nl->handle;
  398. struct DeleteList *deletes;
  399. #ifdef UA_MULTITHREADING
  400. deletes = uatomic_xchg(&layer->deletes, NULL);
  401. #else
  402. deletes = layer->deletes;
  403. layer->deletes = NULL;
  404. #endif
  405. removeMappings(layer, deletes);
  406. UA_Job *items = malloc(sizeof(UA_Job) * layer->mappingsSize);
  407. if(!items)
  408. return 0;
  409. for(size_t i = 0; i < layer->mappingsSize; i++) {
  410. items[i].type = UA_JOBTYPE_CLOSECONNECTION;
  411. items[i].job.closeConnection = layer->mappings[i].connection;
  412. }
  413. #ifdef _WIN32
  414. WSACleanup();
  415. #endif
  416. *jobs = items;
  417. return layer->mappingsSize;
  418. }
  419. /* run only when the server is stopped */
  420. static void ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  421. ServerNetworkLayerTCP *layer = nl->handle;
  422. removeMappings(layer, layer->deletes);
  423. freeConnections(NULL, layer->deletes);
  424. #ifndef UA_MULTITHREADING
  425. UA_ByteString_deleteMembers(&layer->buffer);
  426. #endif
  427. for(size_t i = 0; i < layer->mappingsSize; i++)
  428. free(layer->mappings[i].connection);
  429. free(layer->mappings);
  430. free(layer);
  431. }
  432. UA_ServerNetworkLayer ServerNetworkLayerTCP_new(UA_ConnectionConfig conf, UA_UInt32 port) {
  433. #ifdef _WIN32
  434. WORD wVersionRequested;
  435. WSADATA wsaData;
  436. wVersionRequested = MAKEWORD(2, 2);
  437. WSAStartup(wVersionRequested, &wsaData);
  438. #endif
  439. UA_ServerNetworkLayer nl;
  440. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  441. ServerNetworkLayerTCP *layer = malloc(sizeof(ServerNetworkLayerTCP));
  442. if(!layer){
  443. return nl;
  444. }
  445. layer->conf = conf;
  446. layer->mappingsSize = 0;
  447. layer->mappings = NULL;
  448. layer->port = port;
  449. layer->deletes = NULL;
  450. char hostname[256];
  451. gethostname(hostname, 255);
  452. UA_String_copyprintf("opc.tcp://%s:%d", &nl.discoveryUrl, hostname, port);
  453. #ifndef UA_MULTITHREADING
  454. layer->buffer = (UA_ByteString){.length = conf.maxMessageSize, .data = malloc(conf.maxMessageSize)};
  455. #endif
  456. nl.handle = layer;
  457. nl.start = ServerNetworkLayerTCP_start;
  458. nl.getJobs = ServerNetworkLayerTCP_getJobs;
  459. nl.stop = ServerNetworkLayerTCP_stop;
  460. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  461. return nl;
  462. }
  463. /***************************/
  464. /* Client NetworkLayer TCP */
  465. /***************************/
  466. static UA_StatusCode ClientNetworkLayerGetBuffer(UA_Connection *connection, UA_ByteString *buf) {
  467. #ifndef UA_MULTITHREADING
  468. *buf = *(UA_ByteString*)connection->handle;
  469. return UA_STATUSCODE_GOOD;
  470. #else
  471. return UA_ByteString_newMembers(buf, connection->remoteConf.recvBufferSize);
  472. #endif
  473. }
  474. static void ClientNetworkLayerReleaseBuffer(UA_Connection *connection, UA_ByteString *buf) {
  475. #ifdef UA_MULTITHREADING
  476. UA_ByteString_deleteMembers(buf);
  477. #endif
  478. }
  479. static void ClientNetworkLayerClose(UA_Connection *connection) {
  480. if(connection->state == UA_CONNECTION_CLOSED)
  481. return;
  482. connection->state = UA_CONNECTION_CLOSED;
  483. socket_close(connection);
  484. #ifndef UA_MULTITHREADING
  485. UA_ByteString_delete(connection->handle);
  486. #endif
  487. }
  488. /* we have no networklayer. instead, attach the reusable buffer to the handle */
  489. UA_Connection ClientNetworkLayerTCP_connect(UA_ConnectionConfig localConf, char *endpointUrl,
  490. UA_Logger *logger) {
  491. UA_Connection connection;
  492. UA_Connection_init(&connection);
  493. connection.localConf = localConf;
  494. #ifndef UA_MULTITHREADING
  495. connection.handle = UA_ByteString_new();
  496. UA_ByteString_newMembers(connection.handle, localConf.maxMessageSize);
  497. #endif
  498. size_t urlLength = strlen(endpointUrl);
  499. if(urlLength < 11 || urlLength >= 512) {
  500. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Server url size invalid");
  501. return connection;
  502. }
  503. if(strncmp(endpointUrl, "opc.tcp://", 10) != 0) {
  504. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Server url does not begin with opc.tcp://");
  505. return connection;
  506. }
  507. UA_UInt16 portpos = 9;
  508. UA_UInt16 port = 0;
  509. for(;portpos < urlLength-1; portpos++) {
  510. if(endpointUrl[portpos] == ':') {
  511. port = atoi(&endpointUrl[portpos+1]);
  512. break;
  513. }
  514. }
  515. if(port == 0) {
  516. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Port invalid");
  517. return connection;
  518. }
  519. char hostname[512];
  520. for(int i=10; i < portpos; i++)
  521. hostname[i-10] = endpointUrl[i];
  522. hostname[portpos-10] = 0;
  523. #ifdef _WIN32
  524. WORD wVersionRequested;
  525. WSADATA wsaData;
  526. wVersionRequested = MAKEWORD(2, 2);
  527. WSAStartup(wVersionRequested, &wsaData);
  528. if((connection.sockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
  529. #else
  530. if((connection.sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  531. #endif
  532. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Could not create socket");
  533. return connection;
  534. }
  535. struct hostent *server = gethostbyname(hostname);
  536. if(server == NULL) {
  537. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "DNS lookup of %s failed", hostname);
  538. return connection;
  539. }
  540. struct sockaddr_in server_addr;
  541. memset(&server_addr, 0, sizeof(server_addr));
  542. memcpy((char *)&server_addr.sin_addr.s_addr, (char *)server->h_addr_list[0], server->h_length);
  543. server_addr.sin_family = AF_INET;
  544. server_addr.sin_port = htons(port);
  545. if(connect(connection.sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
  546. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Connection failed");
  547. return connection;
  548. }
  549. connection.state = UA_CONNECTION_OPENING;
  550. //socket_set_nonblocking(connection.sockfd);
  551. connection.write = socket_write;
  552. connection.recv = socket_recv;
  553. connection.close = ClientNetworkLayerClose;
  554. connection.getBuffer = ClientNetworkLayerGetBuffer;
  555. connection.releaseBuffer = ClientNetworkLayerReleaseBuffer;
  556. return connection;
  557. }