networklayer.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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_THREADINGTYPE_SINGLE,
  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 && c->networkLayer->threaded == NL_THREADINGTYPE_PTHREAD);
  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(UA_TL_connection* c, UA_ByteString* msg) {
  79. DBG_VERBOSE(UA_ByteString_printx("NL_TCP_writer - msg=", msg));
  80. int nWritten = 0;
  81. while (nWritten < msg->length) {
  82. int n=0;
  83. do {
  84. DBG_VERBOSE(printf("NL_TCP_writer - enter write\n"));
  85. n = write(c->connectionHandle, &(msg->data[nWritten]), msg->length-nWritten);
  86. DBG_VERBOSE(printf("NL_TCP_writer - leave write with n=%d,errno={%d,%s}\n",n,errno,strerror(errno)));
  87. } while (n == -1L && errno == EINTR);
  88. if (n >= 0) {
  89. nWritten += n;
  90. } else {
  91. // TODO: error handling
  92. }
  93. }
  94. return UA_SUCCESS;
  95. }
  96. void* NL_Connection_init(NL_connection* c, NL_data* tld, UA_Int32 connectionHandle, NL_reader reader, UA_TL_writer writer)
  97. {
  98. // connection layer of UA stack
  99. c->connection.connectionHandle = connectionHandle;
  100. c->connection.connectionState = connectionState_CLOSED;
  101. c->connection.writerCallback = writer;
  102. memcpy(&(c->connection.localConf),&(tld->tld->localConf),sizeof(TL_buffer));
  103. memset(&(c->connection.remoteConf),0,sizeof(TL_buffer));
  104. UA_String_copy(&(tld->endpointUrl), &(c->connection.localEndpointUrl));
  105. // network layer
  106. c->reader = reader;
  107. c->readerThreadHandle = -1;
  108. c->networkLayer = tld;
  109. return UA_NULL;
  110. }
  111. /** the tcp listener routine.
  112. * does a single shot if single threaded, runs forever if multithreaded
  113. */
  114. void* NL_TCP_listen(NL_connection* c) {
  115. NL_data* tld = c->networkLayer;
  116. // UA_String_printf("open62541-server listening at endpoint ",&(tld->endpointUrl));
  117. do {
  118. DBG_VERBOSE(printf("NL_TCP_listen - enter listen\n"));
  119. int retval = listen(c->connection.connectionHandle, tld->tld->maxConnections);
  120. DBG_VERBOSE(printf("NL_TCP_listen - leave listen, retval=%d\n",retval));
  121. if (retval < 0) {
  122. // TODO: Error handling
  123. perror("NL_TCP_listen");
  124. DBG_ERR(printf("NL_TCP_listen retval=%d, errno={%d,%s}\n",retval,errno,strerror(errno)));
  125. } else if (tld->tld->maxConnections == -1 || tld->connections.size < tld->tld->maxConnections) {
  126. // accept only if not max number of connections exceeded
  127. struct sockaddr_in cli_addr;
  128. socklen_t cli_len = sizeof(cli_addr);
  129. DBG_VERBOSE(printf("NL_TCP_listen - enter accept\n"));
  130. int newsockfd = accept(c->connection.connectionHandle, (struct sockaddr *) &cli_addr, &cli_len);
  131. DBG_VERBOSE(printf("NL_TCP_listen - leave accept\n"));
  132. if (newsockfd < 0) {
  133. DBG_ERR(printf("UA_TL_TCP_listen - accept returns errno={%d,%s}\n",errno,strerror(errno)));
  134. perror("ERROR on accept");
  135. } else {
  136. DBG_VERBOSE(printf("NL_TCP_listen - new connection on %d\n",newsockfd));
  137. NL_connection* cclient;
  138. UA_Int32 retval = UA_SUCCESS;
  139. retval |= UA_alloc((void**)&cclient,sizeof(NL_connection));
  140. NL_Connection_init(cclient, tld, newsockfd, NL_TCP_reader, NL_TCP_writer);
  141. UA_list_addPayloadToBack(&(tld->connections),cclient);
  142. if (tld->threaded == NL_THREADINGTYPE_PTHREAD) {
  143. // TODO: handle retval of pthread_create
  144. #ifdef MULTITHREADING
  145. pthread_create( &(cclient->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_reader, (void*) cclient);
  146. #endif
  147. } else {
  148. NL_TCP_SetNonBlocking(cclient->connection.connectionHandle);
  149. }
  150. }
  151. } else {
  152. // no action necessary to reject connection
  153. }
  154. } while (tld->threaded == NL_THREADINGTYPE_PTHREAD);
  155. return UA_NULL;
  156. }
  157. void NL_addHandleToSet(UA_Int32 handle, NL_data* nl) {
  158. FD_SET(handle, &(nl->readerHandles));
  159. nl->maxReaderHandle = (handle > nl->maxReaderHandle) ? handle : nl->maxReaderHandle;
  160. }
  161. void NL_setFdSet(void* payload) {
  162. NL_connection* c = (NL_connection*) payload;
  163. NL_addHandleToSet(c->connection.connectionHandle, c->networkLayer);
  164. }
  165. void NL_checkFdSet(void* payload) {
  166. NL_connection* c = (NL_connection*) payload;
  167. if (FD_ISSET(c->connection.connectionHandle, &(c->networkLayer->readerHandles))) {
  168. c->reader((void*)c);
  169. }
  170. }
  171. UA_Int32 NL_msgLoop(NL_data* nl, struct timeval *tv, UA_Int32(*worker)(void*), void *arg) {
  172. UA_Int32 result;
  173. while (UA_TRUE) {
  174. // determine the largest handle
  175. nl->maxReaderHandle = 0;
  176. UA_list_iteratePayload(&(nl->connections),NL_setFdSet);
  177. DBG_VERBOSE(printf("UA_Stack_msgLoop - maxHandle=%d\n", nl->maxReaderHandle));
  178. // copy tv, some unixes do overwrite and return the remaining time
  179. struct timeval tmptv;
  180. memcpy(&tmptv,tv,sizeof(struct timeval));
  181. // and wait
  182. DBG_VERBOSE(printf("UA_Stack_msgLoop - enter select sec=%d,usec=%d\n",(UA_Int32) tmptv.tv_sec, (UA_Int32) tmptv.tv_usec));
  183. result = select(nl->maxReaderHandle + 1, &(nl->readerHandles), UA_NULL, UA_NULL,&tmptv);
  184. 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));
  185. if (result == 0) {
  186. int err = errno;
  187. switch (err) {
  188. case EBADF:
  189. case EINTR:
  190. case EINVAL:
  191. //FIXME: handle errors
  192. DBG_ERR(printf("UA_Stack_msgLoop - errno={%d,%s}\n", errno, strerror(errno)));
  193. break;
  194. case EAGAIN:
  195. default:
  196. DBG_VERBOSE(printf("UA_Stack_msgLoop - errno={%d,%s}\n", errno, strerror(errno)));
  197. DBG_VERBOSE(printf("UA_Stack_msgLoop - call worker\n"));
  198. worker(arg);
  199. DBG_VERBOSE(printf("UA_Stack_msgLoop - return from worker\n"));
  200. }
  201. } else { // activity on listener or client ports
  202. DBG_VERBOSE(printf("UA_Stack_msgLoop - activities on %d handles\n",result));
  203. UA_list_iteratePayload(&(nl->connections),NL_checkFdSet);
  204. }
  205. }
  206. return UA_SUCCESS;
  207. }
  208. UA_Int32 NL_TCP_init(NL_data* tld, UA_Int32 port) {
  209. UA_Int32 retval = UA_SUCCESS;
  210. // socket variables
  211. int newsockfd;
  212. int optval = 1;
  213. struct sockaddr_in serv_addr;
  214. // create socket for listening to incoming connections
  215. newsockfd = socket(PF_INET, SOCK_STREAM, 0);
  216. if (newsockfd < 0) {
  217. perror("ERROR opening socket");
  218. retval = UA_ERROR;
  219. } else {
  220. // set port number, options and bind
  221. memset((void *) &serv_addr, sizeof(serv_addr),1);
  222. serv_addr.sin_family = AF_INET;
  223. serv_addr.sin_addr.s_addr = INADDR_ANY;
  224. serv_addr.sin_port = htons(port);
  225. if (setsockopt(newsockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) == -1 ) {
  226. perror("setsockopt");
  227. retval = UA_ERROR;
  228. } else {
  229. // bind to port
  230. if (bind(newsockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  231. perror("ERROR on binding");
  232. retval = UA_ERROR;
  233. } else {
  234. UA_String_copyprintf("opc.tcp://localhost:%d/", &(tld->endpointUrl), port);
  235. }
  236. }
  237. }
  238. // finally
  239. if (retval == UA_SUCCESS) {
  240. DBG_VERBOSE(printf("NL_TCP_init - new listener on %d\n",newsockfd));
  241. NL_connection* c;
  242. UA_Int32 retval = UA_SUCCESS;
  243. retval |= UA_alloc((void**)&c,sizeof(NL_connection));
  244. NL_Connection_init(c, tld, newsockfd, NL_TCP_listen, (UA_TL_writer) UA_NULL);
  245. UA_list_addPayloadToBack(&(tld->connections),c);
  246. if (tld->threaded == NL_THREADINGTYPE_PTHREAD) {
  247. // TODO: handle retval of pthread_create
  248. #ifdef MULTITHREADING
  249. pthread_create( &(c->readerThreadHandle), NULL, (void*(*)(void*)) NL_TCP_listen, (void*) c);
  250. #endif
  251. } else {
  252. NL_TCP_SetNonBlocking(c->connection.connectionHandle);
  253. }
  254. }
  255. return retval;
  256. }
  257. /** checks arguments and dispatches to worker or refuses to init */
  258. NL_data* NL_init(NL_Description* tlDesc, UA_Int32 port, UA_Int32 threaded) {
  259. NL_data* nl = UA_NULL;
  260. if (tlDesc->connectionType == NL_CONNECTIONTYPE_TCPV4 && tlDesc->encoding == NL_UA_ENCODING_BINARY) {
  261. UA_alloc((void**)&nl,sizeof(NL_data));
  262. nl->tld = tlDesc;
  263. nl->threaded = threaded;
  264. FD_ZERO(&(nl->readerHandles));
  265. UA_list_init(&(nl->connections));
  266. NL_TCP_init(nl,port);
  267. }
  268. return nl;
  269. }