networklayer.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. #include "networklayer.h"
  2. #include "ua_transport_connection.h"
  3. #ifdef WIN32
  4. #pragma comment (lib,"ws2_32.lib")
  5. #define CLOSESOCKET(S) closesocket(S); \
  6. WSACleanup();
  7. #define IOCTLSOCKET ioctlsocket
  8. #include <sys/types.h>
  9. #include <Windows.h>
  10. #include <ws2tcpip.h>
  11. #else
  12. #define CLOSESOCKET(S) close(S)
  13. #define IOCTLSOCKET ioctl
  14. #include <sys/socket.h>
  15. #include <netinet/in.h>
  16. #include <sys/socketvar.h>
  17. #include <unistd.h> // read, write, close
  18. #endif
  19. #include <stdlib.h> // exit
  20. #include <errno.h> // errno, EINTR
  21. #include <memory.h> // memset
  22. #include <fcntl.h> // fcntl
  23. NL_Description NL_Description_TcpBinary = {
  24. NL_UA_ENCODING_BINARY,
  25. NL_CONNECTIONTYPE_TCPV4,
  26. NL_MAXCONNECTIONS_DEFAULT,
  27. {0,8192,8192,16384,1}
  28. };
  29. /* If we do not have multitasking, we implement a dispatcher-Pattern. All Connections
  30. * are collected in a list. From this list a fd_set is prepared and select then waits
  31. * for activities. We then iterate over the list, check if we've got some activites
  32. * and call the corresponding callback (reader, listener).
  33. */
  34. #ifndef MULTITASKING
  35. _Bool NL_ConnectionComparer(void *p1, void* p2) {
  36. NL_Connection* c1 = (NL_Connection*) p1;
  37. NL_Connection* c2 = (NL_Connection*) p2;
  38. return (c1->connectionHandle == c2->connectionHandle);
  39. }
  40. int NL_TCP_SetNonBlocking(int sock) {
  41. #ifdef WIN32
  42. UA_Int64 iMode = 1;
  43. int opts = IOCTLSOCKET(sock, FIONBIO, &iMode);
  44. if (opts != NO_ERROR){
  45. printf("ioctlsocket failed with error: %ld\n", opts);
  46. return - 1;
  47. }
  48. #else
  49. int opts = fcntl(sock,F_GETFL);
  50. if (opts < 0) {
  51. perror("fcntl(F_GETFL)");
  52. return -1;
  53. }
  54. opts = (opts | O_NONBLOCK);
  55. if (fcntl(sock,F_SETFL,opts) < 0) {
  56. perror("fcntl(F_SETFL)");
  57. return -1;
  58. }
  59. #endif
  60. return 0;
  61. }
  62. void NL_Connection_printf(void* payload) {
  63. NL_Connection* c = (NL_Connection*) payload;
  64. printf("ListElement connectionHandle = %d\n",c->connectionHandle);
  65. }
  66. void NL_addHandleToSet(UA_Int32 handle, NL_data* nl) {
  67. FD_SET(handle, &(nl->readerHandles));
  68. #ifdef WIN32
  69. int err = WSAGetLastError();
  70. #endif
  71. nl->maxReaderHandle = (handle > nl->maxReaderHandle) ? handle : nl->maxReaderHandle;
  72. }
  73. void NL_setFdSet(void* payload) {
  74. NL_Connection* c = (NL_Connection*) payload;
  75. NL_addHandleToSet(c->connectionHandle, c->networkLayer);
  76. }
  77. void NL_checkFdSet(void* payload) {
  78. NL_Connection* c = (NL_Connection*) payload;
  79. if (FD_ISSET(c->connectionHandle, &(c->networkLayer->readerHandles))) {
  80. c->reader((void*)c);
  81. }
  82. }
  83. UA_Int32 NL_msgLoop(NL_data* nl, struct timeval *tv, UA_Int32(*worker)(void*), void *arg, UA_Boolean *running) {
  84. UA_Int32 result;
  85. while (*running) {
  86. // determine the largest handle
  87. nl->maxReaderHandle = 0;
  88. UA_list_iteratePayload(&(nl->connections),NL_setFdSet);
  89. DBG_VERBOSE(printf("\n------------\nUA_Stack_msgLoop - maxHandle=%d\n", nl->maxReaderHandle));
  90. // copy tv, some unixes do overwrite and return the remaining time
  91. struct timeval tmptv;
  92. memcpy(&tmptv,tv,sizeof(struct timeval));
  93. // and wait
  94. DBG_VERBOSE(printf("UA_Stack_msgLoop - enter select sec=%d,usec=%d\n",(UA_Int32) tmptv.tv_sec, (UA_Int32) tmptv.tv_usec));
  95. result = select(nl->maxReaderHandle + 1, &(nl->readerHandles), UA_NULL, UA_NULL, &tmptv);
  96. DBG_VERBOSE(printf("UA_Stack_msgLoop - leave select result=%d,sec=%d,usec=%d\n",result, (UA_Int32) tmptv.tv_sec, (UA_Int32) tmptv.tv_usec));
  97. #ifdef WIN32
  98. if (result == -1) {
  99. DBG_ERR(printf("UA_Stack_msgLoop - errno = { %d, %s }\n", WSAGetLastError()));
  100. }
  101. else if (result >= 0){ // activity on listener or client ports
  102. #else
  103. if (result == 0) {
  104. UA_Int32 err = errno;
  105. switch (err) {
  106. case EBADF:
  107. case EINTR:
  108. case EINVAL:
  109. //FIXME: handle errors
  110. DBG_ERR(printf("UA_Stack_msgLoop - errno={%d,%s}\n", errno, strerror(errno)));
  111. break;
  112. case EAGAIN:
  113. default:
  114. DBG_VERBOSE(printf("UA_Stack_msgLoop - errno={%d,%s}\n", errno, strerror(errno)));
  115. DBG_VERBOSE(printf("UA_Stack_msgLoop - call worker\n"));
  116. DBG_VERBOSE(printf("UA_Stack_msgLoop - return from worker\n"));
  117. }
  118. }
  119. else if (result > 0){ // activity on listener or client ports
  120. #endif
  121. DBG_VERBOSE(printf("UA_Stack_msgLoop - activities on %d handles\n",result));
  122. UA_list_iteratePayload(&(nl->connections),NL_checkFdSet);
  123. }
  124. worker(arg);
  125. }
  126. return UA_SUCCESS;
  127. }
  128. #endif
  129. /** the tcp reader function */
  130. void* NL_TCP_reader(NL_Connection *c) {
  131. UA_ByteString readBuffer;
  132. TL_Buffer localBuffers;
  133. UA_Int32 connectionState;
  134. UA_TL_Connection_getLocalConfig(c->connection, &localBuffers);
  135. UA_alloc((void**)&(readBuffer.data),localBuffers.recvBufferSize);
  136. if (c->state != CONNECTIONSTATE_CLOSE) {
  137. DBG_VERBOSE(printf("NL_TCP_reader - enter read\n"));
  138. #ifdef WIN32
  139. readBuffer.length = recv(c->connectionHandle, readBuffer.data, localBuffers.recvBufferSize, 0);
  140. #else
  141. readBuffer.length = read(c->connectionHandle, readBuffer.data, localBuffers.recvBufferSize);
  142. #endif
  143. DBG_VERBOSE(printf("NL_TCP_reader - leave read\n"));
  144. DBG_VERBOSE(printf("NL_TCP_reader - src={%*.s}, ",c->connection.remoteEndpointUrl.length,c->connection.remoteEndpointUrl.data));
  145. DBG(UA_ByteString_printx("NL_TCP_reader - received=",&readBuffer));
  146. if (readBuffer.length > 0) {
  147. #ifdef DEBUG
  148. #include "ua_transport_binary_secure.h"
  149. UA_UInt32 pos = 0;
  150. UA_OPCUATcpMessageHeader header;
  151. UA_OPCUATcpMessageHeader_decodeBinary(&readBuffer, &pos, &header);
  152. pos = 24;
  153. if(header.messageType == UA_MESSAGETYPE_MSG)
  154. {
  155. UA_NodeId serviceRequestType;
  156. UA_NodeId_decodeBinary(&readBuffer, &pos,&serviceRequestType);
  157. UA_NodeId_printf("Service Type\n",&serviceRequestType);
  158. }
  159. #endif
  160. TL_Process((c->connection),&readBuffer);
  161. } else {
  162. //TODO close connection - what does close do?
  163. c->state = CONNECTIONSTATE_CLOSE;
  164. //c->connection.connectionState = CONNECTIONSTATE_CLOSE;
  165. perror("ERROR reading from socket1");
  166. }
  167. }
  168. UA_TL_Connection_getState(c->connection, &connectionState);
  169. if (connectionState == CONNECTIONSTATE_CLOSE) {
  170. UA_TL_Connection_close(c->connection);
  171. #ifndef MULTITHREADING
  172. DBG_VERBOSE(printf("NL_TCP_reader - search element to remove\n"));
  173. UA_list_Element* lec = UA_list_search(&(c->networkLayer->connections),NL_ConnectionComparer,c);
  174. DBG_VERBOSE(printf("NL_TCP_reader - remove connection for handle=%d\n",((NL_Connection*)lec->payload)->connection.connectionHandle));
  175. UA_list_removeElement(lec,UA_NULL);
  176. DBG_VERBOSE(UA_list_iteratePayload(&(c->networkLayer->connections),NL_Connection_printf));
  177. UA_free(c);
  178. #endif
  179. }
  180. UA_ByteString_deleteMembers(&readBuffer);
  181. return UA_NULL;
  182. }
  183. #ifdef MULTITHREADING
  184. /** the tcp reader thread */
  185. void* NL_TCP_readerThread(NL_Connection *c) {
  186. // just loop, NL_TCP_Reader will call the stack
  187. do {
  188. NL_TCP_reader(c);
  189. } while (c->connection.connectionState != CONNECTIONSTATE_CLOSED);
  190. // clean up
  191. UA_free(c);
  192. pthread_exit(UA_NULL);
  193. }
  194. #endif
  195. /** write message provided in the gather buffers to a tcp transport layer connection */
  196. UA_Int32 NL_TCP_writer(UA_Int32 connectionHandle, UA_ByteString const * const * gather_buf, UA_UInt32 gather_len) {
  197. UA_UInt32 total_len = 0;
  198. #ifdef WIN32
  199. WSABUF *buf = malloc(gather_len * sizeof(WSABUF));
  200. int result = 0;
  201. for (UA_UInt32 i = 0; i<gather_len; i++) {
  202. buf[i].buf = gather_buf[i]->data;
  203. buf[i].len = gather_buf[i]->length;
  204. total_len += gather_buf[i]->length;
  205. // DBG(printf("NL_TCP_writer - gather_buf[%i]",i));
  206. // DBG(UA_ByteString_printx("=", gather_buf[i]));
  207. }
  208. #else
  209. struct iovec iov[gather_len];
  210. for(UA_UInt32 i=0;i<gather_len;i++) {
  211. iov[i].iov_base = gather_buf[i]->data;
  212. iov[i].iov_len = gather_buf[i]->length;
  213. total_len += gather_buf[i]->length;
  214. // DBG(printf("NL_TCP_writer - gather_buf[%i]",i));
  215. // DBG(UA_ByteString_printx("=", gather_buf[i]));
  216. }
  217. struct msghdr message;
  218. message.msg_name = UA_NULL;
  219. message.msg_namelen = 0;
  220. message.msg_iov = iov;
  221. message.msg_iovlen = gather_len;
  222. message.msg_control = UA_NULL;
  223. message.msg_controllen = 0;
  224. message.msg_flags = 0;
  225. #endif
  226. UA_UInt32 nWritten = 0;
  227. while (nWritten < total_len) {
  228. int n=0;
  229. do {
  230. DBG_VERBOSE(printf("NL_TCP_writer - enter write with %d bytes to write\n",total_len));
  231. #ifdef WIN32
  232. //result = WSASendMsg(connectionHandle,&message,0,&n,UA_NULL,UA_NULL);
  233. result = WSASend(connectionHandle, buf, gather_len , &n, 0, NULL, NULL);
  234. if(result != 0)
  235. {
  236. printf("NL_TCP_Writer - Error WSASend, code: %d \n", WSAGetLastError());
  237. }
  238. #else
  239. n = sendmsg(connectionHandle, &message, 0);
  240. #endif
  241. DBG_VERBOSE(printf("NL_TCP_writer - leave write with n=%d,errno={%d,%s}\n",n,(n>0)?0:errno,(n>0)?"":strerror(errno)));
  242. } while (n == -1L && errno == EINTR);
  243. if (n >= 0) {
  244. nWritten += n;
  245. break;
  246. // TODO: handle incompletely send messages
  247. } else {
  248. break;
  249. // TODO: error handling
  250. }
  251. }
  252. #ifdef WIN32
  253. free(buf);
  254. #endif
  255. return UA_SUCCESS;
  256. }
  257. //callback function which is called when the UA_TL_Connection_close() function is initiated
  258. UA_Int32 NL_Connection_close(UA_TL_Connection *connection)
  259. {
  260. NL_Connection *networkLayerData = UA_NULL;
  261. UA_TL_Connection_getNetworkLayerData(connection, (void**)&networkLayerData);
  262. if(networkLayerData != UA_NULL){
  263. DBG_VERBOSE(printf("NL_Connection_close - enter shutdown\n"));
  264. shutdown(networkLayerData->connectionHandle,2);
  265. DBG_VERBOSE(printf("NL_Connection_close - enter close\n"));
  266. CLOSESOCKET(networkLayerData->connectionHandle);
  267. FD_CLR(networkLayerData->connectionHandle, &networkLayerData->networkLayer->readerHandles);
  268. DBG_VERBOSE(printf("NL_Connection_close - leave close\n"));
  269. return UA_SUCCESS;
  270. }
  271. DBG_VERBOSE(printf("NL_Connection_close - ERROR: connection object invalid \n"));
  272. return UA_ERROR;
  273. }
  274. void* NL_Connection_init(NL_Connection* c, NL_data* tld, UA_Int32 connectionHandle, NL_Reader reader, TL_Writer writer)
  275. {
  276. UA_TL_Connection *connection = UA_NULL;
  277. //create new connection object
  278. UA_TL_Connection_new(&connection, tld->tld->localConf, writer, NL_Connection_close,connectionHandle,c);
  279. c->connection = connection;
  280. c->connectionHandle = connectionHandle;
  281. // network layer
  282. c->reader = reader;
  283. #ifdef MULTITHREADING
  284. c->readerThreadHandle = -1;
  285. #endif
  286. c->networkLayer = tld;
  287. return UA_NULL;
  288. }
  289. /** the tcp accept routine */
  290. void* NL_TCP_accept(NL_Connection* c) {
  291. NL_data* tld = c->networkLayer;
  292. if (tld->tld->maxConnections == -1 || tld->connections.size < tld->tld->maxConnections) {
  293. // accept only if not max number of connections exceeded
  294. struct sockaddr_in cli_addr;
  295. socklen_t cli_len = sizeof(cli_addr);
  296. DBG_VERBOSE(printf("NL_TCP_listen - enter accept\n"));
  297. int newsockfd = accept(c->connectionHandle, (struct sockaddr *) &cli_addr, &cli_len);
  298. DBG_VERBOSE(printf("NL_TCP_listen - leave accept\n"));
  299. if (newsockfd < 0) {
  300. DBG_ERR(printf("TL_TCP_listen - accept returns errno={%d,%s}\n",errno,strerror(errno)));
  301. perror("ERROR on accept");
  302. } else {
  303. DBG_VERBOSE(printf("NL_TCP_listen - new connection on %d\n",newsockfd));
  304. NL_Connection* cclient;
  305. UA_Int32 retval = UA_SUCCESS;
  306. retval |= UA_alloc((void**)&cclient,sizeof(NL_Connection));
  307. NL_Connection_init(cclient, tld, newsockfd, NL_TCP_reader, (TL_Writer) NL_TCP_writer);
  308. #ifdef MULTITHREADING
  309. pthread_create( &(cclient->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_readerThread, (void*) cclient);
  310. #else
  311. UA_list_addPayloadToBack(&(tld->connections),cclient);
  312. NL_TCP_SetNonBlocking(cclient->connectionHandle);
  313. #endif
  314. }
  315. } else {
  316. // no action necessary to reject connection
  317. }
  318. return UA_NULL;
  319. }
  320. #ifdef MULTITHREADING
  321. void* NL_TCP_listenThread(NL_Connection* c) {
  322. NL_data* tld = c->networkLayer;
  323. do {
  324. DBG_VERBOSE(printf("NL_TCP_listenThread - enter listen\n"));
  325. int retval = listen(c->connectionHandle, tld->tld->maxConnections);
  326. DBG_VERBOSE(printf("NL_TCP_listenThread - leave listen, retval=%d\n", retval));
  327. if (retval < 0) {
  328. // TODO: Error handling
  329. perror("NL_TCP_listen");
  330. DBG_ERR(printf("NL_TCP_listen retval=%d, errno={%d,%s}\n", retval, errno, strerror(errno)));
  331. } else {
  332. NL_TCP_accept(c);
  333. }
  334. } while (UA_TRUE);
  335. UA_free(c);
  336. pthread_exit(UA_NULL);
  337. }
  338. #endif
  339. UA_Int32 NL_TCP_init(NL_data* tld, UA_Int32 port) {
  340. UA_Int32 retval = UA_SUCCESS;
  341. // socket variables
  342. int newsockfd;
  343. struct sockaddr_in serv_addr;
  344. // create socket for listening to incoming connections
  345. #ifdef WIN32
  346. WORD wVersionRequested;
  347. WSADATA wsaData;
  348. int err;
  349. /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
  350. wVersionRequested = MAKEWORD(2, 2);
  351. err = WSAStartup(wVersionRequested, &wsaData);
  352. newsockfd = socket(PF_INET, SOCK_STREAM,0);
  353. if (newsockfd == INVALID_SOCKET){
  354. UA_Int32 lasterror = WSAGetLastError();
  355. printf("ERROR opening socket, code: %d\n",WSAGetLastError());
  356. #else
  357. newsockfd = socket(PF_INET, SOCK_STREAM, 0);
  358. if (newsockfd < 0) {
  359. #endif
  360. perror("ERROR opening socket");
  361. retval = UA_ERROR;
  362. }
  363. else {
  364. // set port number, options and bind
  365. memset((void *)&serv_addr, sizeof(serv_addr), 1);
  366. serv_addr.sin_family = AF_INET;
  367. serv_addr.sin_addr.s_addr = INADDR_ANY;
  368. serv_addr.sin_port = htons(port);
  369. int optval = 1;
  370. if (setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) == -1) {
  371. perror("setsockopt");
  372. retval = UA_ERROR;
  373. }
  374. else {
  375. // bind to port
  376. if (bind(newsockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  377. perror("ERROR on binding");
  378. retval = UA_ERROR;
  379. }
  380. else {
  381. UA_String_copyprintf("opc.tcp://localhost:%d/", &(tld->endpointUrl), port);
  382. }
  383. }
  384. }
  385. // finally
  386. if (retval == UA_SUCCESS) {
  387. DBG_VERBOSE(printf("NL_TCP_init - new listener on %d\n",newsockfd));
  388. NL_Connection* c;
  389. UA_Int32 retval = UA_SUCCESS;
  390. retval |= UA_alloc((void**)&c,sizeof(NL_Connection));
  391. NL_Connection_init(c, tld, newsockfd, NL_TCP_accept, (TL_Writer) NL_TCP_writer);
  392. #ifdef MULTITHREADING
  393. pthread_create( &(c->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_listenThread, (void*) c);
  394. #else
  395. UA_list_addPayloadToBack(&(tld->connections),c);
  396. NL_TCP_SetNonBlocking(c->connectionHandle);
  397. listen(c->connectionHandle, tld->tld->maxConnections);
  398. #endif
  399. }
  400. return retval;
  401. }
  402. /** checks arguments and dispatches to worker or refuses to init */
  403. NL_data* NL_init(NL_Description* tlDesc, UA_Int32 port) {
  404. NL_data* nl = UA_NULL;
  405. if (tlDesc->connectionType == NL_CONNECTIONTYPE_TCPV4 && tlDesc->encoding == NL_UA_ENCODING_BINARY) {
  406. UA_alloc((void**)&nl, sizeof(NL_data));
  407. nl->tld = tlDesc;
  408. FD_ZERO(&(nl->readerHandles));
  409. UA_list_init(&(nl->connections));
  410. NL_TCP_init(nl, port);
  411. }
  412. return nl;
  413. }