networklayer_udp.c 8.0 KB

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