networklayer.c 12 KB

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