networklayer_udp.c 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 fixme: udp not yet implemented for windows
  32. #endif
  33. /*****************************/
  34. /* Generic Buffer Management */
  35. /*****************************/
  36. static UA_StatusCode GetMallocedBuffer(UA_Connection *connection, UA_ByteString *buf, size_t minSize) {
  37. if(minSize > connection->remoteConf.recvBufferSize)
  38. return UA_STATUSCODE_BADINTERNALERROR;
  39. return UA_ByteString_newMembers(buf, minSize);
  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_Server *server;
  56. UA_ConnectionConfig conf;
  57. fd_set fdset;
  58. UA_Int32 serversockfd;
  59. UA_UInt32 port;
  60. UA_Logger *logger;
  61. } ServerNetworkLayerUDP;
  62. /** Accesses only the sockfd in the handle. Can be run from parallel threads. */
  63. static void writeCallbackUDP(UDPConnection *handle, UA_ByteStringArray gather_buf) {
  64. UA_UInt32 total_len = 0, nWritten = 0;
  65. struct iovec iov[gather_buf.stringsSize];
  66. for(UA_UInt32 i=0;i<gather_buf.stringsSize;i++) {
  67. iov[i] = (struct iovec) {.iov_base = gather_buf.strings[i].data,
  68. .iov_len = gather_buf.strings[i].length};
  69. total_len += gather_buf.strings[i].length;
  70. }
  71. struct sockaddr_in *sin = NULL;
  72. if (handle->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 *) &(handle->from);
  78. #if ((__GNUC__ == 4 && __GNUC_MINOR__ >= 6) || __GNUC__ > 4 || defined(__clang__))
  79. #pragma GCC diagnostic pop
  80. #endif
  81. } else {
  82. //FIXME:
  83. return;
  84. }
  85. struct msghdr message = {.msg_name = sin, .msg_namelen = handle->fromlen, .msg_iov = iov,
  86. .msg_iovlen = gather_buf.stringsSize, .msg_control = NULL,
  87. .msg_controllen = 0, .msg_flags = 0};
  88. while (nWritten < total_len) {
  89. UA_Int32 n = 0;
  90. do {
  91. n = sendmsg(((ServerNetworkLayerUDP*)handle->connection.handle)->serversockfd, &message, 0);
  92. if(n == -1L) {
  93. printf("ERROR:%i\n", errno);
  94. }
  95. } while (n == -1L && errno == EINTR);
  96. nWritten += n;
  97. }
  98. }
  99. static UA_StatusCode socket_set_nonblocking(UA_Int32 sockfd) {
  100. int opts = fcntl(sockfd, F_GETFL);
  101. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  102. return UA_STATUSCODE_BADINTERNALERROR;
  103. return UA_STATUSCODE_GOOD;
  104. }
  105. static void setFDSet(ServerNetworkLayerUDP *layer) {
  106. FD_ZERO(&layer->fdset);
  107. FD_SET(layer->serversockfd, &layer->fdset);
  108. }
  109. static void closeConnectionUDP(UDPConnection *handle) {
  110. free(handle);
  111. }
  112. static UA_StatusCode ServerNetworkLayerUDP_start(ServerNetworkLayerUDP *layer, UA_Logger *logger) {
  113. layer->logger = logger;
  114. if((layer->serversockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
  115. perror("ERROR opening socket");
  116. return UA_STATUSCODE_BADINTERNALERROR;
  117. }
  118. const struct sockaddr_in serv_addr =
  119. {.sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  120. .sin_port = htons(layer->port), .sin_zero = {0}};
  121. int optval = 1;
  122. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  123. SO_REUSEADDR, (const char *)&optval,
  124. sizeof(optval)) == -1) {
  125. perror("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. perror("binding");
  132. CLOSESOCKET(layer->serversockfd);
  133. return UA_STATUSCODE_BADINTERNALERROR;
  134. }
  135. socket_set_nonblocking(layer->serversockfd);
  136. printf("Listening for UDP connections on %s:%d", inet_ntoa(serv_addr.sin_addr),
  137. ntohs(serv_addr.sin_port));
  138. return UA_STATUSCODE_GOOD;
  139. }
  140. static UA_Int32 ServerNetworkLayerUDP_getWork(ServerNetworkLayerUDP *layer, UA_WorkItem **workItems,
  141. UA_UInt16 timeout) {
  142. UA_WorkItem *items = NULL;
  143. setFDSet(layer);
  144. struct timeval tmptv = {0, timeout};
  145. UA_Int32 resultsize = select(layer->serversockfd+1, &layer->fdset, NULL, NULL, &tmptv);
  146. if(resultsize <= 0 || !FD_ISSET(layer->serversockfd, &layer->fdset)) {
  147. *workItems = items;
  148. return 0;
  149. }
  150. items = malloc(sizeof(UA_WorkItem)*(resultsize));
  151. // read from established sockets
  152. UA_Int32 j = 0;
  153. UA_ByteString buf = {-1, NULL};
  154. if(!buf.data) {
  155. buf.data = malloc(sizeof(UA_Byte) * layer->conf.recvBufferSize);
  156. if(!buf.data)
  157. printf("malloc failed");
  158. }
  159. struct sockaddr sender;
  160. socklen_t sendsize = sizeof(sender);
  161. bzero(&sender, sizeof(sender));
  162. buf.length = recvfrom(layer->serversockfd, buf.data, layer->conf.recvBufferSize, 0, &sender, &sendsize);
  163. if (buf.length <= 0) {
  164. } else {
  165. UDPConnection *c = malloc(sizeof(UDPConnection));
  166. if(!c)
  167. return UA_STATUSCODE_BADINTERNALERROR;
  168. c->from = sender;
  169. c->fromlen = sendsize;
  170. c->connection.state = UA_CONNECTION_OPENING;
  171. c->connection.localConf = layer->conf;
  172. c->connection.channel = NULL;
  173. c->connection.close = (void (*)(UA_Connection*))closeConnectionUDP;
  174. c->connection.write = (UA_StatusCode (*)(UA_Connection*, UA_ByteStringArray))writeCallbackUDP;
  175. c->connection.getBuffer = GetMallocedBuffer;
  176. c->connection.releaseBuffer = ReleaseMallocedBuffer;
  177. c->connection.handle = layer;
  178. items[j].type = UA_WORKITEMTYPE_BINARYMESSAGE;
  179. items[j].work.binaryMessage.message = buf;
  180. items[j].work.binaryMessage.connection = (UA_Connection*)c;
  181. buf.data = NULL;
  182. j++;
  183. }
  184. if(buf.data)
  185. free(buf.data);
  186. if(j == 0) {
  187. free(items);
  188. *workItems = NULL;
  189. } else
  190. *workItems = items;
  191. return j;
  192. }
  193. static UA_Int32 ServerNetworkLayerUDP_stop(ServerNetworkLayerUDP * layer, UA_WorkItem **workItems) {
  194. CLOSESOCKET(layer->serversockfd);
  195. return 0;
  196. }
  197. static void ServerNetworkLayerUDP_delete(ServerNetworkLayerUDP *layer) {
  198. free(layer);
  199. }
  200. UA_ServerNetworkLayer ServerNetworkLayerUDP_new(UA_ConnectionConfig conf, UA_UInt32 port) {
  201. ServerNetworkLayerUDP *udplayer = malloc(sizeof(ServerNetworkLayerUDP));
  202. udplayer->conf = conf;
  203. udplayer->port = port;
  204. UA_ServerNetworkLayer nl;
  205. nl.nlHandle = udplayer;
  206. nl.start = (UA_StatusCode (*)(void*, UA_Logger *logger))ServerNetworkLayerUDP_start;
  207. nl.getWork = (UA_Int32 (*)(void*, UA_WorkItem**, UA_UInt16)) ServerNetworkLayerUDP_getWork;
  208. nl.stop = (UA_Int32 (*)(void*, UA_WorkItem**)) ServerNetworkLayerUDP_stop;
  209. nl.free = (void (*)(void*))ServerNetworkLayerUDP_delete;
  210. nl.discoveryUrl = NULL;
  211. return nl;
  212. }