networklayer.c 16 KB

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