networklayer.c 16 KB

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