networklayer.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. #include "networklayer.h"
  2. #include "ua_transport_connection.h"
  3. #ifdef WIN32
  4. #pragma comment (lib,"ws2_32.lib")
  5. #include <sys/types.h>
  6. #include <Windows.h>
  7. #include <ws2tcpip.h>
  8. #define CLOSESOCKET(S) closesocket(S); \
  9. WSACleanup();
  10. #define IOCTLSOCKET ioctlsocket
  11. #else
  12. #include <sys/socket.h>
  13. #include <netinet/in.h>
  14. #include <sys/socketvar.h>
  15. #include <unistd.h> // read, write, close
  16. #define CLOSESOCKET(S) close(S)
  17. #define IOCTLSOCKET ioctl
  18. #endif /* WIN32 */
  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: // timer due, call worker
  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. worker(arg);
  117. DBG_VERBOSE(printf("UA_Stack_msgLoop - return from worker\n"));
  118. }
  119. }
  120. else if (result > 0){ // activity on listener or client ports
  121. #endif
  122. DBG_VERBOSE(printf("UA_Stack_msgLoop - activities on %d handles\n",result));
  123. UA_list_iteratePayload(&(nl->connections),NL_checkFdSet);
  124. }
  125. // Calling worker here would execute worker any times we had received something or were interrupted
  126. // worker(arg);
  127. }
  128. return UA_SUCCESS;
  129. }
  130. #endif
  131. /** the tcp reader function */
  132. void* NL_TCP_reader(NL_Connection *c) {
  133. UA_ByteString readBuffer;
  134. TL_Buffer localBuffers;
  135. UA_Int32 connectionState;
  136. UA_TL_Connection_getLocalConfig(c->connection, &localBuffers);
  137. UA_alloc((void**)&(readBuffer.data),localBuffers.recvBufferSize);
  138. UA_TL_Connection_getState(c->connection, &connectionState);
  139. if (connectionState != CONNECTIONSTATE_CLOSE) {
  140. DBG_VERBOSE(printf("NL_TCP_reader - enter read\n"));
  141. #ifdef WIN32
  142. readBuffer.length = recv(c->connectionHandle, readBuffer.data, localBuffers.recvBufferSize, 0);
  143. #else
  144. readBuffer.length = read(c->connectionHandle, readBuffer.data, localBuffers.recvBufferSize);
  145. #endif
  146. DBG_VERBOSE(printf("NL_TCP_reader - leave read\n"));
  147. DBG_VERBOSE(printf("NL_TCP_reader - src={%*.s}, ",c->connection.remoteEndpointUrl.length,c->connection.remoteEndpointUrl.data));
  148. DBG(UA_ByteString_printx("NL_TCP_reader - received=",&readBuffer));
  149. if (errno != 0) {
  150. perror("NL_TCP_reader - ERROR reading from socket1");
  151. UA_TL_Connection_setState(c->connection, CONNECTIONSTATE_CLOSE);
  152. } else if (readBuffer.length > 0) {
  153. #ifdef DEBUG
  154. #include "ua_transport_binary_secure.h"
  155. UA_UInt32 pos = 0;
  156. UA_OPCUATcpMessageHeader header;
  157. UA_OPCUATcpMessageHeader_decodeBinary(&readBuffer, &pos, &header);
  158. pos = 24;
  159. if(header.messageType == UA_MESSAGETYPE_MSG)
  160. {
  161. UA_NodeId serviceRequestType;
  162. UA_NodeId_decodeBinary(&readBuffer, &pos,&serviceRequestType);
  163. UA_NodeId_printf("NL_TCP_reader - Service Type\n",&serviceRequestType);
  164. }
  165. #endif
  166. TL_Process((c->connection),&readBuffer);
  167. }
  168. }
  169. UA_TL_Connection_getState(c->connection, &connectionState);
  170. DBG_VERBOSE(printf("NL_TCP_reader - connectionState=%d\n",connectionState));
  171. if (connectionState == CONNECTIONSTATE_CLOSE) {
  172. DBG_VERBOSE(printf("NL_TCP_reader - closing connection"));
  173. // set connection's state to CONNECTIONSTATE_CLOSED and call callback to actually close
  174. UA_TL_Connection_close(c->connection);
  175. #ifndef MULTITHREADING
  176. DBG_VERBOSE(printf("NL_TCP_reader - search element to remove\n"));
  177. UA_list_Element* lec = UA_list_search(&(c->networkLayer->connections),NL_ConnectionComparer,c);
  178. DBG_VERBOSE(printf("NL_TCP_reader - remove connection for handle=%d\n",((NL_Connection*)lec->payload)->connection.connectionHandle));
  179. UA_list_removeElement(lec,UA_NULL);
  180. DBG_VERBOSE(UA_list_iteratePayload(&(c->networkLayer->connections),NL_Connection_printf));
  181. UA_free(c);
  182. #endif
  183. }
  184. UA_ByteString_deleteMembers(&readBuffer);
  185. return UA_NULL;
  186. }
  187. #ifdef MULTITHREADING
  188. /** the tcp reader thread */
  189. void* NL_TCP_readerThread(NL_Connection *c) {
  190. // just loop, NL_TCP_Reader will call the stack
  191. UA_Int32 connectionState;
  192. do {
  193. NL_TCP_reader(c);
  194. UA_TL_Connection_getState(c->connection, &connectionState);
  195. } while (connectionState != CONNECTIONSTATE_CLOSED);
  196. // clean up
  197. UA_free(c);
  198. pthread_exit(UA_NULL);
  199. }
  200. #endif
  201. /** write message provided in the gather buffers to a tcp transport layer connection */
  202. UA_Int32 NL_TCP_writer(UA_Int32 connectionHandle, UA_ByteString const * const * gather_buf, UA_UInt32 gather_len) {
  203. UA_UInt32 total_len = 0;
  204. #ifdef WIN32
  205. WSABUF *buf = malloc(gather_len * sizeof(WSABUF));
  206. int result = 0;
  207. for (UA_UInt32 i = 0; i<gather_len; i++) {
  208. buf[i].buf = gather_buf[i]->data;
  209. buf[i].len = gather_buf[i]->length;
  210. total_len += gather_buf[i]->length;
  211. // DBG(printf("NL_TCP_writer - gather_buf[%i]",i));
  212. // DBG(UA_ByteString_printx("=", gather_buf[i]));
  213. }
  214. #else
  215. struct iovec iov[gather_len];
  216. for(UA_UInt32 i=0;i<gather_len;i++) {
  217. iov[i].iov_base = gather_buf[i]->data;
  218. iov[i].iov_len = gather_buf[i]->length;
  219. total_len += gather_buf[i]->length;
  220. // DBG(printf("NL_TCP_writer - gather_buf[%i]",i));
  221. // DBG(UA_ByteString_printx("=", gather_buf[i]));
  222. }
  223. struct msghdr message;
  224. message.msg_name = UA_NULL;
  225. message.msg_namelen = 0;
  226. message.msg_iov = iov;
  227. message.msg_iovlen = gather_len;
  228. message.msg_control = UA_NULL;
  229. message.msg_controllen = 0;
  230. message.msg_flags = 0;
  231. #endif
  232. UA_UInt32 nWritten = 0;
  233. while (nWritten < total_len) {
  234. int n=0;
  235. do {
  236. DBG_VERBOSE(printf("NL_TCP_writer - enter write with %d bytes to write\n",total_len));
  237. #ifdef WIN32
  238. //result = WSASendMsg(connectionHandle,&message,0,&n,UA_NULL,UA_NULL);
  239. result = WSASend(connectionHandle, buf, gather_len , &n, 0, NULL, NULL);
  240. if(result != 0)
  241. {
  242. printf("NL_TCP_Writer - Error WSASend, code: %d \n", WSAGetLastError());
  243. }
  244. #else
  245. n = sendmsg(connectionHandle, &message, 0);
  246. #endif
  247. DBG_VERBOSE(printf("NL_TCP_writer - leave write with n=%d,errno={%d,%s}\n",n,(n>0)?0:errno,(n>0)?"":strerror(errno)));
  248. } while (n == -1L && errno == EINTR);
  249. if (n >= 0) {
  250. nWritten += n;
  251. break;
  252. // TODO: handle incompletely send messages
  253. } else {
  254. break;
  255. // TODO: error handling
  256. }
  257. }
  258. #ifdef WIN32
  259. free(buf);
  260. #endif
  261. return UA_SUCCESS;
  262. }
  263. //callback function which is called when the UA_TL_Connection_close() function is initiated
  264. UA_Int32 NL_Connection_close(UA_TL_Connection *connection)
  265. {
  266. NL_Connection *networkLayerData = UA_NULL;
  267. UA_TL_Connection_getNetworkLayerData(connection, (void**)&networkLayerData);
  268. if(networkLayerData != UA_NULL){
  269. DBG_VERBOSE(printf("NL_Connection_close - enter shutdown\n"));
  270. shutdown(networkLayerData->connectionHandle,2);
  271. DBG_VERBOSE(printf("NL_Connection_close - enter close\n"));
  272. CLOSESOCKET(networkLayerData->connectionHandle);
  273. FD_CLR(networkLayerData->connectionHandle, &networkLayerData->networkLayer->readerHandles);
  274. DBG_VERBOSE(printf("NL_Connection_close - leave close\n"));
  275. return UA_SUCCESS;
  276. }
  277. DBG_VERBOSE(printf("NL_Connection_close - ERROR: connection object invalid \n"));
  278. return UA_ERROR;
  279. }
  280. void* NL_Connection_init(NL_Connection* c, NL_data* tld, UA_Int32 connectionHandle, NL_Reader reader, TL_Writer writer)
  281. {
  282. UA_TL_Connection *connection = UA_NULL;
  283. //create new connection object
  284. UA_TL_Connection_new(&connection, tld->tld->localConf, writer, NL_Connection_close,connectionHandle,c);
  285. c->connection = connection;
  286. c->connectionHandle = connectionHandle;
  287. // network layer
  288. c->reader = reader;
  289. #ifdef MULTITHREADING
  290. c->readerThreadHandle = -1;
  291. #endif
  292. c->networkLayer = tld;
  293. return UA_NULL;
  294. }
  295. /** the tcp accept routine */
  296. void* NL_TCP_accept(NL_Connection* c) {
  297. NL_data* tld = c->networkLayer;
  298. if (tld->tld->maxConnections == -1 || tld->connections.size < tld->tld->maxConnections) {
  299. // accept only if not max number of connections exceeded
  300. struct sockaddr_in cli_addr;
  301. socklen_t cli_len = sizeof(cli_addr);
  302. DBG_VERBOSE(printf("NL_TCP_listen - enter accept\n"));
  303. int newsockfd = accept(c->connectionHandle, (struct sockaddr *) &cli_addr, &cli_len);
  304. DBG_VERBOSE(printf("NL_TCP_listen - leave accept\n"));
  305. if (newsockfd < 0) {
  306. DBG_ERR(printf("TL_TCP_listen - accept returns errno={%d,%s}\n",errno,strerror(errno)));
  307. perror("ERROR on accept");
  308. } else {
  309. DBG_VERBOSE(printf("NL_TCP_listen - new connection on %d\n",newsockfd));
  310. NL_Connection* cclient;
  311. UA_Int32 retval = UA_SUCCESS;
  312. retval |= UA_alloc((void**)&cclient,sizeof(NL_Connection));
  313. NL_Connection_init(cclient, tld, newsockfd, NL_TCP_reader, (TL_Writer) NL_TCP_writer);
  314. #ifdef MULTITHREADING
  315. pthread_create( &(cclient->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_readerThread, (void*) cclient);
  316. #else
  317. UA_list_addPayloadToBack(&(tld->connections),cclient);
  318. NL_TCP_SetNonBlocking(cclient->connectionHandle);
  319. #endif
  320. }
  321. } else {
  322. // no action necessary to reject connection
  323. }
  324. return UA_NULL;
  325. }
  326. #ifdef MULTITHREADING
  327. void* NL_TCP_listenThread(NL_Connection* c) {
  328. NL_data* tld = c->networkLayer;
  329. DBG_VERBOSE(printf("NL_TCP_listenThread - enter listen\n"));
  330. int retval = listen(c->connectionHandle, tld->tld->maxConnections);
  331. DBG_VERBOSE(printf("NL_TCP_listenThread - leave listen, retval=%d\n", retval));
  332. if (retval < 0) {
  333. // TODO: Error handling
  334. perror("NL_TCP_listen");
  335. DBG_ERR(printf("NL_TCP_listen retval=%d, errno={%d,%s}\n", retval, errno, strerror(errno)));
  336. } else {
  337. do {
  338. NL_TCP_accept(c);
  339. }
  340. } while (UA_TRUE);
  341. UA_free(c);
  342. pthread_exit(UA_NULL);
  343. }
  344. #endif
  345. UA_Int32 NL_TCP_init(NL_data* tld, UA_Int32 port) {
  346. UA_Int32 retval = UA_SUCCESS;
  347. // socket variables
  348. int newsockfd;
  349. struct sockaddr_in serv_addr;
  350. // create socket for listening to incoming connections
  351. #ifdef WIN32
  352. WORD wVersionRequested;
  353. WSADATA wsaData;
  354. int err;
  355. /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
  356. wVersionRequested = MAKEWORD(2, 2);
  357. err = WSAStartup(wVersionRequested, &wsaData);
  358. newsockfd = socket(PF_INET, SOCK_STREAM,0);
  359. if (newsockfd == INVALID_SOCKET){
  360. UA_Int32 lasterror = WSAGetLastError();
  361. printf("ERROR opening socket, code: %d\n",WSAGetLastError());
  362. #else
  363. newsockfd = socket(PF_INET, SOCK_STREAM, 0);
  364. if (newsockfd < 0) {
  365. #endif
  366. perror("ERROR opening socket");
  367. retval = UA_ERROR;
  368. }
  369. else {
  370. // set port number, options and bind
  371. memset((void *)&serv_addr, sizeof(serv_addr), 1);
  372. serv_addr.sin_family = AF_INET;
  373. serv_addr.sin_addr.s_addr = INADDR_ANY;
  374. serv_addr.sin_port = htons(port);
  375. int optval = 1;
  376. if (setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) == -1) {
  377. perror("setsockopt");
  378. retval = UA_ERROR;
  379. }
  380. else {
  381. // bind to port
  382. if (bind(newsockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  383. perror("ERROR on binding");
  384. retval = UA_ERROR;
  385. }
  386. else {
  387. UA_String_copyprintf("opc.tcp://localhost:%d/", &(tld->endpointUrl), port);
  388. }
  389. }
  390. }
  391. // finally
  392. if (retval == UA_SUCCESS) {
  393. DBG_VERBOSE(printf("NL_TCP_init - new listener on %d\n",newsockfd));
  394. NL_Connection* c;
  395. UA_Int32 retval = UA_SUCCESS;
  396. retval |= UA_alloc((void**)&c,sizeof(NL_Connection));
  397. NL_Connection_init(c, tld, newsockfd, NL_TCP_accept, (TL_Writer) NL_TCP_writer);
  398. #ifdef MULTITHREADING
  399. pthread_create( &(c->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_listenThread, (void*) c);
  400. #else
  401. UA_list_addPayloadToBack(&(tld->connections),c);
  402. NL_TCP_SetNonBlocking(c->connectionHandle);
  403. listen(c->connectionHandle, tld->tld->maxConnections);
  404. #endif
  405. }
  406. return retval;
  407. }
  408. /** checks arguments and dispatches to worker or refuses to init */
  409. NL_data* NL_init(NL_Description* tlDesc, UA_Int32 port) {
  410. NL_data* nl = UA_NULL;
  411. if (tlDesc->connectionType == NL_CONNECTIONTYPE_TCPV4 && tlDesc->encoding == NL_UA_ENCODING_BINARY) {
  412. UA_alloc((void**)&nl, sizeof(NL_data));
  413. nl->tld = tlDesc;
  414. FD_ZERO(&(nl->readerHandles));
  415. UA_list_init(&(nl->connections));
  416. NL_TCP_init(nl, port);
  417. }
  418. return nl;
  419. }