ua_network_udp.c 8.1 KB

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