networklayer_tcp.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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_String discoveryUrl;
  143. UA_ConnectionConfig conf; /* todo: rename to localconf. */
  144. #ifndef UA_MULTITHREADING
  145. UA_ByteString buffer; // message buffer that is reused
  146. #endif
  147. /* open sockets and connections */
  148. fd_set fdset;
  149. UA_Int32 serversockfd;
  150. UA_Int32 highestfd;
  151. size_t mappingsSize;
  152. struct ConnectionMapping {
  153. UA_Connection *connection;
  154. UA_Int32 sockfd;
  155. } *mappings;
  156. /* to-be-deleted connections */
  157. struct DeleteList {
  158. struct DeleteList *next;
  159. UA_Connection *connection;
  160. } *deletes;
  161. } ServerNetworkLayerTCP;
  162. static UA_StatusCode ServerNetworkLayerGetBuffer(UA_Connection *connection, UA_ByteString *buf, size_t minSize) {
  163. #ifdef UA_MULTITHREADING
  164. return UA_ByteStringnewMembers(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(ServerNetworkLayerTCP *layer, UA_Logger *logger) {
  249. layer->logger = logger;
  250. #ifdef _WIN32
  251. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
  252. UA_LOG_WARNING((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Error opening socket, code: %d",
  253. WSAGetLastError());
  254. return UA_STATUSCODE_BADINTERNALERROR;
  255. }
  256. #else
  257. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  258. UA_LOG_WARNING((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Error opening socket");
  259. return UA_STATUSCODE_BADINTERNALERROR;
  260. }
  261. #endif
  262. const struct sockaddr_in serv_addr =
  263. {.sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  264. .sin_port = htons(layer->port), .sin_zero = {0}};
  265. int optval = 1;
  266. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  267. SO_REUSEADDR, (const char *)&optval,
  268. sizeof(optval)) == -1) {
  269. UA_LOG_WARNING((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Error during setting of socket options");
  270. CLOSESOCKET(layer->serversockfd);
  271. return UA_STATUSCODE_BADINTERNALERROR;
  272. }
  273. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  274. sizeof(serv_addr)) < 0) {
  275. UA_LOG_WARNING((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Error during socket binding");
  276. CLOSESOCKET(layer->serversockfd);
  277. return UA_STATUSCODE_BADINTERNALERROR;
  278. }
  279. socket_set_nonblocking(layer->serversockfd);
  280. listen(layer->serversockfd, MAXBACKLOG);
  281. UA_LOG_INFO((*layer->logger), UA_LOGCATEGORY_COMMUNICATION, "Listening on %.*s",
  282. layer->discoveryUrl.length, layer->discoveryUrl.data);
  283. return UA_STATUSCODE_GOOD;
  284. }
  285. /* delayed callback that frees old connections */
  286. static void freeConnections(UA_Server *server, struct DeleteList *d) {
  287. while(d) {
  288. UA_Connection_deleteMembers(d->connection);
  289. free(d->connection);
  290. struct DeleteList *old = d;
  291. d = d->next;
  292. free(old);
  293. }
  294. }
  295. /* remove the closed sockets from the mappings array */
  296. static void removeMappings(ServerNetworkLayerTCP *layer, struct DeleteList *d) {
  297. while(d) {
  298. size_t i = 0;
  299. for(; i < layer->mappingsSize; i++) {
  300. if(layer->mappings[i].sockfd == d->connection->sockfd)
  301. break;
  302. }
  303. if(i >= layer->mappingsSize)
  304. continue;
  305. layer->mappingsSize--;
  306. layer->mappings[i] = layer->mappings[layer->mappingsSize];
  307. d = d->next;
  308. }
  309. }
  310. static UA_Int32 ServerNetworkLayerTCP_getJobs(ServerNetworkLayerTCP *layer, UA_Job **jobs, UA_UInt16 timeout) {
  311. /* remove the deleted sockets from the array */
  312. struct DeleteList *deletes;
  313. #ifdef UA_MULTITHREADING
  314. deletes = uatomic_xchg(&layer->deletes, NULL);
  315. #else
  316. deletes = layer->deletes;
  317. layer->deletes = NULL;
  318. #endif
  319. removeMappings(layer, deletes);
  320. setFDSet(layer);
  321. struct timeval tmptv = {0, timeout};
  322. UA_Int32 resultsize = select(layer->highestfd+1, &layer->fdset, NULL, NULL, &tmptv);
  323. /* accept new connections (can only be a single one) */
  324. if(FD_ISSET(layer->serversockfd, &layer->fdset)) {
  325. resultsize--;
  326. struct sockaddr_in cli_addr;
  327. socklen_t cli_len = sizeof(cli_addr);
  328. int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
  329. int i = 1;
  330. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY, (void *)&i, sizeof(i));
  331. if (newsockfd >= 0) {
  332. socket_set_nonblocking(newsockfd);
  333. ServerNetworkLayerTCP_add(layer, newsockfd);
  334. }
  335. }
  336. if(!deletes && resultsize <= 0) {
  337. *jobs = NULL;
  338. return 0;
  339. }
  340. if(resultsize < 0)
  341. resultsize = 0;
  342. UA_Int32 deletesJob = 0;
  343. if(deletes)
  344. deletesJob = 1;
  345. UA_Job *items = malloc(sizeof(UA_Job) * (resultsize + deletesJob));
  346. if(deletes && !items) {
  347. /* abort. reattach the deletes so that they get deleted eventually. */
  348. #ifdef UA_MULTITHREADING
  349. struct DeleteList *last_delete;
  350. while(deletes) {
  351. last_delete = deletes;
  352. deletes = deletes->next;
  353. }
  354. while(1) {
  355. last_delete->next = layer->deletes;
  356. if(uatomic_cmpxchg(&layer->deletes, last_delete->next, deletes) == last_delete->next)
  357. break;
  358. }
  359. #else
  360. layer->deletes = deletes;
  361. #endif
  362. }
  363. /* read from established sockets */
  364. UA_Int32 j = 0;
  365. UA_ByteString buf = UA_BYTESTRING_NULL;
  366. for(size_t i = 0; i < layer->mappingsSize && j < resultsize; i++) {
  367. if(!(FD_ISSET(layer->mappings[i].sockfd, &layer->fdset)))
  368. continue;
  369. if(!buf.data) {
  370. buf.data = malloc(sizeof(UA_Byte) * layer->conf.recvBufferSize);
  371. buf.length = layer->conf.recvBufferSize;
  372. if(!buf.data)
  373. break;
  374. }
  375. if(socket_recv(layer->mappings[i].connection, &buf, 0) == UA_STATUSCODE_GOOD) {
  376. items[j].type = UA_JOBTYPE_BINARYMESSAGE;
  377. items[j].job.binaryMessage.message = buf;
  378. items[j].job.binaryMessage.connection = layer->mappings[i].connection;
  379. buf.data = NULL;
  380. } else {
  381. items[j].type = UA_JOBTYPE_CLOSECONNECTION;
  382. items[j].job.closeConnection = layer->mappings[i].connection;
  383. }
  384. j++;
  385. }
  386. /* add the delayed job that frees the connections */
  387. if(deletes) {
  388. items[j].type = UA_JOBTYPE_DELAYEDMETHODCALL;
  389. items[j].job.methodCall.data = deletes;
  390. items[j].job.methodCall.method = (void (*)(UA_Server *server, void *data))freeConnections;
  391. j++;
  392. }
  393. if(buf.data)
  394. free(buf.data);
  395. /* free the array if there is no job */
  396. if(j == 0) {
  397. free(items);
  398. *jobs = NULL;
  399. } else
  400. *jobs = items;
  401. return j;
  402. }
  403. static UA_Int32 ServerNetworkLayerTCP_stop(ServerNetworkLayerTCP *layer, UA_Job **jobs) {
  404. struct DeleteList *deletes;
  405. #ifdef UA_MULTITHREADING
  406. deletes = uatomic_xchg(&layer->deletes, NULL);
  407. #else
  408. deletes = layer->deletes;
  409. layer->deletes = NULL;
  410. #endif
  411. removeMappings(layer, deletes);
  412. UA_Job *items = malloc(sizeof(UA_Job) * layer->mappingsSize);
  413. if(!items)
  414. return 0;
  415. for(size_t i = 0; i < layer->mappingsSize; i++) {
  416. items[i].type = UA_JOBTYPE_CLOSECONNECTION;
  417. items[i].job.closeConnection = layer->mappings[i].connection;
  418. }
  419. #ifdef _WIN32
  420. WSACleanup();
  421. #endif
  422. *jobs = items;
  423. return layer->mappingsSize;
  424. }
  425. /* run only when the server is stopped */
  426. static void ServerNetworkLayerTCP_delete(ServerNetworkLayerTCP *layer) {
  427. UA_String_deleteMembers(&layer->discoveryUrl);
  428. removeMappings(layer, layer->deletes);
  429. freeConnections(NULL, layer->deletes);
  430. #ifndef UA_MULTITHREADING
  431. UA_ByteString_deleteMembers(&layer->buffer);
  432. #endif
  433. for(size_t i = 0; i < layer->mappingsSize; i++)
  434. free(layer->mappings[i].connection);
  435. free(layer->mappings);
  436. free(layer);
  437. }
  438. UA_ServerNetworkLayer ServerNetworkLayerTCP_new(UA_ConnectionConfig conf, UA_UInt32 port) {
  439. #ifdef _WIN32
  440. WORD wVersionRequested;
  441. WSADATA wsaData;
  442. wVersionRequested = MAKEWORD(2, 2);
  443. WSAStartup(wVersionRequested, &wsaData);
  444. #endif
  445. UA_ServerNetworkLayer nl;
  446. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  447. ServerNetworkLayerTCP *layer = malloc(sizeof(ServerNetworkLayerTCP));
  448. if(!layer){
  449. return nl;
  450. }
  451. layer->conf = conf;
  452. layer->mappingsSize = 0;
  453. layer->mappings = NULL;
  454. layer->port = port;
  455. layer->deletes = NULL;
  456. char hostname[256];
  457. gethostname(hostname, 255);
  458. UA_String_copyprintf("opc.tcp://%s:%d", &layer->discoveryUrl, hostname, port);
  459. #ifndef UA_MULTITHREADING
  460. layer->buffer = (UA_ByteString){.length = conf.maxMessageSize, .data = malloc(conf.maxMessageSize)};
  461. #endif
  462. nl.nlHandle = layer;
  463. nl.start = (UA_StatusCode (*)(void*, UA_Logger *logger))ServerNetworkLayerTCP_start;
  464. nl.getJobs = (UA_Int32 (*)(void*, UA_Job**, UA_UInt16))ServerNetworkLayerTCP_getJobs;
  465. nl.stop = (UA_Int32 (*)(void*, UA_Job**))ServerNetworkLayerTCP_stop;
  466. nl.free = (void (*)(void*))ServerNetworkLayerTCP_delete;
  467. nl.discoveryUrl = &layer->discoveryUrl;
  468. return nl;
  469. }
  470. /***************************/
  471. /* Client NetworkLayer TCP */
  472. /***************************/
  473. static UA_StatusCode ClientNetworkLayerGetBuffer(UA_Connection *connection, UA_ByteString *buf, size_t minSize) {
  474. #ifdef UA_MULTITHREADING
  475. *buf = *(UA_ByteString*)connection->handle;
  476. return UA_STATUSCODE_GOOD;
  477. #else
  478. return UA_ByteString_newMembers(buf, minSize);
  479. #endif
  480. }
  481. static void ClientNetworkLayerReleaseBuffer(UA_Connection *connection, UA_ByteString *buf) {
  482. #ifdef UA_MULTITHREADING
  483. UA_ByteString_deleteMembers(buf);
  484. #endif
  485. }
  486. static void ClientNetworkLayerClose(UA_Connection *connection) {
  487. socket_close(connection);
  488. #ifndef UA_MULTITHREADING
  489. UA_ByteString_delete(connection->handle);
  490. #endif
  491. }
  492. /* we have no networklayer. instead, attach the reusable buffer to the handle */
  493. UA_Connection ClientNetworkLayerTCP_connect(UA_ConnectionConfig localConf, char *endpointUrl,
  494. UA_Logger *logger) {
  495. UA_Connection connection;
  496. UA_Connection_init(&connection);
  497. connection.localConf = localConf;
  498. #ifndef UA_MULTITHREADING
  499. connection.handle = UA_ByteString_new();
  500. UA_ByteString_newMembers(connection.handle, localConf.maxMessageSize);
  501. #endif
  502. size_t urlLength = strlen(endpointUrl);
  503. if(urlLength < 11 || urlLength >= 512) {
  504. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Server url size invalid");
  505. return connection;
  506. }
  507. if(strncmp(endpointUrl, "opc.tcp://", 10) != 0) {
  508. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Server url does not begin with opc.tcp://");
  509. return connection;
  510. }
  511. UA_UInt16 portpos = 9;
  512. UA_UInt16 port = 0;
  513. for(;portpos < urlLength-1; portpos++) {
  514. if(endpointUrl[portpos] == ':') {
  515. port = atoi(&endpointUrl[portpos+1]);
  516. break;
  517. }
  518. }
  519. if(port == 0) {
  520. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Port invalid");
  521. return connection;
  522. }
  523. char hostname[512];
  524. for(int i=10; i < portpos; i++)
  525. hostname[i-10] = endpointUrl[i];
  526. hostname[portpos-10] = 0;
  527. #ifdef _WIN32
  528. WORD wVersionRequested;
  529. WSADATA wsaData;
  530. wVersionRequested = MAKEWORD(2, 2);
  531. WSAStartup(wVersionRequested, &wsaData);
  532. if((connection.sockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
  533. #else
  534. if((connection.sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  535. #endif
  536. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Could not create socket");
  537. return connection;
  538. }
  539. struct hostent *server = gethostbyname(hostname);
  540. if(server == NULL) {
  541. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "DNS lookup of %s failed", hostname);
  542. return connection;
  543. }
  544. struct sockaddr_in server_addr;
  545. memset(&server_addr, 0, sizeof(server_addr));
  546. memcpy((char *)&server_addr.sin_addr.s_addr, (char *)server->h_addr_list[0], server->h_length);
  547. server_addr.sin_family = AF_INET;
  548. server_addr.sin_port = htons(port);
  549. if(connect(connection.sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
  550. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_COMMUNICATION, "Connection failed");
  551. return connection;
  552. }
  553. connection.state = UA_CONNECTION_OPENING;
  554. //socket_set_nonblocking(connection.sockfd);
  555. connection.write = socket_write;
  556. connection.recv = socket_recv;
  557. connection.close = ClientNetworkLayerClose;
  558. connection.getBuffer = ClientNetworkLayerGetBuffer;
  559. connection.releaseBuffer = ClientNetworkLayerReleaseBuffer;
  560. return connection;
  561. }