networklayer_udp.c 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /*
  2. * This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  3. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  4. */
  5. #include <stdlib.h> // malloc, free
  6. #ifdef _WIN32
  7. #include <malloc.h>
  8. #include <winsock2.h>
  9. #include <sys/types.h>
  10. #include <Windows.h>
  11. #include <ws2tcpip.h>
  12. #define CLOSESOCKET(S) closesocket(S)
  13. #else
  14. #include <strings.h> //bzero
  15. #include <sys/select.h>
  16. #include <netinet/in.h>
  17. #include <sys/socketvar.h>
  18. #include <sys/ioctl.h>
  19. #include <unistd.h> // read, write, close
  20. #include <arpa/inet.h>
  21. #define CLOSESOCKET(S) close(S)
  22. #endif
  23. #include <stdio.h>
  24. #include <errno.h> // errno, EINTR
  25. #include <fcntl.h> // fcntl
  26. #include "networklayer_udp.h" // UA_MULTITHREADING is defined in here
  27. #ifdef UA_MULTITHREADING
  28. #include <urcu/uatomic.h>
  29. #endif
  30. #define MAXBACKLOG 100
  31. struct Networklayer_UDP;
  32. /* Forwarded to the server as a (UA_Connection) and used for callbacks back into
  33. the networklayer */
  34. typedef struct {
  35. UA_Connection connection;
  36. struct sockaddr from;
  37. socklen_t fromlen;
  38. struct NetworkLayerUDP *layer;
  39. } UDPConnection;
  40. typedef struct NetworkLayerUDP {
  41. UA_ConnectionConfig conf;
  42. fd_set fdset;
  43. UA_Int32 serversockfd;
  44. UA_UInt32 port;
  45. } NetworkLayerUDP;
  46. static UA_StatusCode setNonBlocking(int sockid) {
  47. #ifdef _WIN32
  48. u_long iMode = 1;
  49. if(ioctlsocket(sockid, FIONBIO, &iMode) != NO_ERROR)
  50. return UA_STATUSCODE_BADINTERNALERROR;
  51. #else
  52. int opts = fcntl(sockid,F_GETFL);
  53. if(opts < 0 || fcntl(sockid,F_SETFL,opts|O_NONBLOCK) < 0)
  54. return UA_STATUSCODE_BADINTERNALERROR;
  55. #endif
  56. return UA_STATUSCODE_GOOD;
  57. }
  58. static void setFDSet(NetworkLayerUDP *layer) {
  59. FD_ZERO(&layer->fdset);
  60. FD_SET(layer->serversockfd, &layer->fdset);
  61. }
  62. // the callbacks are thread-safe if UA_MULTITHREADING is defined
  63. void closeConnectionUDP(UDPConnection *handle){
  64. free(handle);
  65. }
  66. void writeCallbackUDP(UDPConnection *handle, UA_ByteStringArray gather_buf);
  67. /** Accesses only the sockfd in the handle. Can be run from parallel threads. */
  68. void writeCallbackUDP(UDPConnection *handle, UA_ByteStringArray gather_buf) {
  69. UA_UInt32 total_len = 0, nWritten = 0;
  70. #ifdef _WIN32
  71. LPWSABUF buf = _alloca(gather_buf.stringsSize * sizeof(WSABUF));
  72. int result = 0;
  73. for(UA_UInt32 i = 0; i<gather_buf.stringsSize; i++) {
  74. buf[i].buf = gather_buf.strings[i].data;
  75. buf[i].len = gather_buf.strings[i].length;
  76. total_len += gather_buf.strings[i].length;
  77. }
  78. while(nWritten < total_len) {
  79. UA_UInt32 n = 0;
  80. do {
  81. result = WSASendto(handle->sockfd, buf, gather_buf.stringsSize ,
  82. (LPDWORD)&n, 0, NULL, NULL);
  83. //FIXME:
  84. if(result != 0)
  85. printf("Error WSASend, code: %d \n", WSAGetLastError());
  86. } while(errno == EINTR);
  87. nWritten += n;
  88. }
  89. #else
  90. struct iovec iov[gather_buf.stringsSize];
  91. for(UA_UInt32 i=0;i<gather_buf.stringsSize;i++) {
  92. iov[i] = (struct iovec) {.iov_base = gather_buf.strings[i].data,
  93. .iov_len = gather_buf.strings[i].length};
  94. total_len += gather_buf.strings[i].length;
  95. }
  96. struct sockaddr_in *sin = UA_NULL;
  97. if (handle->from.sa_family == AF_INET)
  98. {
  99. sin = (struct sockaddr_in *) &(handle->from);
  100. }else{
  101. //FIXME:
  102. return;
  103. }
  104. struct msghdr message = {.msg_name = sin, .msg_namelen = handle->fromlen, .msg_iov = iov,
  105. .msg_iovlen = gather_buf.stringsSize, .msg_control = NULL,
  106. .msg_controllen = 0, .msg_flags = 0};
  107. while (nWritten < total_len) {
  108. UA_Int32 n = 0;
  109. do {
  110. n = sendmsg(handle->layer->serversockfd, &message, 0);
  111. if(n==-1L){
  112. printf("ERROR:%i\n", errno);
  113. }
  114. } while (n == -1L && errno == EINTR);
  115. nWritten += n;
  116. }
  117. #endif
  118. }
  119. UA_StatusCode NetworkLayerUDP_start(NetworkLayerUDP *layer) {
  120. #ifdef _WIN32
  121. WORD wVersionRequested;
  122. WSADATA wsaData;
  123. wVersionRequested = MAKEWORD(2, 2);
  124. WSAStartup(wVersionRequested, &wsaData);
  125. if((layer->serversockfd = socket(PF_INET, SOCK_DGRAM,0)) == INVALID_SOCKET) {
  126. printf("ERROR opening socket, code: %d\n", WSAGetLastError());
  127. return UA_STATUSCODE_BADINTERNALERROR;
  128. }
  129. #else
  130. if((layer->serversockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
  131. perror("ERROR opening socket");
  132. return UA_STATUSCODE_BADINTERNALERROR;
  133. }
  134. #endif
  135. const struct sockaddr_in serv_addr = {
  136. .sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  137. .sin_port = htons(layer->port), .sin_zero = {0}};
  138. int optval = 1;
  139. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  140. SO_REUSEADDR, (const char *)&optval,
  141. sizeof(optval)) == -1) {
  142. perror("setsockopt");
  143. CLOSESOCKET(layer->serversockfd);
  144. return UA_STATUSCODE_BADINTERNALERROR;
  145. }
  146. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  147. sizeof(serv_addr)) < 0) {
  148. perror("binding");
  149. CLOSESOCKET(layer->serversockfd);
  150. return UA_STATUSCODE_BADINTERNALERROR;
  151. }
  152. setNonBlocking(layer->serversockfd);
  153. printf("Listening for UDP connections on %s:%d\n",
  154. inet_ntoa(serv_addr.sin_addr),
  155. ntohs(serv_addr.sin_port));
  156. return UA_STATUSCODE_GOOD;
  157. }
  158. UA_Int32 NetworkLayerUDP_getWork(NetworkLayerUDP *layer, UA_WorkItem **workItems,
  159. UA_UInt16 timeout) {
  160. UA_WorkItem *items = UA_NULL;
  161. setFDSet(layer);
  162. struct timeval tmptv = {0, timeout};
  163. UA_Int32 resultsize = select(layer->serversockfd+1, &layer->fdset, NULL, NULL, &tmptv);
  164. if(resultsize <= 0 || !FD_ISSET(layer->serversockfd, &layer->fdset)) {
  165. *workItems = items;
  166. return 0;
  167. }
  168. items = malloc(sizeof(UA_WorkItem)*(resultsize));
  169. // read from established sockets
  170. UA_Int32 j = 0;
  171. UA_ByteString buf = { -1, NULL};
  172. if(!buf.data) {
  173. buf.data = malloc(sizeof(UA_Byte) * layer->conf.recvBufferSize);
  174. if(!buf.data){
  175. //TODO:
  176. printf("malloc failed");
  177. }
  178. }
  179. struct sockaddr sender;
  180. socklen_t sendsize = sizeof(sender);
  181. bzero(&sender, sizeof(sender));
  182. #ifdef _WIN32
  183. buf.length = recvfrom(layer->conLinks[i].sockfd, (char *)buf.data,
  184. layer->conf.recvBufferSize, 0);
  185. //todo: fixme
  186. #else
  187. buf.length = recvfrom(layer->serversockfd, buf.data, layer->conf.recvBufferSize, 0, &sender, &sendsize);
  188. #endif
  189. if (buf.length <= 0) {
  190. } else {
  191. UDPConnection *c = malloc(sizeof(UDPConnection));
  192. if(!c)
  193. return UA_STATUSCODE_BADINTERNALERROR;
  194. c->layer = layer;
  195. c->from = sender;
  196. c->fromlen = sendsize;
  197. c->connection.state = UA_CONNECTION_OPENING;
  198. c->connection.localConf = layer->conf;
  199. c->connection.channel = UA_NULL;
  200. c->connection.close = (void (*)(void*))closeConnectionUDP;
  201. c->connection.write = (void (*)(void*, UA_ByteStringArray))writeCallbackUDP;
  202. items[j].type = UA_WORKITEMTYPE_BINARYNETWORKMESSAGE;
  203. items[j].work.binaryNetworkMessage.message = buf;
  204. items[j].work.binaryNetworkMessage.connection = (UA_Connection*)c;
  205. buf.data = NULL;
  206. j++;
  207. }
  208. if(buf.data)
  209. free(buf.data);
  210. if(j == 0) {
  211. free(items);
  212. *workItems = NULL;
  213. } else
  214. *workItems = items;
  215. return j;
  216. }
  217. UA_Int32 NetworkLayerUDP_stop(NetworkLayerUDP * layer, UA_WorkItem **workItems) {
  218. CLOSESOCKET(layer->serversockfd);
  219. return 0;
  220. }
  221. void NetworkLayerUDP_delete(NetworkLayerUDP *layer) {
  222. free(layer);
  223. }
  224. UA_NetworkLayer NetworkLayerUDP_new(UA_ConnectionConfig conf, UA_UInt32 port) {
  225. NetworkLayerUDP *udplayer = malloc(sizeof(NetworkLayerUDP));
  226. udplayer->conf = conf;
  227. udplayer->port = port;
  228. UA_NetworkLayer nl;
  229. nl.nlHandle = udplayer;
  230. nl.start = (UA_StatusCode (*)(void*))NetworkLayerUDP_start;
  231. nl.getWork = (UA_Int32 (*)(void*, UA_WorkItem**, UA_UInt16)) NetworkLayerUDP_getWork;
  232. nl.stop = (UA_Int32 (*)(void*, UA_WorkItem**)) NetworkLayerUDP_stop;
  233. nl.delete = (void (*)(void*))NetworkLayerUDP_delete;
  234. return nl;
  235. }