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