3d8d65145b4078dcaf3d0c5a80d76b863b1231e8
[debian/gnuradio] / gnuradio-core / src / lib / io / gr_udp_sink.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2007,2008,2009 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 typedef void* optval_t;
34 #else
35 // if not posix, assume winsock
36 #define USING_WINSOCK
37 #define SHUT_RDWR 2
38 typedef char* optval_t;
39 #define ENOPROTOOPT 109
40 #endif
41
42 #include <gruel/thread.h>
43
44 #define SNK_VERBOSE 0
45
46 static int is_error( int perr )
47 {
48   // Compare error to posix error code; return nonzero if match.
49 #if defined(USING_WINSOCK)
50   // All codes to be checked for must be defined below
51   int werr = WSAGetLastError();
52   switch( werr ) {
53   case WSAETIMEDOUT:
54     return( perr == EAGAIN );
55   case WSAENOPROTOOPT:
56     return( perr == ENOPROTOOPT );
57   default:
58     fprintf(stderr,"gr_udp_source/is_error: unknown error %d\n", perr );
59     throw std::runtime_error("internal error");
60   }
61   return 0;
62 #else
63   return( perr == errno );
64 #endif
65 }
66
67 static void report_error( char *msg1, char *msg2 )
68 {
69   // Deal with errors, both posix and winsock
70 #if defined(USING_WINSOCK)
71   int werr = WSAGetLastError();
72   fprintf(stderr, "%s: winsock error %d\n", msg1, werr );
73 #else
74   perror(msg1);
75 #endif
76   if( msg2 != NULL )
77     throw std::runtime_error(msg2);
78   return;
79 }
80
81 gr_udp_sink::gr_udp_sink (size_t itemsize, 
82                           const char *src, unsigned short port_src,
83                           const char *dst, unsigned short port_dst,
84                           int payload_size)
85   : gr_sync_block ("udp_sink",
86                    gr_make_io_signature (1, 1, itemsize),
87                    gr_make_io_signature (0, 0, 0)),
88     d_itemsize (itemsize), d_updated(false), d_payload_size(payload_size)
89 {
90   int ret = 0;
91
92 #if !defined(HAVE_SOCKET) // for Windows (with MinGW)
93   // initialize winsock DLL
94   WSADATA wsaData;
95   int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
96   if( iResult != NO_ERROR ) {
97     report_error( "gr_udp_source WSAStartup", "can't open socket" );
98   }
99 #endif
100   
101   // Set up the address stucture for the source address and port numbers
102   // Get the source IP address from the host name
103   struct addrinfo hints;
104   memset( (void*)&hints, 0, sizeof(hints) );
105   hints.ai_family = AF_INET;
106   hints.ai_socktype = SOCK_DGRAM;
107   hints.ai_protocol = IPPROTO_UDP;
108   char port_str[7];
109   sprintf( port_str, "%d", port_src );
110   ret = getaddrinfo( src, port_str, &hints, &d_ip_src );
111   if( ret != 0 )
112     report_error("gr_udp_source/getaddrinfo",
113                  "can't initialize source socket" );
114
115   // Get the destination IP address from the host name
116   sprintf( port_str, "%d", port_dst );
117   ret = getaddrinfo( dst, port_str, &hints, &d_ip_dst );
118   if( ret != 0 )
119     report_error("gr_udp_source/getaddrinfo",
120                  "can't initialize destination socket" );
121   
122   open();
123 }
124
125 // public constructor that returns a shared_ptr
126
127 gr_udp_sink_sptr
128 gr_make_udp_sink (size_t itemsize, 
129                   const char *src, unsigned short port_src,
130                   const char *dst, unsigned short port_dst,
131                   int payload_size)
132 {
133   return gr_udp_sink_sptr (new gr_udp_sink (itemsize, 
134                                             src, port_src,
135                                             dst, port_dst,
136                                             payload_size));
137 }
138
139 gr_udp_sink::~gr_udp_sink ()
140 {
141   freeaddrinfo(d_ip_src);
142   freeaddrinfo(d_ip_dst);
143   close();
144
145 #if !defined(HAVE_SOCKET) // for Windows (with MinGW)
146   // free winsock resources
147   WSACleanup();
148 #endif
149 }
150
151 bool
152 gr_udp_sink::open()
153 {
154   gruel::scoped_lock guard(d_mutex);    // hold mutex for duration of this function
155
156   // create socket
157   d_socket = socket(d_ip_src->ai_family, d_ip_src->ai_socktype,
158                     d_ip_src->ai_protocol);
159   if(d_socket == -1) {
160     report_error("socket open","can't open socket");
161   }
162
163   // Turn on reuse address
164   int opt_val = true;
165   if(setsockopt(d_socket, SOL_SOCKET, SO_REUSEADDR, (optval_t)&opt_val, sizeof(int)) == -1) {
166     report_error("SO_REUSEADDR","can't set socket option SO_REUSEADDR");
167   }
168
169   // Don't wait when shutting down
170   linger lngr;
171   lngr.l_onoff  = 1;
172   lngr.l_linger = 0;
173   if(setsockopt(d_socket, SOL_SOCKET, SO_LINGER, (optval_t)&lngr, sizeof(linger)) == -1) {
174     if( !is_error(ENOPROTOOPT) ) {  // no SO_LINGER for SOCK_DGRAM on Windows
175       report_error("SO_LINGER","can't set socket option SO_LINGER");
176     }
177   }
178
179   // bind socket to an address and port number to listen on
180   if(bind (d_socket, d_ip_src->ai_addr, d_ip_src->ai_addrlen) == -1) {
181     report_error("socket bind","can't bind socket");
182   }
183
184   // Not sure if we should throw here or allow retries
185   if(connect(d_socket, d_ip_dst->ai_addr, d_ip_dst->ai_addrlen) == -1) {
186     report_error("socket connect","can't connect to socket");
187   }
188
189   d_updated = true;
190   return d_socket != 0;
191 }
192
193 void
194 gr_udp_sink::close()
195 {
196   gruel::scoped_lock guard(d_mutex);    // hold mutex for duration of this function
197
198   if (d_socket){
199     shutdown(d_socket, SHUT_RDWR);
200 #if defined(USING_WINSOCK)
201     closesocket(d_socket);
202 #else
203     ::close(d_socket);
204 #endif
205     d_socket = 0;
206   }
207   d_updated = true;
208 }
209
210 int 
211 gr_udp_sink::work (int noutput_items,
212                    gr_vector_const_void_star &input_items,
213                    gr_vector_void_star &output_items)
214 {
215   const char *in = (const char *) input_items[0];
216   ssize_t r=0, bytes_sent=0, bytes_to_send=0;
217   ssize_t total_size = noutput_items*d_itemsize;
218
219   #if SNK_VERBOSE
220   printf("Entered upd_sink\n");
221   #endif
222
223   while(bytes_sent <  total_size) {
224     bytes_to_send = std::min((ssize_t)d_payload_size, (total_size-bytes_sent));
225   
226     r = send(d_socket, (in+bytes_sent), bytes_to_send, 0);
227     if(r == -1) {         // error on send command
228       report_error("udp_sink",NULL); // there should be no error case where
229       return -1;                   // this function should not exit immediately
230     }
231     bytes_sent += r;
232     
233     #if SNK_VERBOSE
234     printf("\tbyte sent: %d bytes\n", bytes);
235     #endif
236   }
237
238   #if SNK_VERBOSE
239   printf("Sent: %d bytes (noutput_items: %d)\n", bytes_sent, noutput_items);
240   #endif
241
242   return noutput_items;
243 }