networklayer.c 13 KB

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