ua_network_udp.c 8.4 KB

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