networklayer.c 11 KB

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