networklayer_udp.c 8.7 KB

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