ua_network_udp.c 8.4 KB

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