ua_network_udp.c 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
  3. #include "ua_network_udp.h"
  4. #include <stdio.h>
  5. #include <string.h> // memset
  6. #ifdef UA_ENABLE_MULTITHREADING
  7. # include <urcu/uatomic.h>
  8. #endif
  9. /* with a space so amalgamation does not remove the includes */
  10. # include <errno.h> // errno, EINTR
  11. # include <fcntl.h> // fcntl
  12. # include <strings.h> //bzero
  13. # ifndef _WRS_KERNEL
  14. # include <sys/select.h>
  15. # else
  16. # include <selectLib.h>
  17. # endif
  18. # include <netinet/in.h>
  19. # include <netinet/tcp.h>
  20. # include <sys/socketvar.h>
  21. # include <sys/ioctl.h>
  22. # include <unistd.h> // read, write, close
  23. # include <arpa/inet.h>
  24. #ifdef __QNX__
  25. #include <sys/socket.h>
  26. #endif
  27. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  28. # include <sys/param.h>
  29. # if defined(BSD)
  30. # include<sys/socket.h>
  31. # endif
  32. #endif
  33. # define CLOSESOCKET(S) close(S)
  34. #define MAXBACKLOG 100
  35. #ifdef _WIN32
  36. # error udp not yet implemented for windows
  37. #endif
  38. /*****************************/
  39. /* Generic Buffer Management */
  40. /*****************************/
  41. static UA_StatusCode GetMallocedBuffer(UA_Connection *connection, size_t length, UA_ByteString *buf) {
  42. if(length > connection->remoteConf.recvBufferSize)
  43. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  44. return UA_ByteString_allocBuffer(buf, connection->remoteConf.recvBufferSize);
  45. }
  46. static void ReleaseMallocedBuffer(UA_Connection *connection, UA_ByteString *buf) {
  47. UA_ByteString_deleteMembers(buf);
  48. }
  49. /*********************/
  50. /* UDP Network Layer */
  51. /*********************/
  52. /* Forwarded to the server as a (UA_Connection) and used for callbacks back into
  53. the networklayer */
  54. typedef struct {
  55. UA_Connection connection;
  56. struct sockaddr from;
  57. socklen_t fromlen;
  58. } UDPConnection;
  59. typedef struct {
  60. UA_ConnectionConfig conf;
  61. UA_UInt16 port;
  62. fd_set fdset;
  63. UA_Int32 serversockfd;
  64. UA_Logger logger; // Set during start
  65. } ServerNetworkLayerUDP;
  66. /** Accesses only the sockfd in the handle. Can be run from parallel threads. */
  67. static UA_StatusCode sendUDP(UA_Connection *connection, UA_ByteString *buf) {
  68. UDPConnection *udpc = (UDPConnection*)connection;
  69. ServerNetworkLayerUDP *layer = (ServerNetworkLayerUDP*)connection->handle;
  70. long nWritten = 0;
  71. struct sockaddr_in *sin = NULL;
  72. if (udpc->from.sa_family == AF_INET) {
  73. #if ((__GNUC__ == 4 && __GNUC_MINOR__ >= 6) || __GNUC__ > 4 || defined(__clang__))
  74. #pragma GCC diagnostic push
  75. #pragma GCC diagnostic ignored "-Wcast-align"
  76. #endif
  77. sin = (struct sockaddr_in *) &udpc->from;
  78. #if ((__GNUC__ == 4 && __GNUC_MINOR__ >= 6) || __GNUC__ > 4 || defined(__clang__))
  79. #pragma GCC diagnostic pop
  80. #endif
  81. } else {
  82. UA_ByteString_deleteMembers(buf);
  83. return UA_STATUSCODE_BADINTERNALERROR;
  84. }
  85. while (nWritten < (long)buf->length) {
  86. long n = sendto(layer->serversockfd, buf->data, buf->length, 0,
  87. (struct sockaddr*)sin, sizeof(struct sockaddr_in));
  88. if(n == -1L) {
  89. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "UDP send error %i", errno);
  90. UA_ByteString_deleteMembers(buf);
  91. return UA_STATUSCODE_BADINTERNALERROR;
  92. }
  93. nWritten += n;
  94. }
  95. UA_ByteString_deleteMembers(buf);
  96. return UA_STATUSCODE_GOOD;
  97. }
  98. static UA_StatusCode socket_set_nonblocking(UA_Int32 sockfd) {
  99. int opts = fcntl(sockfd, F_GETFL);
  100. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  101. return UA_STATUSCODE_BADINTERNALERROR;
  102. return UA_STATUSCODE_GOOD;
  103. }
  104. static void setFDSet(ServerNetworkLayerUDP *layer) {
  105. FD_ZERO(&layer->fdset);
  106. FD_SET(layer->serversockfd, &layer->fdset);
  107. }
  108. static void closeConnectionUDP(UA_Connection *handle) {
  109. UA_free(handle);
  110. }
  111. static UA_StatusCode ServerNetworkLayerUDP_start(UA_ServerNetworkLayer *nl, UA_Logger logger) {
  112. ServerNetworkLayerUDP *layer = nl->handle;
  113. layer->logger = logger;
  114. layer->serversockfd = socket(AF_INET6, SOCK_DGRAM, 0);
  115. if(layer->serversockfd < 0) {
  116. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Error opening socket");
  117. return UA_STATUSCODE_BADINTERNALERROR;
  118. }
  119. struct sockaddr_in6 serv_addr;
  120. memset(&serv_addr, 0, sizeof(serv_addr));
  121. serv_addr.sin6_family = AF_INET6;
  122. serv_addr.sin6_port = htons(layer->port);
  123. serv_addr.sin6_addr = in6addr_any;
  124. int optval = 1;
  125. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  126. SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
  127. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Could not setsockopt");
  128. CLOSESOCKET(layer->serversockfd);
  129. return UA_STATUSCODE_BADINTERNALERROR;
  130. }
  131. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  132. sizeof(serv_addr)) < 0) {
  133. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Could not bind the socket");
  134. CLOSESOCKET(layer->serversockfd);
  135. return UA_STATUSCODE_BADINTERNALERROR;
  136. }
  137. socket_set_nonblocking(layer->serversockfd);
  138. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Listening for UDP connections on %s:%d",
  139. inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  140. return UA_STATUSCODE_GOOD;
  141. }
  142. static size_t ServerNetworkLayerUDP_getJobs(UA_ServerNetworkLayer *nl, UA_Job **jobs, UA_UInt16 timeout) {
  143. ServerNetworkLayerUDP *layer = nl->handle;
  144. UA_Job *items = NULL;
  145. setFDSet(layer);
  146. struct timeval tmptv = {0, timeout};
  147. int resultsize = select(layer->serversockfd+1, &layer->fdset, NULL, NULL, &tmptv);
  148. if(resultsize <= 0 || !FD_ISSET(layer->serversockfd, &layer->fdset)) {
  149. *jobs = items;
  150. return 0;
  151. }
  152. items = UA_malloc(sizeof(UA_Job)*(unsigned long)resultsize);
  153. // read from established sockets
  154. size_t j = 0;
  155. UA_ByteString buf = {0, NULL};
  156. if(!buf.data) {
  157. buf.data = UA_malloc(sizeof(UA_Byte) * layer->conf.recvBufferSize);
  158. if(!buf.data)
  159. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "malloc failed");
  160. }
  161. struct sockaddr sender;
  162. socklen_t sendsize = sizeof(sender);
  163. bzero(&sender, sizeof(sender));
  164. ssize_t rec_result = recvfrom(layer->serversockfd, buf.data, layer->conf.recvBufferSize, 0, &sender, &sendsize);
  165. if (rec_result > 0) {
  166. buf.length = (size_t)rec_result;
  167. UDPConnection *c = UA_malloc(sizeof(UDPConnection));
  168. if(!c){
  169. UA_free(items);
  170. return UA_STATUSCODE_BADINTERNALERROR;
  171. }
  172. UA_Connection_init(&c->connection);
  173. c->from = sender;
  174. c->fromlen = sendsize;
  175. // c->sockfd = newsockfd;
  176. c->connection.getSendBuffer = GetMallocedBuffer;
  177. c->connection.releaseSendBuffer = ReleaseMallocedBuffer;
  178. c->connection.releaseRecvBuffer = ReleaseMallocedBuffer;
  179. c->connection.handle = layer;
  180. c->connection.send = sendUDP;
  181. c->connection.close = closeConnectionUDP;
  182. c->connection.localConf = layer->conf;
  183. c->connection.state = UA_CONNECTION_OPENING;
  184. items[j].type = UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER;
  185. items[j].job.binaryMessage.message = buf;
  186. items[j].job.binaryMessage.connection = (UA_Connection*)c;
  187. buf.data = NULL;
  188. j++;
  189. *jobs = items;
  190. } else {
  191. UA_free(items);
  192. *jobs = NULL;
  193. }
  194. if(buf.data)
  195. UA_free(buf.data);
  196. return j;
  197. }
  198. static size_t ServerNetworkLayerUDP_stop(UA_ServerNetworkLayer *nl, UA_Job **jobs) {
  199. ServerNetworkLayerUDP *layer = nl->handle;
  200. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  201. "Shutting down the UDP network layer");
  202. CLOSESOCKET(layer->serversockfd);
  203. return 0;
  204. }
  205. static void ServerNetworkLayerUDP_deleteMembers(UA_ServerNetworkLayer *nl) {
  206. ServerNetworkLayerUDP *layer = nl->handle;
  207. UA_free(layer);
  208. UA_String_deleteMembers(&nl->discoveryUrl);
  209. }
  210. UA_ServerNetworkLayer
  211. UA_ServerNetworkLayerUDP(UA_ConnectionConfig conf, UA_UInt16 port) {
  212. UA_ServerNetworkLayer nl;
  213. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  214. ServerNetworkLayerUDP *layer = UA_malloc(sizeof(ServerNetworkLayerUDP));
  215. if(!layer)
  216. return nl;
  217. memset(layer, 0, sizeof(ServerNetworkLayerUDP));
  218. layer->conf = conf;
  219. layer->port = port;
  220. nl.handle = layer;
  221. nl.start = ServerNetworkLayerUDP_start;
  222. nl.getJobs = ServerNetworkLayerUDP_getJobs;
  223. nl.stop = ServerNetworkLayerUDP_stop;
  224. nl.deleteMembers = ServerNetworkLayerUDP_deleteMembers;
  225. return nl;
  226. }