ua_network_udp.c 8.0 KB

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