ua_network_udp.c 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. #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_newMembers(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_ServerNetworkLayer layer;
  58. UA_ConnectionConfig conf;
  59. fd_set fdset;
  60. UA_Int32 serversockfd;
  61. UA_UInt32 port;
  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. size_t 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 < (size_t)buf->length) {
  83. UA_Int32 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->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(ServerNetworkLayerUDP *layer, UA_Logger logger) {
  109. layer->layer.logger = logger;
  110. layer->serversockfd = socket(PF_INET, SOCK_DGRAM, 0);
  111. if(layer->serversockfd < 0) {
  112. UA_LOG_WARNING(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "Error opening socket");
  113. return UA_STATUSCODE_BADINTERNALERROR;
  114. }
  115. const struct sockaddr_in serv_addr =
  116. {.sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  117. .sin_port = htons(layer->port), .sin_zero = {0}};
  118. int optval = 1;
  119. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  120. SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
  121. UA_LOG_WARNING(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "Could not setsockopt");
  122. CLOSESOCKET(layer->serversockfd);
  123. return UA_STATUSCODE_BADINTERNALERROR;
  124. }
  125. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  126. sizeof(serv_addr)) < 0) {
  127. UA_LOG_WARNING(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "Could not bind the socket");
  128. CLOSESOCKET(layer->serversockfd);
  129. return UA_STATUSCODE_BADINTERNALERROR;
  130. }
  131. socket_set_nonblocking(layer->serversockfd);
  132. UA_LOG_WARNING(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "Listening for UDP connections on %s:%d",
  133. inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  134. return UA_STATUSCODE_GOOD;
  135. }
  136. static size_t ServerNetworkLayerUDP_getJobs(ServerNetworkLayerUDP *layer, UA_Job **jobs, UA_UInt16 timeout) {
  137. UA_Job *items = NULL;
  138. setFDSet(layer);
  139. struct timeval tmptv = {0, timeout};
  140. UA_Int32 resultsize = select(layer->serversockfd+1, &layer->fdset, NULL, NULL, &tmptv);
  141. if(resultsize <= 0 || !FD_ISSET(layer->serversockfd, &layer->fdset)) {
  142. *jobs = items;
  143. return 0;
  144. }
  145. items = malloc(sizeof(UA_Job)*resultsize);
  146. // read from established sockets
  147. UA_Int32 j = 0;
  148. UA_ByteString buf = {-1, NULL};
  149. if(!buf.data) {
  150. buf.data = malloc(sizeof(UA_Byte) * layer->conf.recvBufferSize);
  151. if(!buf.data)
  152. UA_LOG_WARNING(layer->layer.logger, UA_LOGCATEGORY_NETWORK, "malloc failed");
  153. }
  154. struct sockaddr sender;
  155. socklen_t sendsize = sizeof(sender);
  156. bzero(&sender, sizeof(sender));
  157. ssize_t rec_result = recvfrom(layer->serversockfd, buf.data, layer->conf.recvBufferSize, 0, &sender, &sendsize);
  158. if (rec_result > 0) {
  159. buf.length = rec_result;
  160. UDPConnection *c = malloc(sizeof(UDPConnection));
  161. if(!c){
  162. free(items);
  163. return UA_STATUSCODE_BADINTERNALERROR;
  164. }
  165. UA_Connection_init(&c->connection);
  166. c->from = sender;
  167. c->fromlen = sendsize;
  168. // c->sockfd = newsockfd;
  169. c->connection.getSendBuffer = GetMallocedBuffer;
  170. c->connection.releaseSendBuffer = ReleaseMallocedBuffer;
  171. c->connection.releaseRecvBuffer = ReleaseMallocedBuffer;
  172. c->connection.handle = layer;
  173. c->connection.send = sendUDP;
  174. c->connection.close = closeConnectionUDP;
  175. c->connection.localConf = layer->conf;
  176. c->connection.state = UA_CONNECTION_OPENING;
  177. items[j].type = UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER;
  178. items[j].job.binaryMessage.message = buf;
  179. items[j].job.binaryMessage.connection = (UA_Connection*)c;
  180. buf.data = NULL;
  181. j++;
  182. *jobs = items;
  183. } else {
  184. free(items);
  185. *jobs = NULL;
  186. }
  187. if(buf.data)
  188. free(buf.data);
  189. return j;
  190. }
  191. static UA_Int32 ServerNetworkLayerUDP_stop(ServerNetworkLayerUDP * layer, UA_Job **jobs) {
  192. CLOSESOCKET(layer->serversockfd);
  193. return 0;
  194. }
  195. static void ServerNetworkLayerUDP_deleteMembers(ServerNetworkLayerUDP *layer) {
  196. }
  197. UA_ServerNetworkLayer * ServerNetworkLayerUDP_new(UA_ConnectionConfig conf, UA_UInt32 port) {
  198. ServerNetworkLayerUDP *layer = malloc(sizeof(ServerNetworkLayerUDP));
  199. if(!layer)
  200. return NULL;
  201. memset(layer, 0, sizeof(ServerNetworkLayerUDP));
  202. layer->conf = conf;
  203. layer->port = port;
  204. layer->layer.start = (UA_StatusCode(*)(UA_ServerNetworkLayer*,UA_Logger))ServerNetworkLayerUDP_start;
  205. layer->layer.getJobs = (size_t(*)(UA_ServerNetworkLayer*,UA_Job**,UA_UInt16))ServerNetworkLayerUDP_getJobs;
  206. layer->layer.stop = (size_t(*)(UA_ServerNetworkLayer*, UA_Job**))ServerNetworkLayerUDP_stop;
  207. layer->layer.deleteMembers = (void(*)(UA_ServerNetworkLayer*))ServerNetworkLayerUDP_deleteMembers;
  208. return &layer->layer;
  209. }