networklayer.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. #include "networklayer.h"
  2. #include "ua_transport_connection.h"
  3. #ifdef WIN32
  4. #include <sys/types.h>
  5. #include <Windows.h>
  6. #include <ws2tcpip.h>
  7. #define CLOSESOCKET(S) closesocket(S)
  8. #define IOCTLSOCKET ioctlsocket
  9. #else
  10. #include <sys/socket.h>
  11. #include <netinet/in.h>
  12. #include <sys/socketvar.h>
  13. #include <unistd.h> // read, write, close
  14. #define CLOSESOCKET(S) close(S)
  15. #define IOCTLSOCKET ioctl
  16. #endif /* WIN32 */
  17. #include <stdlib.h> // exit
  18. #include <errno.h> // errno, EINTR
  19. #include <memory.h> // memset
  20. #include <fcntl.h> // fcntl
  21. #ifdef ENABLE_MULTITHREADING
  22. #include <pthread.h>
  23. #endif
  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 ENABLE_MULTITHREADING
  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. u_long 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. #if 0
  85. char _str_error[256];
  86. char* strerror(int errno) {
  87. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  88. NULL, errno,
  89. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  90. &_str_error[0], 256, NULL);
  91. return &_str_error[0];
  92. }
  93. #endif
  94. UA_Int32 NL_msgLoop(NL_data* nl, struct timeval *tv, UA_Int32(*worker)(void*), void *arg, UA_Boolean *running) {
  95. UA_Int32 result;
  96. UA_Int32 err;
  97. while (*running) {
  98. // determine the largest handle
  99. nl->maxReaderHandle = 0;
  100. UA_list_iteratePayload(&(nl->connections),NL_setFdSet);
  101. DBG_VERBOSE(printf("\n------------\nUA_Stack_msgLoop - maxHandle=%d\n", nl->maxReaderHandle));
  102. // copy tv, some unixes do overwrite and return the remaining time
  103. // FIXME: actually we might want to do this ourselves to call the
  104. // worker on a more regular cyclic basis
  105. struct timeval tmptv;
  106. memcpy(&tmptv,tv,sizeof(struct timeval));
  107. // and wait
  108. DBG_VERBOSE(printf("UA_Stack_msgLoop - enter select sec=%d,usec=%d\n",(UA_Int32) tmptv.tv_sec, (UA_Int32) tmptv.tv_usec));
  109. result = select(nl->maxReaderHandle + 1, &(nl->readerHandles), UA_NULL, UA_NULL, &tmptv);
  110. 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));
  111. // handle timeout (winsock: result=0, unix: result=0,errno=0||EAGAIN)
  112. // and errors (winsock: result=SOCKET_ERROR (-1), unix: result = 0)
  113. if (result <= 0) {
  114. #ifdef WIN32
  115. err = (result == SOCKET_ERROR) ? WSAGetLastError() : 0;
  116. #else
  117. err = errno;
  118. #endif
  119. switch (err) {
  120. // handle known errors
  121. #ifdef WIN32
  122. case WSANOTINITIALISED:
  123. case WSAEFAULT:
  124. case WSAENETDOWN:
  125. case WSAEINVAL:
  126. case WSAEINTR:
  127. case WSAEINPROGRESS:
  128. case WSAENOTSOCK:
  129. #else
  130. case EBADF:
  131. case EINTR:
  132. case EINVAL:
  133. #endif
  134. // FIXME: handle errors
  135. printf("UA_Stack_msgLoop - result=%d, errno={%d,%s}\n", result, errno, strerror(errno));
  136. break;
  137. // otherwise we've got a timeout and call the worker
  138. #ifndef WIN32
  139. case EAGAIN:
  140. #endif
  141. default:
  142. DBG_VERBOSE(printf("UA_Stack_msgLoop - result=%d, errno={%d,%s}\n", result, errno, strerror(errno)));
  143. worker(arg);
  144. }
  145. } else { // activity on listener or client ports
  146. DBG_VERBOSE(printf("UA_Stack_msgLoop - activities on %d handles\n",result));
  147. UA_list_iteratePayload(&(nl->connections),NL_checkFdSet);
  148. // FIXME: Thought it would be a conceptional flaw to call the worker
  149. // here. However, there is no guarantee that the timeout would be
  150. // triggered, so we call it in this branch as well.
  151. worker(arg);
  152. }
  153. }
  154. #ifdef WIN32
  155. // finally we should clean up the winsock.dll
  156. WSACleanup();
  157. #endif
  158. return UA_SUCCESS;
  159. }
  160. #endif /* ENABLE_MULTITHREADING */
  161. /** the tcp reader function */
  162. void* NL_TCP_reader(NL_Connection *c) {
  163. UA_ByteString readBuffer;
  164. TL_Buffer localBuffers;
  165. UA_Int32 connectionState;
  166. UA_TL_Connection_getLocalConfig(c->connection, &localBuffers);
  167. UA_alloc((void**)&(readBuffer.data),localBuffers.recvBufferSize);
  168. UA_TL_Connection_getState(c->connection, &connectionState);
  169. if (connectionState != CONNECTIONSTATE_CLOSE) {
  170. DBG_VERBOSE(printf("NL_TCP_reader - enter read\n"));
  171. #ifdef WIN32
  172. readBuffer.length = recv(c->connectionHandle, (char *)readBuffer.data, localBuffers.recvBufferSize, 0);
  173. #else
  174. readBuffer.length = read(c->connectionHandle, readBuffer.data, localBuffers.recvBufferSize);
  175. #endif
  176. DBG_VERBOSE(printf("NL_TCP_reader - leave read\n"));
  177. DBG_VERBOSE(printf("NL_TCP_reader - src={%*.s}, ",c->connection.remoteEndpointUrl.length,c->connection.remoteEndpointUrl.data));
  178. DBG(UA_ByteString_printx("NL_TCP_reader - received=",&readBuffer));
  179. if (errno != 0) {
  180. perror("NL_TCP_reader - ERROR reading from socket1");
  181. UA_TL_Connection_setState(c->connection, CONNECTIONSTATE_CLOSE);
  182. } else if (readBuffer.length > 0) {
  183. #ifdef DEBUG
  184. #include "ua_transport_binary_secure.h"
  185. UA_UInt32 pos = 0;
  186. UA_OPCUATcpMessageHeader header;
  187. UA_OPCUATcpMessageHeader_decodeBinary(&readBuffer, &pos, &header);
  188. pos = 24;
  189. if(header.messageType == UA_MESSAGETYPE_MSG)
  190. {
  191. UA_NodeId serviceRequestType;
  192. UA_NodeId_decodeBinary(&readBuffer, &pos,&serviceRequestType);
  193. UA_NodeId_printf("NL_TCP_reader - Service Type\n",&serviceRequestType);
  194. }
  195. #endif
  196. TL_Process((c->connection),&readBuffer);
  197. } else {
  198. perror("NL_TCP_reader - ERROR reading from socket");
  199. UA_TL_Connection_setState(c->connection, CONNECTIONSTATE_CLOSE);
  200. }
  201. }
  202. UA_TL_Connection_getState(c->connection, &connectionState);
  203. DBG_VERBOSE(printf("NL_TCP_reader - connectionState=%d\n",connectionState));
  204. if (connectionState == CONNECTIONSTATE_CLOSE) {
  205. // set connection's state to CONNECTIONSTATE_CLOSED and call callback to actually close
  206. UA_TL_Connection_close(c->connection);
  207. #ifndef ENABLE_MULTITHREADING
  208. DBG_VERBOSE(printf("NL_TCP_reader - search element to remove\n"));
  209. UA_list_Element* lec = UA_list_search(&(c->networkLayer->connections),NL_ConnectionComparer,c);
  210. DBG_VERBOSE(printf("NL_TCP_reader - remove connection for handle=%d\n",((NL_Connection*)lec->payload)->connection.connectionHandle));
  211. UA_list_removeElement(lec,UA_NULL);
  212. DBG_VERBOSE(UA_list_iteratePayload(&(c->networkLayer->connections),NL_Connection_printf));
  213. UA_free(c);
  214. #endif
  215. }
  216. UA_ByteString_deleteMembers(&readBuffer);
  217. return UA_NULL;
  218. }
  219. #ifdef ENABLE_MULTITHREADING
  220. /** the tcp reader thread */
  221. void* NL_TCP_readerThread(NL_Connection *c) {
  222. // just loop, NL_TCP_Reader will call the stack
  223. UA_Int32 connectionState;
  224. do {
  225. NL_TCP_reader(c);
  226. UA_TL_Connection_getState(c->connection, &connectionState);
  227. } while (connectionState != CONNECTIONSTATE_CLOSED);
  228. // clean up
  229. UA_free(c);
  230. pthread_exit(UA_NULL);
  231. }
  232. #endif
  233. /** write message provided in the gather buffers to a tcp transport layer connection */
  234. UA_Int32 NL_TCP_writer(UA_Int32 connectionHandle, UA_ByteString const * const * gather_buf, UA_UInt32 gather_len) {
  235. UA_UInt32 total_len = 0;
  236. #ifdef WIN32
  237. WSABUF *buf = malloc(gather_len * sizeof(WSABUF));
  238. int result = 0;
  239. for (UA_UInt32 i = 0; i<gather_len; i++) {
  240. buf[i].buf = (char*)gather_buf[i]->data;
  241. buf[i].len = gather_buf[i]->length;
  242. total_len += gather_buf[i]->length;
  243. // DBG(printf("NL_TCP_writer - gather_buf[%i]",i));
  244. // DBG(UA_ByteString_printx("=", gather_buf[i]));
  245. }
  246. #else
  247. struct iovec iov[gather_len];
  248. for(UA_UInt32 i=0;i<gather_len;i++) {
  249. iov[i].iov_base = gather_buf[i]->data;
  250. iov[i].iov_len = gather_buf[i]->length;
  251. total_len += gather_buf[i]->length;
  252. // DBG(printf("NL_TCP_writer - gather_buf[%i]",i));
  253. // DBG(UA_ByteString_printx("=", gather_buf[i]));
  254. }
  255. struct msghdr message;
  256. message.msg_name = UA_NULL;
  257. message.msg_namelen = 0;
  258. message.msg_iov = iov;
  259. message.msg_iovlen = gather_len;
  260. message.msg_control = UA_NULL;
  261. message.msg_controllen = 0;
  262. message.msg_flags = 0;
  263. #endif
  264. UA_UInt32 nWritten = 0;
  265. #ifdef WIN32
  266. while (nWritten < total_len) {
  267. UA_UInt32 n=0;
  268. do {
  269. DBG_VERBOSE(printf("NL_TCP_writer - enter write with %d bytes to write\n",total_len));
  270. //result = WSASendMsg(connectionHandle,&message,0,&n,UA_NULL,UA_NULL);
  271. result = WSASend(connectionHandle, buf, gather_len , (LPDWORD)&n, 0, NULL, NULL);
  272. if(result != 0)
  273. printf("NL_TCP_Writer - Error WSASend, code: %d \n", WSAGetLastError());
  274. DBG_VERBOSE(printf("NL_TCP_writer - leave write with n=%d,errno={%d,%s}\n",n,(n>0)?0:errno,(n>0)?"":strerror(errno)));
  275. } while (errno == EINTR);
  276. nWritten += n;
  277. #else
  278. while (nWritten < total_len) {
  279. UA_Int32 n=0;
  280. do {
  281. DBG_VERBOSE(printf("NL_TCP_writer - enter write with %d bytes to write\n",total_len));
  282. n = sendmsg(connectionHandle, &message, 0);
  283. DBG_VERBOSE(printf("NL_TCP_writer - leave write with n=%d,errno={%d,%s}\n",n,(n>0)?0:errno,(n>0)?"":strerror(errno)));
  284. } while (n == -1L && errno == EINTR);
  285. if (n >= 0) {
  286. nWritten += n;
  287. break;
  288. // TODO: handle incompletely send messages
  289. } else {
  290. // TODO: error handling
  291. break;
  292. }
  293. #endif
  294. }
  295. #ifdef WIN32
  296. free(buf);
  297. #endif
  298. return UA_SUCCESS;
  299. }
  300. //callback function which is called when the UA_TL_Connection_close() function is initiated
  301. UA_Int32 NL_Connection_close(UA_TL_Connection *connection)
  302. {
  303. NL_Connection *networkLayerData = UA_NULL;
  304. UA_TL_Connection_getNetworkLayerData(connection, (void**)&networkLayerData);
  305. if(networkLayerData != UA_NULL){
  306. DBG_VERBOSE(printf("NL_Connection_close - enter shutdown\n"));
  307. shutdown(networkLayerData->connectionHandle,2);
  308. DBG_VERBOSE(printf("NL_Connection_close - enter close\n"));
  309. CLOSESOCKET(networkLayerData->connectionHandle);
  310. FD_CLR(networkLayerData->connectionHandle, &networkLayerData->networkLayer->readerHandles);
  311. DBG_VERBOSE(printf("NL_Connection_close - leave close\n"));
  312. return UA_SUCCESS;
  313. }
  314. DBG_VERBOSE(printf("NL_Connection_close - ERROR: connection object invalid \n"));
  315. return UA_ERROR;
  316. }
  317. void* NL_Connection_init(NL_Connection* c, NL_data* tld, UA_Int32 connectionHandle, NL_Reader reader, TL_Writer writer)
  318. {
  319. UA_TL_Connection *connection = UA_NULL;
  320. //create new connection object
  321. UA_TL_Connection_new(&connection, tld->tld->localConf, writer, NL_Connection_close,connectionHandle,c);
  322. c->connection = connection;
  323. c->connectionHandle = connectionHandle;
  324. // network layer
  325. c->reader = reader;
  326. #ifdef MULTITHREADING
  327. c->readerThreadHandle = -1;
  328. #endif
  329. c->networkLayer = tld;
  330. return UA_NULL;
  331. }
  332. /** the tcp accept routine */
  333. void* NL_TCP_accept(NL_Connection* c) {
  334. NL_data* tld = c->networkLayer;
  335. if (tld->tld->maxConnections == -1 || tld->connections.size < tld->tld->maxConnections) {
  336. // accept only if not max number of connections exceeded
  337. struct sockaddr_in cli_addr;
  338. socklen_t cli_len = sizeof(cli_addr);
  339. DBG_VERBOSE(printf("NL_TCP_listen - enter accept\n"));
  340. int newsockfd = accept(c->connectionHandle, (struct sockaddr *) &cli_addr, &cli_len);
  341. DBG_VERBOSE(printf("NL_TCP_listen - leave accept\n"));
  342. if (newsockfd < 0) {
  343. DBG_ERR(printf("TL_TCP_listen - accept returns errno={%d,%s}\n",errno,strerror(errno)));
  344. perror("ERROR on accept");
  345. } else {
  346. DBG_VERBOSE(printf("NL_TCP_listen - new connection on %d\n",newsockfd));
  347. NL_Connection* cclient;
  348. UA_Int32 retval = UA_SUCCESS;
  349. retval |= UA_alloc((void**)&cclient,sizeof(NL_Connection));
  350. NL_Connection_init(cclient, tld, newsockfd, NL_TCP_reader, (TL_Writer) NL_TCP_writer);
  351. #ifdef ENABLE_MULTITHREADING
  352. pthread_create( &(cclient->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_readerThread, (void*) cclient);
  353. #else
  354. UA_list_addPayloadToBack(&(tld->connections),cclient);
  355. NL_TCP_SetNonBlocking(cclient->connectionHandle);
  356. #endif
  357. }
  358. } else {
  359. // no action necessary to reject connection
  360. }
  361. return UA_NULL;
  362. }
  363. #ifdef ENABLE_MULTITHREADING
  364. void* NL_TCP_listenThread(NL_Connection* c) {
  365. NL_data* tld = c->networkLayer;
  366. DBG_VERBOSE(printf("NL_TCP_listenThread - enter listen\n"));
  367. int retval = listen(c->connectionHandle, tld->tld->maxConnections);
  368. DBG_VERBOSE(printf("NL_TCP_listenThread - leave listen, retval=%d\n", retval));
  369. if (retval < 0) {
  370. // TODO: Error handling
  371. perror("NL_TCP_listen");
  372. DBG_ERR(printf("NL_TCP_listen retval=%d, errno={%d,%s}\n", retval, errno, strerror(errno)));
  373. } else {
  374. do {
  375. NL_TCP_accept(c);
  376. }
  377. } while (UA_TRUE);
  378. UA_free(c);
  379. pthread_exit(UA_NULL);
  380. }
  381. #endif
  382. UA_Int32 NL_TCP_init(NL_data* tld, UA_Int32 port) {
  383. UA_Int32 retval = UA_SUCCESS;
  384. // socket variables
  385. #ifdef WIN32
  386. unsigned int newsockfd;
  387. #else
  388. int newsockfd;
  389. #endif
  390. struct sockaddr_in serv_addr;
  391. // create socket for listening to incoming connections
  392. #ifdef WIN32
  393. WORD wVersionRequested;
  394. WSADATA wsaData;
  395. /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
  396. wVersionRequested = MAKEWORD(2, 2);
  397. WSAStartup(wVersionRequested, &wsaData);
  398. newsockfd = socket(PF_INET, SOCK_STREAM,0);
  399. if (newsockfd == INVALID_SOCKET){
  400. //UA_Int32 lasterror = WSAGetLastError();
  401. printf("ERROR opening socket, code: %d\n",WSAGetLastError());
  402. #else
  403. newsockfd = socket(PF_INET, SOCK_STREAM, 0);
  404. if (newsockfd < 0) {
  405. #endif
  406. perror("ERROR opening socket");
  407. retval = UA_ERROR;
  408. }
  409. else {
  410. // set port number, options and bind
  411. memset((void *)&serv_addr, sizeof(serv_addr), 1);
  412. serv_addr.sin_family = AF_INET;
  413. serv_addr.sin_addr.s_addr = INADDR_ANY;
  414. serv_addr.sin_port = htons(port);
  415. int optval = 1;
  416. if (setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
  417. perror("setsockopt");
  418. close(newsockfd);
  419. retval = UA_ERROR;
  420. }
  421. else {
  422. // bind to port
  423. if (bind(newsockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  424. perror("ERROR on binding");
  425. close(newsockfd);
  426. retval = UA_ERROR;
  427. }
  428. else {
  429. UA_String_copyprintf("opc.tcp://localhost:%d/", &(tld->endpointUrl), port);
  430. }
  431. //#ifdef WIN32
  432. }
  433. //#endif
  434. }
  435. // finally
  436. if (retval == UA_SUCCESS) {
  437. DBG_VERBOSE(printf("NL_TCP_init - new listener on %d\n",newsockfd));
  438. NL_Connection* c;
  439. UA_Int32 retval = UA_SUCCESS;
  440. retval |= UA_alloc((void**)&c,sizeof(NL_Connection));
  441. NL_Connection_init(c, tld, newsockfd, NL_TCP_accept, (TL_Writer) NL_TCP_writer);
  442. #ifdef MULTITHREADING
  443. pthread_create( &(c->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_listenThread, (void*) c);
  444. #else
  445. UA_list_addPayloadToBack(&(tld->connections),c);
  446. NL_TCP_SetNonBlocking(c->connectionHandle);
  447. listen(c->connectionHandle, tld->tld->maxConnections);
  448. #endif
  449. }
  450. return retval;
  451. }
  452. /** checks arguments and dispatches to worker or refuses to init */
  453. NL_data* NL_init(NL_Description* tlDesc, UA_Int32 port) {
  454. NL_data* nl = UA_NULL;
  455. if (tlDesc->connectionType == NL_CONNECTIONTYPE_TCPV4 && tlDesc->encoding == NL_UA_ENCODING_BINARY) {
  456. UA_alloc((void**)&nl, sizeof(NL_data));
  457. nl->tld = tlDesc;
  458. FD_ZERO(&(nl->readerHandles));
  459. UA_list_init(&(nl->connections));
  460. NL_TCP_init(nl, port);
  461. }
  462. return nl;
  463. }