networklayer.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. #define VERBOSE 1
  11. #include "networklayer.h"
  12. NL_Description NL_Description_TcpBinary = {
  13. NL_UA_ENCODING_BINARY,
  14. NL_CONNECTIONTYPE_TCPV4,
  15. NL_MAXCONNECTIONS_DEFAULT,
  16. {-1,8192,8192,16384,1}
  17. };
  18. _Bool NL_connectionComparer(void *p1, void* p2) {
  19. NL_connection* c1 = (NL_connection*) p1;
  20. NL_connection* c2 = (NL_connection*) p2;
  21. return (c1->connection.connectionHandle == c2->connection.connectionHandle);
  22. }
  23. int NL_TCP_SetNonBlocking(int sock) {
  24. int opts = fcntl(sock,F_GETFL);
  25. if (opts < 0) {
  26. perror("fcntl(F_GETFL)");
  27. return -1;
  28. }
  29. opts = (opts | O_NONBLOCK);
  30. if (fcntl(sock,F_SETFL,opts) < 0) {
  31. perror("fcntl(F_SETFL)");
  32. return -1;
  33. }
  34. return 0;
  35. }
  36. void NL_connection_printf(void* payload) {
  37. NL_connection* c = (NL_connection*) payload;
  38. printf("ListElement connectionHandle = %d\n",c->connection.connectionHandle);
  39. }
  40. /** the tcp reader thread - single shot if single-threaded, looping until CLOSE if multi-threaded
  41. */
  42. void* NL_TCP_reader(NL_connection *c) {
  43. UA_ByteString readBuffer;
  44. UA_alloc((void**)&(readBuffer.data),c->connection.localConf.recvBufferSize);
  45. if (c->connection.connectionState != connectionState_CLOSE) {
  46. do {
  47. DBG_VERBOSE(printf("NL_TCP_reader - enter read\n"));
  48. readBuffer.length = read(c->connection.connectionHandle, readBuffer.data, c->connection.localConf.recvBufferSize);
  49. DBG_VERBOSE(printf("NL_TCP_reader - leave read\n"));
  50. DBG_VERBOSE(printf("NL_TCP_reader - src={%*.s}, ",c->connection.remoteEndpointUrl.length,c->connection.remoteEndpointUrl.data));
  51. UA_ByteString_printx("received=",&readBuffer);
  52. if (readBuffer.length > 0) {
  53. TL_process(&(c->connection),&readBuffer);
  54. } else {
  55. c->connection.connectionState = connectionState_CLOSE;
  56. perror("ERROR reading from socket1");
  57. }
  58. } while (c->connection.connectionState != connectionState_CLOSE);
  59. }
  60. if (c->connection.connectionState == connectionState_CLOSE) {
  61. DBG_VERBOSE(printf("NL_TCP_reader - enter shutdown\n"));
  62. shutdown(c->connection.connectionHandle,2);
  63. DBG_VERBOSE(printf("NL_TCP_reader - enter close\n"));
  64. close(c->connection.connectionHandle);
  65. DBG_VERBOSE(printf("NL_TCP_reader - leave close\n"));
  66. c->connection.connectionState = connectionState_CLOSED;
  67. UA_ByteString_deleteMembers(&readBuffer);
  68. DBG_VERBOSE(printf("NL_TCP_reader - search element to remove\n"));
  69. UA_list_Element* lec = UA_list_search(&(c->networkLayer->connections),NL_connectionComparer,c);
  70. DBG_VERBOSE(printf("NL_TCP_reader - remove connection for handle=%d\n",((NL_connection*)lec->payload)->connection.connectionHandle));
  71. UA_list_removeElement(lec,UA_NULL);
  72. DBG_VERBOSE(UA_list_iteratePayload(&(c->networkLayer->connections),NL_connection_printf));
  73. UA_free(c);
  74. }
  75. return UA_NULL;
  76. }
  77. /** write to a tcp transport layer connection */
  78. UA_Int32 NL_TCP_writer(TL_connection* c, UA_ByteString** gather_buf, UA_UInt32 gather_len) {
  79. struct iovec iov[gather_len];
  80. UA_UInt32 total_len = 0;
  81. for(UA_UInt32 i=0;i<gather_len;i++) {
  82. iov[i].iov_base = gather_buf[i]->data;
  83. iov[i].iov_len = gather_buf[i]->length;
  84. total_len += gather_buf[i]->length;
  85. DBG_VERBOSE(UA_ByteString_printx("NL_TCP_writer - msg=", gather_buf[i]));
  86. }
  87. struct msghdr message;
  88. message.msg_name = 0;
  89. message.msg_namelen = 0;
  90. message.msg_iov = iov;
  91. message.msg_iovlen = gather_len;
  92. message.msg_control = 0;
  93. message.msg_controllen = 0;
  94. UA_UInt32 nWritten = 0;
  95. while (nWritten < total_len) {
  96. int n=0;
  97. do {
  98. DBG_VERBOSE(printf("NL_TCP_writer - enter write\n"));
  99. n = write(c->connectionHandle, &message, 0);
  100. DBG_VERBOSE(printf("NL_TCP_writer - leave write with n=%d,errno={%d,%s}\n",n,errno,strerror(errno)));
  101. } while (n == -1L && errno == EINTR);
  102. if (n >= 0) {
  103. nWritten += n;
  104. break;
  105. // TODO: handle incompletely send messages
  106. } else {
  107. // TODO: error handling
  108. }
  109. }
  110. return UA_SUCCESS;
  111. }
  112. void* NL_Connection_init(NL_connection* c, NL_data* tld, UA_Int32 connectionHandle, NL_reader reader, TL_writer writer)
  113. {
  114. // connection layer of UA stack
  115. c->connection.connectionHandle = connectionHandle;
  116. c->connection.connectionState = connectionState_CLOSED;
  117. c->connection.writerCallback = writer;
  118. memcpy(&(c->connection.localConf),&(tld->tld->localConf),sizeof(TL_buffer));
  119. memset(&(c->connection.remoteConf),0,sizeof(TL_buffer));
  120. UA_String_copy(&(tld->endpointUrl), &(c->connection.localEndpointUrl));
  121. // network layer
  122. c->reader = reader;
  123. #ifdef MULTITHREADING
  124. c->readerThreadHandle = -1;
  125. #endif
  126. c->networkLayer = tld;
  127. return UA_NULL;
  128. }
  129. /** the tcp listener routine.
  130. * does a single shot if single threaded, runs forever if multithreaded
  131. */
  132. void* NL_TCP_listen(NL_connection* c) {
  133. NL_data* tld = c->networkLayer;
  134. do {
  135. DBG_VERBOSE(printf("NL_TCP_listen - enter listen\n"));
  136. int retval = listen(c->connection.connectionHandle, tld->tld->maxConnections);
  137. DBG_VERBOSE(printf("NL_TCP_listen - leave listen, retval=%d\n",retval));
  138. if (retval < 0) {
  139. // TODO: Error handling
  140. perror("NL_TCP_listen");
  141. DBG_ERR(printf("NL_TCP_listen retval=%d, errno={%d,%s}\n",retval,errno,strerror(errno)));
  142. } else if (tld->tld->maxConnections == -1 || tld->connections.size < tld->tld->maxConnections) {
  143. // accept only if not max number of connections exceeded
  144. struct sockaddr_in cli_addr;
  145. socklen_t cli_len = sizeof(cli_addr);
  146. DBG_VERBOSE(printf("NL_TCP_listen - enter accept\n"));
  147. int newsockfd = accept(c->connection.connectionHandle, (struct sockaddr *) &cli_addr, &cli_len);
  148. DBG_VERBOSE(printf("NL_TCP_listen - leave accept\n"));
  149. if (newsockfd < 0) {
  150. DBG_ERR(printf("TL_TCP_listen - accept returns errno={%d,%s}\n",errno,strerror(errno)));
  151. perror("ERROR on accept");
  152. } else {
  153. DBG_VERBOSE(printf("NL_TCP_listen - new connection on %d\n",newsockfd));
  154. NL_connection* cclient;
  155. UA_Int32 retval = UA_SUCCESS;
  156. retval |= UA_alloc((void**)&cclient,sizeof(NL_connection));
  157. NL_Connection_init(cclient, tld, newsockfd, NL_TCP_reader, (TL_writer) NL_TCP_writer);
  158. UA_list_addPayloadToBack(&(tld->connections),cclient);
  159. #ifdef MULTITHREADING
  160. pthread_create( &(cclient->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_reader, (void*) cclient);
  161. #else
  162. NL_TCP_SetNonBlocking(cclient->connection.connectionHandle);
  163. #endif
  164. }
  165. } else {
  166. // no action necessary to reject connection
  167. }
  168. } while (1);
  169. return UA_NULL;
  170. }
  171. void NL_addHandleToSet(UA_Int32 handle, NL_data* nl) {
  172. FD_SET(handle, &(nl->readerHandles));
  173. nl->maxReaderHandle = (handle > nl->maxReaderHandle) ? handle : nl->maxReaderHandle;
  174. }
  175. void NL_setFdSet(void* payload) {
  176. NL_connection* c = (NL_connection*) payload;
  177. NL_addHandleToSet(c->connection.connectionHandle, c->networkLayer);
  178. }
  179. void NL_checkFdSet(void* payload) {
  180. NL_connection* c = (NL_connection*) payload;
  181. if (FD_ISSET(c->connection.connectionHandle, &(c->networkLayer->readerHandles))) {
  182. c->reader((void*)c);
  183. }
  184. }
  185. UA_Int32 NL_msgLoop(NL_data* nl, struct timeval *tv, UA_Int32(*worker)(void*), void *arg) {
  186. UA_Int32 result;
  187. while (UA_TRUE) {
  188. // determine the largest handle
  189. nl->maxReaderHandle = 0;
  190. UA_list_iteratePayload(&(nl->connections),NL_setFdSet);
  191. DBG_VERBOSE(printf("UA_Stack_msgLoop - maxHandle=%d\n", nl->maxReaderHandle));
  192. // copy tv, some unixes do overwrite and return the remaining time
  193. struct timeval tmptv;
  194. memcpy(&tmptv,tv,sizeof(struct timeval));
  195. // and wait
  196. DBG_VERBOSE(printf("UA_Stack_msgLoop - enter select sec=%d,usec=%d\n",(UA_Int32) tmptv.tv_sec, (UA_Int32) tmptv.tv_usec));
  197. result = select(nl->maxReaderHandle + 1, &(nl->readerHandles), UA_NULL, UA_NULL,&tmptv);
  198. 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));
  199. if (result == 0) {
  200. int err = errno;
  201. switch (err) {
  202. case EBADF:
  203. case EINTR:
  204. case EINVAL:
  205. //FIXME: handle errors
  206. DBG_ERR(printf("UA_Stack_msgLoop - errno={%d,%s}\n", errno, strerror(errno)));
  207. break;
  208. case EAGAIN:
  209. default:
  210. DBG_VERBOSE(printf("UA_Stack_msgLoop - errno={%d,%s}\n", errno, strerror(errno)));
  211. DBG_VERBOSE(printf("UA_Stack_msgLoop - call worker\n"));
  212. worker(arg);
  213. DBG_VERBOSE(printf("UA_Stack_msgLoop - return from worker\n"));
  214. }
  215. } else { // activity on listener or client ports
  216. DBG_VERBOSE(printf("UA_Stack_msgLoop - activities on %d handles\n",result));
  217. UA_list_iteratePayload(&(nl->connections),NL_checkFdSet);
  218. }
  219. }
  220. return UA_SUCCESS;
  221. }
  222. UA_Int32 NL_TCP_init(NL_data* tld, UA_Int32 port) {
  223. UA_Int32 retval = UA_SUCCESS;
  224. // socket variables
  225. int newsockfd;
  226. int optval = 1;
  227. struct sockaddr_in serv_addr;
  228. // create socket for listening to incoming connections
  229. newsockfd = socket(PF_INET, SOCK_STREAM, 0);
  230. if (newsockfd < 0) {
  231. perror("ERROR opening socket");
  232. retval = UA_ERROR;
  233. } else {
  234. // set port number, options and bind
  235. memset((void *) &serv_addr, sizeof(serv_addr),1);
  236. serv_addr.sin_family = AF_INET;
  237. serv_addr.sin_addr.s_addr = INADDR_ANY;
  238. serv_addr.sin_port = htons(port);
  239. if (setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) == -1 ) {
  240. perror("setsockopt");
  241. retval = UA_ERROR;
  242. } else {
  243. // bind to port
  244. if (bind(newsockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  245. perror("ERROR on binding");
  246. retval = UA_ERROR;
  247. } else {
  248. UA_String_copyprintf("opc.tcp://localhost:%d/", &(tld->endpointUrl), port);
  249. }
  250. }
  251. }
  252. // finally
  253. if (retval == UA_SUCCESS) {
  254. DBG_VERBOSE(printf("NL_TCP_init - new listener on %d\n",newsockfd));
  255. NL_connection* c;
  256. UA_Int32 retval = UA_SUCCESS;
  257. retval |= UA_alloc((void**)&c,sizeof(NL_connection));
  258. NL_Connection_init(c, tld, newsockfd, NL_TCP_listen, (TL_writer) UA_NULL);
  259. UA_list_addPayloadToBack(&(tld->connections),c);
  260. #ifdef MULTITHREADING
  261. pthread_create( &(c->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_listen, (void*) c);
  262. #else
  263. NL_TCP_SetNonBlocking(c->connection.connectionHandle);
  264. #endif
  265. }
  266. return retval;
  267. }
  268. /** checks arguments and dispatches to worker or refuses to init */
  269. NL_data* NL_init(NL_Description* tlDesc, UA_Int32 port) {
  270. NL_data* nl = UA_NULL;
  271. if (tlDesc->connectionType == NL_CONNECTIONTYPE_TCPV4 && tlDesc->encoding == NL_UA_ENCODING_BINARY) {
  272. UA_alloc((void**)&nl, sizeof(NL_data));
  273. nl->tld = tlDesc;
  274. FD_ZERO(&(nl->readerHandles));
  275. UA_list_init(&(nl->connections));
  276. NL_TCP_init(nl, port);
  277. }
  278. return nl;
  279. }