ua_network_udp.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  5. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
  6. #include "ua_network_udp.h"
  7. #include <stdlib.h> // malloc, free
  8. #include <stdio.h>
  9. #include <string.h> // memset
  10. #ifdef UA_ENABLE_MULTITHREADING
  11. # include <urcu/uatomic.h>
  12. #endif
  13. /* with a space so amalgamation does not remove the includes */
  14. # include <errno.h> // errno, EINTR
  15. # include <fcntl.h> // fcntl
  16. # include <strings.h> //bzero
  17. # include <sys/select.h>
  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. 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(PF_INET, 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. const struct sockaddr_in serv_addr =
  120. {.sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  121. .sin_port = htons(layer->port), .sin_zero = {0}};
  122. int optval = 1;
  123. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  124. SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
  125. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Could not setsockopt");
  126. CLOSESOCKET(layer->serversockfd);
  127. return UA_STATUSCODE_BADINTERNALERROR;
  128. }
  129. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  130. sizeof(serv_addr)) < 0) {
  131. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Could not bind the socket");
  132. CLOSESOCKET(layer->serversockfd);
  133. return UA_STATUSCODE_BADINTERNALERROR;
  134. }
  135. socket_set_nonblocking(layer->serversockfd);
  136. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Listening for UDP connections on %s:%d",
  137. inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  138. return UA_STATUSCODE_GOOD;
  139. }
  140. static size_t ServerNetworkLayerUDP_getJobs(UA_ServerNetworkLayer *nl, UA_Job **jobs, UA_UInt16 timeout) {
  141. ServerNetworkLayerUDP *layer = nl->handle;
  142. UA_Job *items = NULL;
  143. setFDSet(layer);
  144. struct timeval tmptv = {0, timeout};
  145. int resultsize = select(layer->serversockfd+1, &layer->fdset, NULL, NULL, &tmptv);
  146. if(resultsize <= 0 || !FD_ISSET(layer->serversockfd, &layer->fdset)) {
  147. *jobs = items;
  148. return 0;
  149. }
  150. items = malloc(sizeof(UA_Job)*(unsigned long)resultsize);
  151. // read from established sockets
  152. size_t j = 0;
  153. UA_ByteString buf = {0, NULL};
  154. if(!buf.data) {
  155. buf.data = malloc(sizeof(UA_Byte) * layer->conf.recvBufferSize);
  156. if(!buf.data)
  157. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "malloc failed");
  158. }
  159. struct sockaddr sender;
  160. socklen_t sendsize = sizeof(sender);
  161. bzero(&sender, sizeof(sender));
  162. ssize_t rec_result = recvfrom(layer->serversockfd, buf.data, layer->conf.recvBufferSize, 0, &sender, &sendsize);
  163. if (rec_result > 0) {
  164. buf.length = (size_t)rec_result;
  165. UDPConnection *c = malloc(sizeof(UDPConnection));
  166. if(!c){
  167. free(items);
  168. return UA_STATUSCODE_BADINTERNALERROR;
  169. }
  170. UA_Connection_init(&c->connection);
  171. c->from = sender;
  172. c->fromlen = sendsize;
  173. // c->sockfd = newsockfd;
  174. c->connection.getSendBuffer = GetMallocedBuffer;
  175. c->connection.releaseSendBuffer = ReleaseMallocedBuffer;
  176. c->connection.releaseRecvBuffer = ReleaseMallocedBuffer;
  177. c->connection.handle = layer;
  178. c->connection.send = sendUDP;
  179. c->connection.close = closeConnectionUDP;
  180. c->connection.localConf = layer->conf;
  181. c->connection.state = UA_CONNECTION_OPENING;
  182. items[j].type = UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER;
  183. items[j].job.binaryMessage.message = buf;
  184. items[j].job.binaryMessage.connection = (UA_Connection*)c;
  185. buf.data = NULL;
  186. j++;
  187. *jobs = items;
  188. } else {
  189. free(items);
  190. *jobs = NULL;
  191. }
  192. if(buf.data)
  193. free(buf.data);
  194. return j;
  195. }
  196. static size_t ServerNetworkLayerUDP_stop(UA_ServerNetworkLayer *nl, UA_Job **jobs) {
  197. ServerNetworkLayerUDP *layer = nl->handle;
  198. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  199. "Shutting down the UDP network layer");
  200. CLOSESOCKET(layer->serversockfd);
  201. return 0;
  202. }
  203. static void ServerNetworkLayerUDP_deleteMembers(UA_ServerNetworkLayer *nl) {
  204. ServerNetworkLayerUDP *layer = nl->handle;
  205. free(layer);
  206. UA_String_deleteMembers(&nl->discoveryUrl);
  207. }
  208. UA_ServerNetworkLayer
  209. UA_ServerNetworkLayerUDP(UA_ConnectionConfig conf, UA_UInt16 port) {
  210. UA_ServerNetworkLayer nl;
  211. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  212. ServerNetworkLayerUDP *layer = malloc(sizeof(ServerNetworkLayerUDP));
  213. if(!layer)
  214. return nl;
  215. memset(layer, 0, sizeof(ServerNetworkLayerUDP));
  216. layer->conf = conf;
  217. layer->port = port;
  218. nl.handle = layer;
  219. nl.start = ServerNetworkLayerUDP_start;
  220. nl.getJobs = ServerNetworkLayerUDP_getJobs;
  221. nl.stop = ServerNetworkLayerUDP_stop;
  222. nl.deleteMembers = ServerNetworkLayerUDP_deleteMembers;
  223. return nl;
  224. }