56499258c3557e765a1ab50ca23a0f19ee76a20a
[debian/gnuradio] / gnuradio-core / src / lib / io / gr_udp_source.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_source.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 #endif
40
41 #define SRC_VERBOSE 0
42
43 static int is_error( int perr )
44 {
45   // Compare error to posix error code; return nonzero if match.
46 #if defined(USING_WINSOCK)
47 #define ENOPROTOOPT 109
48   // All codes to be checked for must be defined below
49   int werr = WSAGetLastError();
50   switch( werr ) {
51   case WSAETIMEDOUT:
52     return( perr == EAGAIN );
53   case WSAENOPROTOOPT:
54     return( perr == ENOPROTOOPT );
55   default:
56     fprintf(stderr,"gr_udp_source/is_error: unknown error %d\n", perr );
57     throw std::runtime_error("internal error");
58   }
59   return 0;
60 #else
61   return( perr == errno );
62 #endif
63 }
64
65 static void report_error( char *msg1, char *msg2 )
66 {
67   // Deal with errors, both posix and winsock
68 #if defined(USING_WINSOCK)
69   int werr = WSAGetLastError();
70   fprintf(stderr, "%s: winsock error %d\n", msg1, werr );
71 #else
72   perror(msg1);
73 #endif
74   if( msg2 != NULL )
75     throw std::runtime_error(msg2);
76   return;
77 }
78
79 gr_udp_source::gr_udp_source(size_t itemsize, const char *src, 
80                              unsigned short port_src, int payload_size)
81   : gr_sync_block ("udp_source",
82                    gr_make_io_signature(0, 0, 0),
83                    gr_make_io_signature(1, 1, itemsize)),
84     d_itemsize(itemsize), d_updated(false), d_payload_size(payload_size), d_residual(0), d_temp_offset(0)
85 {
86   int ret = 0;
87
88 #if !defined(HAVE_SOCKET) // for Windows (with MinGW)
89   // initialize winsock DLL
90   WSADATA wsaData;
91   int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
92   if( iResult != NO_ERROR ) {
93     report_error( "gr_udp_source WSAStartup", "can't open socket" );
94   }
95 #endif
96   
97   // Set up the address stucture for the source address and port numbers
98   // Get the source IP address from the host name
99   struct addrinfo hints;
100   memset( (void*)&hints, 0, sizeof(hints) );
101   hints.ai_family = AF_INET;
102   hints.ai_socktype = SOCK_DGRAM;
103   hints.ai_protocol = IPPROTO_UDP;
104   char port_str[7];
105   sprintf( port_str, "%d", port_src );
106   ret = getaddrinfo( src, port_str, &hints, &d_ip_src );
107   if( ret != 0 )
108     report_error("gr_udp_source/getaddrinfo",
109                  "can't initialize source socket" );
110
111   d_temp_buff = new char[d_payload_size];   // allow it to hold up to payload_size bytes
112   
113   open();
114 }
115
116 gr_udp_source_sptr
117 gr_make_udp_source (size_t itemsize, const char *ipaddr, 
118                     unsigned short port, int payload_size)
119 {
120   return gr_udp_source_sptr (new gr_udp_source (itemsize, ipaddr, 
121                                                 port, payload_size));
122 }
123
124 gr_udp_source::~gr_udp_source ()
125 {
126   freeaddrinfo(d_ip_src);
127   delete [] d_temp_buff;
128   close();
129
130 #if !defined(HAVE_SOCKET) // for Windows (with MinGW)
131   // free winsock resources
132   WSACleanup();
133 #endif
134 }
135
136 bool
137 gr_udp_source::open()
138 {
139   gruel::scoped_lock guard(d_mutex);    // hold mutex for duration of this function
140   // create socket
141   d_socket = socket(d_ip_src->ai_family, d_ip_src->ai_socktype,
142                     d_ip_src->ai_protocol);
143   if(d_socket == -1) {
144     report_error("socket open","can't open socket");
145   }
146
147   // Turn on reuse address
148   int opt_val = 1;
149   if(setsockopt(d_socket, SOL_SOCKET, SO_REUSEADDR, (optval_t)&opt_val, sizeof(int)) == -1) {
150     report_error("SO_REUSEADDR","can't set socket option SO_REUSEADDR");
151   }
152
153   // Don't wait when shutting down
154   linger lngr;
155   lngr.l_onoff  = 1;
156   lngr.l_linger = 0;
157   if(setsockopt(d_socket, SOL_SOCKET, SO_LINGER, (optval_t)&lngr, sizeof(linger)) == -1) {
158     if( !is_error(ENOPROTOOPT) ) {  // no SO_LINGER for SOCK_DGRAM on Windows
159       report_error("SO_LINGER","can't set socket option SO_LINGER");
160     }
161   }
162
163   // Set a timeout on the receive function to not block indefinitely
164   // This value can (and probably should) be changed
165   // Ignored on Cygwin
166 #if defined(USING_WINSOCK)
167   DWORD timeout = 1000;  // milliseconds
168 #else
169   timeval timeout;
170   timeout.tv_sec = 1;
171   timeout.tv_usec = 0;
172 #endif
173   if(setsockopt(d_socket, SOL_SOCKET, SO_RCVTIMEO, (optval_t)&timeout, sizeof(timeout)) == -1) {
174     report_error("SO_RCVTIMEO","can't set socket option SO_RCVTIMEO");
175   }
176
177   // bind socket to an address and port number to listen on
178   if(bind (d_socket, d_ip_src->ai_addr, d_ip_src->ai_addrlen) == -1) {
179     report_error("socket bind","can't bind socket");
180   }
181
182   d_updated = true;
183   return d_socket != 0;
184 }
185
186 void
187 gr_udp_source::close()
188 {
189   gruel::scoped_lock guard(d_mutex);    // hold mutex for duration of this function
190
191   if (d_socket){
192     shutdown(d_socket, SHUT_RDWR);
193 #if defined(USING_WINSOCK)
194     closesocket(d_socket);
195 #else
196     ::close(d_socket);
197 #endif
198     d_socket = 0;
199   }
200   d_updated = true;
201 }
202
203 int 
204 gr_udp_source::work (int noutput_items,
205                      gr_vector_const_void_star &input_items,
206                      gr_vector_void_star &output_items)
207 {
208   char *out = (char *) output_items[0];
209   ssize_t r=0, nbytes=0, bytes_received=0;
210   ssize_t total_bytes = (ssize_t)(d_itemsize*noutput_items);
211
212   #if SRC_VERBOSE
213   printf("\nEntered udp_source\n");
214   #endif
215
216   // Remove items from temp buffer if they are in there
217   if(d_residual) {
218     nbytes = std::min(d_residual, total_bytes);
219     memcpy(out, d_temp_buff+d_temp_offset, nbytes);
220     bytes_received = nbytes;
221
222     #if SRC_VERBOSE
223     printf("\tTemp buff size: %d  offset: %d (bytes_received: %d) (noutput_items: %d)\n", 
224            d_residual, d_temp_offset, bytes_received, noutput_items);
225     #endif
226
227     // Increment pointer
228     out += bytes_received;
229     
230     // Update indexing of amount of bytes left in the buffer
231     d_residual -= nbytes;
232     d_temp_offset = d_temp_offset+d_residual;
233   }
234
235   while(1) {
236     // get the data into our output buffer and record the number of bytes
237     // This is a non-blocking call with a timeout set in the constructor
238     r = recv(d_socket, d_temp_buff, d_payload_size, 0);  // get the entire payload or the what's available
239
240     // Check if there was a problem; forget it if the operation just timed out
241     if(r == -1) {
242       if( is_error(EAGAIN) ) {  // handle non-blocking call timeout
243         #if SRC_VERBOSE
244         printf("UDP receive timed out\n"); 
245         #endif
246
247         // Break here to allow the rest of the flow graph time to run and so ctrl-C breaks
248         break;
249       }
250       else {
251         report_error("udp_source",NULL);
252         return -1;
253       }
254     }
255     else {
256       // Calculate the number of bytes we can take from the buffer in this call
257       nbytes = std::min(r, total_bytes-bytes_received);
258       
259       // adjust the total number of bytes we have to round down to nearest integer of an itemsize
260       nbytes -= ((bytes_received+nbytes) % d_itemsize);   
261
262       // copy the number of bytes we want to look at here
263       memcpy(out, d_temp_buff, nbytes);    
264
265       d_residual = r - nbytes;                      // save the number of bytes stored
266       d_temp_offset=nbytes;                         // reset buffer index
267
268       // keep track of the total number of bytes received
269       bytes_received += nbytes;
270
271       // increment the pointer
272       out += nbytes;
273
274       // Immediately return when data comes in
275       break;
276     }
277
278     #if SNK_VERBOSE
279     printf("\tbytes received: %d bytes (nbytes: %d)\n", bytes, nbytes);
280     #endif
281   }
282
283   #if SRC_VERBOSE
284   printf("Total Bytes Received: %d (bytes_received / noutput_items = %d / %d)\n", 
285          bytes_received, bytes_received, noutput_items);
286   #endif
287
288   // bytes_received is already set to some integer multiple of itemsize
289   return bytes_received/d_itemsize;
290 }
291