networklayer.c 15 KB

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