networklayer.c 12 KB

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