Merge remote branch 'gnuradio/wip/udp_source_sink'
[debian/gnuradio] / gnuradio-core / src / lib / io / gr_udp_sink.cc
index d37adfb8a8cf780f996ba6a1b1f7cc566d06e450..3084a848be7a78c537af79e069703ca404533052 100644 (file)
@@ -1,6 +1,6 @@
 /* -*- c++ -*- */
 /*
- * Copyright 2007,2008,2009 Free Software Foundation, Inc.
+ * Copyright 2007,2008,2009,2010 Free Software Foundation, Inc.
  * 
  * This file is part of GNU Radio
  * 
 #include <gr_udp_sink.h>
 #include <gr_io_signature.h>
 #include <stdexcept>
-#if defined(HAVE_SOCKET)
-#include <netdb.h>
+#include <errno.h>
 #include <stdio.h>
+#include <string.h>
+#if defined(HAVE_NETDB_H)
+#include <netdb.h>
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>  //usually included by <netdb.h>?
+#endif
 typedef void* optval_t;
-#else
+#elif defined(HAVE_WINDOWS_H)
+// if not posix, assume winsock
+#define USING_WINSOCK
+#include <winsock2.h>
+#include <ws2tcpip.h>
 #define SHUT_RDWR 2
-#define inet_aton(N,A) ( (A)->s_addr = inet_addr(N), ( (A)->s_addr != INADDR_NONE ) )
 typedef char* optval_t;
 #endif
 
@@ -40,91 +51,67 @@ typedef char* optval_t;
 
 #define SNK_VERBOSE 0
 
-gr_udp_sink::gr_udp_sink (size_t itemsize, 
-                         const char *src, unsigned short port_src,
-                         const char *dst, unsigned short port_dst,
-                         int payload_size)
-  : gr_sync_block ("udp_sink",
-                  gr_make_io_signature (1, 1, itemsize),
-                  gr_make_io_signature (0, 0, 0)),
-    d_itemsize (itemsize), d_updated(false), d_payload_size(payload_size)
+static int is_error( int perr )
 {
-  int ret = 0;
-  
-  // Set up the address stucture for the source address and port numbers
-  // Get the source IP address from the host name
-  struct hostent *hsrc = gethostbyname(src);
-  if(hsrc) {   // if the source was provided as a host namex
-    d_ip_src = *(struct in_addr*)hsrc->h_addr_list[0];    
+  // Compare error to posix error code; return nonzero if match.
+#if defined(USING_WINSOCK)
+#define ENOPROTOOPT 109
+#define ECONNREFUSED 111
+  // All codes to be checked for must be defined below
+  int werr = WSAGetLastError();
+  switch( werr ) {
+  case WSAETIMEDOUT:
+    return( perr == EAGAIN );
+  case WSAENOPROTOOPT:
+    return( perr == ENOPROTOOPT );
+  case WSAECONNREFUSED:
+    return( perr == ECONNREFUSED );
+  default:
+    fprintf(stderr,"gr_udp_source/is_error: unknown error %d\n", perr );
+    throw std::runtime_error("internal error");
   }
-  else { // assume it was specified as an IP address
-    if((ret=inet_aton(src, &d_ip_src)) == 0) {            // format IP address
-      perror("Not a valid source IP address or host name");
-      throw std::runtime_error("can't initialize source socket");
-    }
-  }
-
-  // Get the destination IP address from the host name
-  struct hostent *hdst = gethostbyname(dst);
-  if(hdst) {   // if the source was provided as a host namex
-    d_ip_dst = *(struct in_addr*)hdst->h_addr_list[0];    
-  }
-  else { // assume it was specified as an IP address
-    if((ret=inet_aton(dst, &d_ip_dst)) == 0) {            // format IP address
-      perror("Not a valid destination IP address or host name");
-      throw std::runtime_error("can't initialize destination socket");
-    }
-  }
-
-  d_port_src = htons(port_src);           // format port number
-  d_port_dst = htons(port_dst);           // format port number
-
-  d_sockaddr_src.sin_family = AF_INET;
-  d_sockaddr_src.sin_addr   = d_ip_src;
-  d_sockaddr_src.sin_port   = d_port_src;
-
-  d_sockaddr_dst.sin_family = AF_INET;
-  d_sockaddr_dst.sin_addr   = d_ip_dst;
-  d_sockaddr_dst.sin_port   = d_port_dst;
-  
-  open();
-}
-
-// public constructor that returns a shared_ptr
-
-gr_udp_sink_sptr
-gr_make_udp_sink (size_t itemsize, 
-                 const char *src, unsigned short port_src,
-                 const char *dst, unsigned short port_dst,
-                 int payload_size)
-{
-  return gr_udp_sink_sptr (new gr_udp_sink (itemsize, 
-                                           src, port_src,
-                                           dst, port_dst,
-                                           payload_size));
+  return 0;
+#else
+  return( perr == errno );
+#endif
 }
 
-gr_udp_sink::~gr_udp_sink ()
+static void report_error( const char *msg1, const char *msg2 )
 {
-  close();
+  // Deal with errors, both posix and winsock
+#if defined(USING_WINSOCK)
+  int werr = WSAGetLastError();
+  fprintf(stderr, "%s: winsock error %d\n", msg1, werr );
+#else
+  perror(msg1);
+#endif
+  if( msg2 != NULL )
+    throw std::runtime_error(msg2);
+  return;
 }
 
-bool
-gr_udp_sink::open()
+gr_udp_sink::gr_udp_sink (size_t itemsize, 
+                         const char *host, unsigned short port,
+                         int payload_size, bool eof)
+  : gr_sync_block ("udp_sink",
+                  gr_make_io_signature (1, 1, itemsize),
+                  gr_make_io_signature (0, 0, 0)),
+    d_itemsize (itemsize), d_payload_size(payload_size), d_eof(eof),
+    d_socket(-1), d_connected(false)
 {
-  gruel::scoped_lock guard(d_mutex);   // hold mutex for duration of this function
-
-  // create socket
-  if((d_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
-    perror("socket open");
-    throw std::runtime_error("can't open socket");
+#if defined(USING_WINSOCK) // for Windows (with MinGW)
+  // initialize winsock DLL
+  WSADATA wsaData;
+  int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
+  if( iResult != NO_ERROR ) {
+    report_error( "gr_udp_source WSAStartup", "can't open socket" );
   }
+#endif
 
-  // Turn on reuse address
-  int opt_val = true;
-  if(setsockopt(d_socket, SOL_SOCKET, SO_REUSEADDR, (optval_t)&opt_val, sizeof(int)) == -1) {
-    perror("SO_REUSEADDR");
-    throw std::runtime_error("can't set socket option SO_REUSEADDR");
+  // create socket
+  d_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+  if(d_socket == -1) {
+    report_error("socket open","can't open socket");
   }
 
   // Don't wait when shutting down
@@ -132,36 +119,46 @@ gr_udp_sink::open()
   lngr.l_onoff  = 1;
   lngr.l_linger = 0;
   if(setsockopt(d_socket, SOL_SOCKET, SO_LINGER, (optval_t)&lngr, sizeof(linger)) == -1) {
-    perror("SO_LINGER");
-    throw std::runtime_error("can't set socket option SO_LINGER");
+    if( !is_error(ENOPROTOOPT) ) {  // no SO_LINGER for SOCK_DGRAM on Windows
+      report_error("SO_LINGER","can't set socket option SO_LINGER");
+    }
   }
 
-  // bind socket to an address and port number to listen on
-  if(bind (d_socket, (sockaddr*)&d_sockaddr_src, sizeof(struct sockaddr)) == -1) {
-    perror("socket bind");
-    throw std::runtime_error("can't bind socket");
-  }
+  // Get the destination address
+  connect(host, port);
+}
 
-  // Not sure if we should throw here or allow retries
-  if(connect(d_socket, (sockaddr*)&d_sockaddr_dst, sizeof(struct sockaddr)) == -1) {
-    perror("socket connect");
-    throw std::runtime_error("can't connect to socket");
-  }
+// public constructor that returns a shared_ptr
 
-  d_updated = true;
-  return d_socket != 0;
+gr_udp_sink_sptr
+gr_make_udp_sink (size_t itemsize, 
+                 const char *host, unsigned short port,
+                 int payload_size, bool eof)
+{
+  return gr_udp_sink_sptr (new gr_udp_sink (itemsize, 
+                                           host, port,
+                                           payload_size, eof));
 }
 
-void
-gr_udp_sink::close()
+gr_udp_sink::~gr_udp_sink ()
 {
-  gruel::scoped_lock guard(d_mutex);   // hold mutex for duration of this function
+  if (d_connected)
+    disconnect();
 
-  if (d_socket){
+  if (d_socket != -1){
     shutdown(d_socket, SHUT_RDWR);
-    d_socket = 0;
+#if defined(USING_WINSOCK)
+    closesocket(d_socket);
+#else
+    ::close(d_socket);
+#endif
+    d_socket = -1;
   }
-  d_updated = true;
+
+#if defined(USING_WINSOCK) // for Windows (with MinGW)
+  // free winsock resources
+  WSACleanup();
+#endif
 }
 
 int 
@@ -174,21 +171,31 @@ gr_udp_sink::work (int noutput_items,
   ssize_t total_size = noutput_items*d_itemsize;
 
   #if SNK_VERBOSE
-  printf("Entered upd_sink\n");
+  printf("Entered udp_sink\n");
   #endif
 
+  gruel::scoped_lock guard(d_mutex);  // protect d_socket
+
   while(bytes_sent <  total_size) {
     bytes_to_send = std::min((ssize_t)d_payload_size, (total_size-bytes_sent));
   
-    r = send(d_socket, (in+bytes_sent), bytes_to_send, 0);
-    if(r == -1) {         // error on send command
-      perror("udp_sink"); // there should be no error case where this function 
-      return -1;          // should not exit immediately
+    if(d_connected) {
+      r = send(d_socket, (in+bytes_sent), bytes_to_send, 0);
+      if(r == -1) {         // error on send command
+       if( is_error(ECONNREFUSED) )
+         r = bytes_to_send;  // discard data until receiver is started
+       else {
+         report_error("udp_sink",NULL); // there should be no error case where
+         return -1;                  // this function should not exit immediately
+       }
+      }
     }
+    else
+      r = bytes_to_send;  // discarded for lack of connection
     bytes_sent += r;
     
     #if SNK_VERBOSE
-    printf("\tbyte sent: %d bytes\n", bytes);
+    printf("\tbyte sent: %d bytes\n", r);
     #endif
   }
 
@@ -198,3 +205,98 @@ gr_udp_sink::work (int noutput_items,
 
   return noutput_items;
 }
+
+void gr_udp_sink::connect( const char *host, unsigned short port )
+{
+  if(d_connected)
+    disconnect();
+
+  if(host != NULL ) {
+    // Get the destination address
+    struct addrinfo *ip_dst;
+    struct addrinfo hints;
+    memset( (void*)&hints, 0, sizeof(hints) );
+    hints.ai_family = AF_INET;
+    hints.ai_socktype = SOCK_DGRAM;
+    hints.ai_protocol = IPPROTO_UDP;
+    char port_str[12];
+    sprintf( port_str, "%d", port );
+
+    // FIXME leaks if report_error throws below
+    int ret = getaddrinfo( host, port_str, &hints, &ip_dst );
+    if( ret != 0 )
+      report_error("gr_udp_source/getaddrinfo",
+                  "can't initialize destination socket" );
+
+    // don't need d_mutex lock when !d_connected
+    if(::connect(d_socket, ip_dst->ai_addr, ip_dst->ai_addrlen) == -1) {
+      report_error("socket connect","can't connect to socket");
+    }
+    d_connected = true;
+
+    freeaddrinfo(ip_dst);
+  }
+
+  return;
+}
+
+void gr_udp_sink::disconnect()
+{
+  if(!d_connected)
+    return;
+
+  #if SNK_VERBOSE
+  printf("gr_udp_sink disconnecting\n");
+  #endif
+
+  gruel::scoped_lock guard(d_mutex);  // protect d_socket from work()
+
+  // Send a few zero-length packets to signal receiver we are done
+  if(d_eof) {
+    int i;
+    for( i = 0; i < 3; i++ )
+      (void) send( d_socket, NULL, 0, 0 );  // ignore errors
+  }
+
+  // Sending EOF can produce ERRCONNREFUSED errors that won't show up
+  //  until the next send or recv, which might confuse us if it happens
+  //  on a new connection.  The following does a nonblocking recv to
+  //  clear any such errors.
+  timeval timeout;
+  timeout.tv_sec = 0;    // zero time for immediate return
+  timeout.tv_usec = 0;
+  fd_set readfds;
+  FD_ZERO(&readfds);
+  FD_SET(d_socket, &readfds);
+  int r = select(FD_SETSIZE, &readfds, NULL, NULL, &timeout);
+  if(r < 0) {
+      #if SNK_VERBOSE
+      report_error("udp_sink/select",NULL);
+      #endif
+  }
+  else if(r > 0) {  // call recv() to get error return
+    r = recv(d_socket, (char*)&readfds, sizeof(readfds), 0);
+    if(r < 0) {
+       #if SNK_VERBOSE
+       report_error("udp_sink/recv",NULL);
+       #endif
+    }
+  }
+
+  // Since I can't find any way to disconnect a datagram socket in Cygwin,
+  // we just leave it connected but disable sending.
+#if 0
+  // zeroed address structure should reset connection
+  struct sockaddr addr;
+  memset( (void*)&addr, 0, sizeof(addr) );
+  // addr.sa_family = AF_UNSPEC;  // doesn't work on Cygwin
+  // addr.sa_family = AF_INET;  // doesn't work on Cygwin
+
+  if(::connect(d_socket, &addr, sizeof(addr)) == -1)
+    report_error("socket connect","can't connect to socket");
+#endif
+
+  d_connected = false;
+
+  return;
+}