networklayer.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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_TL_Connection_getLocalConfig(c->connection, &localBuffers);
  104. UA_alloc((void**)&(readBuffer.data),localBuffers.recvBufferSize);
  105. if (c->state != CONNECTIONSTATE_CLOSE) {
  106. DBG_VERBOSE(printf("NL_TCP_reader - enter read\n"));
  107. readBuffer.length = read(c->connectionHandle, readBuffer.data, localBuffers.recvBufferSize);
  108. DBG_VERBOSE(printf("NL_TCP_reader - leave read\n"));
  109. DBG_VERBOSE(printf("NL_TCP_reader - src={%*.s}, ",c->connection.remoteEndpointUrl.length,c->connection.remoteEndpointUrl.data));
  110. DBG(UA_ByteString_printx("NL_TCP_reader - received=",&readBuffer));
  111. if (readBuffer.length > 0) {
  112. #ifdef DEBUG
  113. #include "ua_transport_binary_secure.h"
  114. UA_UInt32 pos = 0;
  115. UA_OPCUATcpMessageHeader header;
  116. UA_OPCUATcpMessageHeader_decodeBinary(&readBuffer, &pos, &header);
  117. pos = 24;
  118. if(header.messageType == UA_MESSAGETYPE_MSG)
  119. {
  120. UA_NodeId serviceRequestType;
  121. UA_NodeId_decodeBinary(&readBuffer, &pos,&serviceRequestType);
  122. UA_NodeId_printf("Service Type\n",&serviceRequestType);
  123. }
  124. #endif
  125. TL_Process((c->connection),&readBuffer);
  126. } else {
  127. //TODO close connection - what does close do?
  128. c->state = CONNECTIONSTATE_CLOSE;
  129. //c->connection.connectionState = CONNECTIONSTATE_CLOSE;
  130. perror("ERROR reading from socket1");
  131. }
  132. }
  133. UA_TL_Connection_getState(c->connection, &connectionState);
  134. if (connectionState == CONNECTIONSTATE_CLOSE) {
  135. UA_TL_Connection_close(c->connection);
  136. //c->state = CONNECTIONSTATE_CLOSED;
  137. #ifndef MULTITHREADING
  138. DBG_VERBOSE(printf("NL_TCP_reader - search element to remove\n"));
  139. UA_list_Element* lec = UA_list_search(&(c->networkLayer->connections),NL_ConnectionComparer,c);
  140. DBG_VERBOSE(printf("NL_TCP_reader - remove connection for handle=%d\n",((NL_Connection*)lec->payload)->connection.connectionHandle));
  141. UA_list_removeElement(lec,UA_NULL);
  142. DBG_VERBOSE(UA_list_iteratePayload(&(c->networkLayer->connections),NL_Connection_printf));
  143. UA_free(c);
  144. #endif
  145. }
  146. UA_ByteString_deleteMembers(&readBuffer);
  147. return UA_NULL;
  148. }
  149. #ifdef MULTITHREADING
  150. /** the tcp reader thread */
  151. void* NL_TCP_readerThread(NL_Connection *c) {
  152. // just loop, NL_TCP_Reader will call the stack
  153. do {
  154. NL_TCP_reader(c);
  155. } while (c->connection.connectionState != CONNECTIONSTATE_CLOSED);
  156. // clean up
  157. UA_free(c);
  158. pthread_exit(UA_NULL);
  159. }
  160. #endif
  161. /** write message provided in the gather buffers to a tcp transport layer connection */
  162. UA_Int32 NL_TCP_writer(UA_Int32 connectionHandle, UA_ByteString const * const * gather_buf, UA_UInt32 gather_len) {
  163. struct iovec iov[gather_len];
  164. UA_UInt32 total_len = 0;
  165. for(UA_UInt32 i=0;i<gather_len;i++) {
  166. iov[i].iov_base = gather_buf[i]->data;
  167. iov[i].iov_len = gather_buf[i]->length;
  168. total_len += gather_buf[i]->length;
  169. // DBG(printf("NL_TCP_writer - gather_buf[%i]",i));
  170. // DBG(UA_ByteString_printx("=", gather_buf[i]));
  171. }
  172. struct msghdr message;
  173. message.msg_name = UA_NULL;
  174. message.msg_namelen = 0;
  175. message.msg_iov = iov;
  176. message.msg_iovlen = gather_len;
  177. message.msg_control = UA_NULL;
  178. message.msg_controllen = 0;
  179. message.msg_flags = 0;
  180. UA_UInt32 nWritten = 0;
  181. while (nWritten < total_len) {
  182. int n=0;
  183. do {
  184. DBG_VERBOSE(printf("NL_TCP_writer - enter write with %d bytes to write\n",total_len));
  185. n = sendmsg(connectionHandle, &message, 0);
  186. DBG_VERBOSE(printf("NL_TCP_writer - leave write with n=%d,errno={%d,%s}\n",n,(n>0)?0:errno,(n>0)?"":strerror(errno)));
  187. } while (n == -1L && errno == EINTR);
  188. if (n >= 0) {
  189. nWritten += n;
  190. break;
  191. // TODO: handle incompletely send messages
  192. } else {
  193. break;
  194. // TODO: error handling
  195. }
  196. }
  197. return UA_SUCCESS;
  198. }
  199. //callback function which is called when the UA_TL_Connection_close() function is initiated
  200. UA_Int32 NL_Connection_close(UA_TL_Connection connection)
  201. {
  202. NL_Connection *networkLayerData = UA_NULL;
  203. UA_TL_Connection_getNetworkLayerData(connection, (void**)&networkLayerData);
  204. if(networkLayerData != UA_NULL){
  205. DBG_VERBOSE(printf("NL_Connection_close - enter shutdown\n"));
  206. shutdown(networkLayerData->connectionHandle,2);
  207. DBG_VERBOSE(printf("NL_Connection_close - enter close\n"));
  208. close(networkLayerData->connectionHandle);
  209. DBG_VERBOSE(printf("NL_Connection_close - leave close\n"));
  210. return UA_SUCCESS;
  211. }
  212. DBG_VERBOSE(printf("NL_Connection_close - ERROR: connection object invalid \n"));
  213. return UA_ERROR;
  214. }
  215. void* NL_Connection_init(NL_Connection* c, NL_data* tld, UA_Int32 connectionHandle, NL_Reader reader, TL_Writer writer)
  216. {
  217. UA_TL_Connection connection = UA_NULL;
  218. //create new connection object
  219. UA_TL_Connection_new(&connection, tld->tld->localConf, writer, NL_Connection_close,connectionHandle,c);
  220. c->connection = connection;
  221. c->connectionHandle = connectionHandle;
  222. // network layer
  223. c->reader = reader;
  224. #ifdef MULTITHREADING
  225. c->readerThreadHandle = -1;
  226. #endif
  227. c->networkLayer = tld;
  228. return UA_NULL;
  229. }
  230. /** the tcp listener routine */
  231. void* NL_TCP_listen(NL_Connection* c) {
  232. NL_data* tld = c->networkLayer;
  233. DBG_VERBOSE(printf("NL_TCP_listen - enter listen\n"));
  234. int retval = listen(c->connectionHandle, tld->tld->maxConnections);
  235. DBG_VERBOSE(printf("NL_TCP_listen - leave listen, retval=%d\n",retval));
  236. if (retval < 0) {
  237. // TODO: Error handling
  238. perror("NL_TCP_listen");
  239. DBG_ERR(printf("NL_TCP_listen retval=%d, errno={%d,%s}\n",retval,errno,strerror(errno)));
  240. } else if (tld->tld->maxConnections == -1 || tld->connections.size < tld->tld->maxConnections) {
  241. // accept only if not max number of connections exceeded
  242. struct sockaddr_in cli_addr;
  243. socklen_t cli_len = sizeof(cli_addr);
  244. DBG_VERBOSE(printf("NL_TCP_listen - enter accept\n"));
  245. int newsockfd = accept(c->connectionHandle, (struct sockaddr *) &cli_addr, &cli_len);
  246. DBG_VERBOSE(printf("NL_TCP_listen - leave accept\n"));
  247. if (newsockfd < 0) {
  248. DBG_ERR(printf("TL_TCP_listen - accept returns errno={%d,%s}\n",errno,strerror(errno)));
  249. perror("ERROR on accept");
  250. } else {
  251. DBG_VERBOSE(printf("NL_TCP_listen - new connection on %d\n",newsockfd));
  252. NL_Connection* cclient;
  253. UA_Int32 retval = UA_SUCCESS;
  254. retval |= UA_alloc((void**)&cclient,sizeof(NL_Connection));
  255. NL_Connection_init(cclient, tld, newsockfd, NL_TCP_reader, (TL_Writer) NL_TCP_writer);
  256. #ifdef MULTITHREADING
  257. pthread_create( &(cclient->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_readerThread, (void*) cclient);
  258. #else
  259. UA_list_addPayloadToBack(&(tld->connections),cclient);
  260. NL_TCP_SetNonBlocking(cclient->connectionHandle);
  261. #endif
  262. }
  263. } else {
  264. // no action necessary to reject connection
  265. }
  266. return UA_NULL;
  267. }
  268. #ifdef MULTITHREADING
  269. void* NL_TCP_listenThread(NL_Connection* c) {
  270. do {
  271. NL_TCP_listen(c);
  272. } while (UA_TRUE);
  273. UA_free(c);
  274. pthread_exit(UA_NULL);
  275. }
  276. #endif
  277. UA_Int32 NL_TCP_init(NL_data* tld, UA_Int32 port) {
  278. UA_Int32 retval = UA_SUCCESS;
  279. // socket variables
  280. int newsockfd;
  281. int optval = 1;
  282. struct sockaddr_in serv_addr;
  283. // create socket for listening to incoming connections
  284. newsockfd = socket(PF_INET, SOCK_STREAM, 0);
  285. if (newsockfd < 0) {
  286. perror("ERROR opening socket");
  287. retval = UA_ERROR;
  288. } else {
  289. // set port number, options and bind
  290. memset((void *) &serv_addr, sizeof(serv_addr),1);
  291. serv_addr.sin_family = AF_INET;
  292. serv_addr.sin_addr.s_addr = INADDR_ANY;
  293. serv_addr.sin_port = htons(port);
  294. if (setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) == -1 ) {
  295. perror("setsockopt");
  296. retval = UA_ERROR;
  297. } else {
  298. // bind to port
  299. if (bind(newsockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  300. perror("ERROR on binding");
  301. retval = UA_ERROR;
  302. } else {
  303. UA_String_copyprintf("opc.tcp://localhost:%d/", &(tld->endpointUrl), port);
  304. }
  305. }
  306. }
  307. // finally
  308. if (retval == UA_SUCCESS) {
  309. DBG_VERBOSE(printf("NL_TCP_init - new listener on %d\n",newsockfd));
  310. NL_Connection* c;
  311. UA_Int32 retval = UA_SUCCESS;
  312. retval |= UA_alloc((void**)&c,sizeof(NL_Connection));
  313. NL_Connection_init(c, tld, newsockfd, NL_TCP_listen, (TL_Writer) NL_TCP_writer);
  314. #ifdef MULTITHREADING
  315. pthread_create( &(c->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_listenThread, (void*) c);
  316. #else
  317. UA_list_addPayloadToBack(&(tld->connections),c);
  318. NL_TCP_SetNonBlocking(c->connectionHandle);
  319. #endif
  320. }
  321. return retval;
  322. }
  323. /** checks arguments and dispatches to worker or refuses to init */
  324. NL_data* NL_init(NL_Description* tlDesc, UA_Int32 port) {
  325. NL_data* nl = UA_NULL;
  326. if (tlDesc->connectionType == NL_CONNECTIONTYPE_TCPV4 && tlDesc->encoding == NL_UA_ENCODING_BINARY) {
  327. UA_alloc((void**)&nl, sizeof(NL_data));
  328. nl->tld = tlDesc;
  329. FD_ZERO(&(nl->readerHandles));
  330. UA_list_init(&(nl->connections));
  331. NL_TCP_init(nl, port);
  332. }
  333. return nl;
  334. }