Rework UDP source and sink, with incompatible API changes
[debian/gnuradio] / gnuradio-core / src / lib / io / gr_udp_sink.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2007,2008,2009,2010 Free Software Foundation, Inc.
4  * 
5  * This file is part of GNU Radio
6  * 
7  * GNU Radio is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3, or (at your option)
10  * any later version.
11  * 
12  * GNU Radio is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with GNU Radio; see the file COPYING.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26 #include <gr_udp_sink.h>
27 #include <gr_io_signature.h>
28 #include <stdexcept>
29 #include <errno.h>
30 #include <stdio.h>
31 #include <string.h>
32 #if defined(HAVE_NETDB_H)
33 #include <netdb.h>
34 #include <sys/socket.h>  //usually included by <netdb.h>?
35 typedef void* optval_t;
36 #elif defined(HAVE_WINDOWS_H)
37 // if not posix, assume winsock
38 #define USING_WINSOCK
39 #include <winsock2.h>
40 #include <ws2tcpip.h>
41 #define SHUT_RDWR 2
42 typedef char* optval_t;
43 #endif
44
45 #include <gruel/thread.h>
46
47 #define SNK_VERBOSE 0
48
49 static int is_error( int perr )
50 {
51   // Compare error to posix error code; return nonzero if match.
52 #if defined(USING_WINSOCK)
53 #define ENOPROTOOPT 109
54 #define ECONNREFUSED 111
55   // All codes to be checked for must be defined below
56   int werr = WSAGetLastError();
57   switch( werr ) {
58   case WSAETIMEDOUT:
59     return( perr == EAGAIN );
60   case WSAENOPROTOOPT:
61     return( perr == ENOPROTOOPT );
62   case WSAECONNREFUSED:
63     return( perr == ECONNREFUSED );
64   default:
65     fprintf(stderr,"gr_udp_source/is_error: unknown error %d\n", perr );
66     throw std::runtime_error("internal error");
67   }
68   return 0;
69 #else
70   return( perr == errno );
71 #endif
72 }
73
74 static void report_error( const char *msg1, const char *msg2 )
75 {
76   // Deal with errors, both posix and winsock
77 #if defined(USING_WINSOCK)
78   int werr = WSAGetLastError();
79   fprintf(stderr, "%s: winsock error %d\n", msg1, werr );
80 #else
81   perror(msg1);
82 #endif
83   if( msg2 != NULL )
84     throw std::runtime_error(msg2);
85   return;
86 }
87
88 gr_udp_sink::gr_udp_sink (size_t itemsize, 
89                           const char *host, unsigned short port,
90                           int payload_size, bool eof)
91   : gr_sync_block ("udp_sink",
92                    gr_make_io_signature (1, 1, itemsize),
93                    gr_make_io_signature (0, 0, 0)),
94     d_itemsize (itemsize), d_payload_size(payload_size), d_eof(eof),
95     d_connected(false)
96 {
97 #if defined(USING_WINSOCK) // for Windows (with MinGW)
98   // initialize winsock DLL
99   WSADATA wsaData;
100   int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
101   if( iResult != NO_ERROR ) {
102     report_error( "gr_udp_source WSAStartup", "can't open socket" );
103   }
104 #endif
105
106   // create socket
107   d_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
108   if(d_socket == -1) {
109     report_error("socket open","can't open socket");
110   }
111
112   // Don't wait when shutting down
113   linger lngr;
114   lngr.l_onoff  = 1;
115   lngr.l_linger = 0;
116   if(setsockopt(d_socket, SOL_SOCKET, SO_LINGER, (optval_t)&lngr, sizeof(linger)) == -1) {
117     if( !is_error(ENOPROTOOPT) ) {  // no SO_LINGER for SOCK_DGRAM on Windows
118       report_error("SO_LINGER","can't set socket option SO_LINGER");
119     }
120   }
121
122   // Get the destination address
123   connect(host, port);
124 }
125
126 // public constructor that returns a shared_ptr
127
128 gr_udp_sink_sptr
129 gr_make_udp_sink (size_t itemsize, 
130                   const char *host, unsigned short port,
131                   int payload_size, bool eof)
132 {
133   return gr_udp_sink_sptr (new gr_udp_sink (itemsize, 
134                                             host, port,
135                                             payload_size, eof));
136 }
137
138 gr_udp_sink::~gr_udp_sink ()
139 {
140   if (d_connected)
141     disconnect();
142
143   if (d_socket){
144     shutdown(d_socket, SHUT_RDWR);
145 #if defined(USING_WINSOCK)
146     closesocket(d_socket);
147 #else
148     ::close(d_socket);
149 #endif
150     d_socket = 0;
151   }
152
153 #if defined(USING_WINSOCK) // for Windows (with MinGW)
154   // free winsock resources
155   WSACleanup();
156 #endif
157 }
158
159 int 
160 gr_udp_sink::work (int noutput_items,
161                    gr_vector_const_void_star &input_items,
162                    gr_vector_void_star &output_items)
163 {
164   const char *in = (const char *) input_items[0];
165   ssize_t r=0, bytes_sent=0, bytes_to_send=0;
166   ssize_t total_size = noutput_items*d_itemsize;
167
168   #if SNK_VERBOSE
169   printf("Entered udp_sink\n");
170   #endif
171
172   gruel::scoped_lock guard(d_mutex);  // protect d_socket
173
174   while(bytes_sent <  total_size) {
175     bytes_to_send = std::min((ssize_t)d_payload_size, (total_size-bytes_sent));
176   
177     if(d_connected) {
178       r = send(d_socket, (in+bytes_sent), bytes_to_send, 0);
179       if(r == -1) {         // error on send command
180         if( is_error(ECONNREFUSED) )
181           r = bytes_to_send;  // discard data until receiver is started
182         else {
183           report_error("udp_sink",NULL); // there should be no error case where
184           return -1;                  // this function should not exit immediately
185         }
186       }
187     }
188     else
189       r = bytes_to_send;  // discarded for lack of connection
190     bytes_sent += r;
191     
192     #if SNK_VERBOSE
193     printf("\tbyte sent: %d bytes\n", r);
194     #endif
195   }
196
197   #if SNK_VERBOSE
198   printf("Sent: %d bytes (noutput_items: %d)\n", bytes_sent, noutput_items);
199   #endif
200
201   return noutput_items;
202 }
203
204 void gr_udp_sink::connect( const char *host, unsigned short port )
205 {
206   if(d_connected)
207     disconnect();
208
209   if(host != NULL ) {
210     // Get the destination address
211     struct addrinfo *ip_dst;
212     struct addrinfo hints;
213     memset( (void*)&hints, 0, sizeof(hints) );
214     hints.ai_family = AF_INET;
215     hints.ai_socktype = SOCK_DGRAM;
216     hints.ai_protocol = IPPROTO_UDP;
217     char port_str[12];
218     sprintf( port_str, "%d", port );
219     int ret = getaddrinfo( host, port_str, &hints, &ip_dst );
220     if( ret != 0 )
221       report_error("gr_udp_source/getaddrinfo",
222                    "can't initialize destination socket" );
223
224     // don't need d_mutex lock when !d_connected
225     if(::connect(d_socket, ip_dst->ai_addr, ip_dst->ai_addrlen) == -1) {
226       report_error("socket connect","can't connect to socket");
227     }
228     d_connected = true;
229
230     freeaddrinfo(ip_dst);
231   }
232
233   return;
234 }
235
236 void gr_udp_sink::disconnect()
237 {
238   if(!d_connected)
239     return;
240
241   #if SNK_VERBOSE
242   printf("gr_udp_sink disconnecting\n");
243   #endif
244
245   gruel::scoped_lock guard(d_mutex);  // protect d_socket from work()
246
247   // Send a few zero-length packets to signal receiver we are done
248   if(d_eof) {
249     int i;
250     for( i = 0; i < 3; i++ )
251       (void) send( d_socket, NULL, 0, 0 );  // ignore errors
252   }
253
254   // Since I can't find any way to disconnect a datagram socket in Cygwin,
255   // we just leave it connected but disable sending.
256 #if 0
257   // zeroed address structure should reset connection
258   struct sockaddr addr;
259   memset( (void*)&addr, 0, sizeof(addr) );
260   // addr.sa_family = AF_UNSPEC;  // doesn't work on Cygwin
261   // addr.sa_family = AF_INET;  // doesn't work on Cygwin
262
263   if(::connect(d_socket, &addr, sizeof(addr)) == -1)
264     report_error("socket connect","can't connect to socket");
265 #endif
266
267   d_connected = false;
268
269   return;
270 }