networklayer.c 14 KB

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