Merged -r7436:7453 eb/freebsd into trunk. This is a part of a set of
[debian/gnuradio] / gnuradio-core / src / lib / io / gr_udp_source.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2007,2008 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 <netdb.h>
31
32 #define SRC_VERBOSE 0
33
34 gr_udp_source::gr_udp_source(size_t itemsize, const char *src, 
35                              unsigned short port_src, int payload_size)
36   : gr_sync_block ("udp_source",
37                    gr_make_io_signature(0, 0, 0),
38                    gr_make_io_signature(1, 1, itemsize)),
39     d_itemsize(itemsize), d_updated(false), d_payload_size(payload_size), d_residual(0), d_temp_offset(0)
40 {
41   int ret = 0;
42   
43   // Set up the address stucture for the source address and port numbers
44   // Get the source IP address from the host name
45   struct hostent *hsrc = gethostbyname(src);
46   if(hsrc) {   // if the source was provided as a host namex
47     d_ip_src = *(struct in_addr*)hsrc->h_addr_list[0];    
48   }
49   else { // assume it was specified as an IP address
50     if((ret=inet_aton(src, &d_ip_src)) == 0) {            // format IP address
51       perror("Not a valid source IP address or host name");
52       throw std::runtime_error("can't initialize source socket");
53     }
54   }
55
56   d_port_src = htons(port_src);     // format port number
57   
58   d_sockaddr_src.sin_family = AF_INET;
59   d_sockaddr_src.sin_addr   = d_ip_src;
60   d_sockaddr_src.sin_port   = d_port_src;
61
62   d_temp_buff = new char[d_payload_size];   // allow it to hold up to payload_size bytes
63   
64   open();
65 }
66
67 gr_udp_source_sptr
68 gr_make_udp_source (size_t itemsize, const char *ipaddr, 
69                     unsigned short port, int payload_size)
70 {
71   return gr_udp_source_sptr (new gr_udp_source (itemsize, ipaddr, 
72                                                 port, payload_size));
73 }
74
75 gr_udp_source::~gr_udp_source ()
76 {
77   delete [] d_temp_buff;
78   close();
79 }
80
81 bool
82 gr_udp_source::open()
83 {
84   omni_mutex_lock l(d_mutex);   // hold mutex for duration of this function
85   // create socket
86   d_socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
87   if(d_socket == -1) {
88     perror("socket open");
89     throw std::runtime_error("can't open socket");
90   }
91
92   // Turn on reuse address
93   int opt_val = 1;
94   if(setsockopt(d_socket, SOL_SOCKET, SO_REUSEADDR, (void*)&opt_val, sizeof(int)) == -1) {
95     perror("SO_REUSEADDR");
96     throw std::runtime_error("can't set socket option SO_REUSEADDR");
97   }
98
99   // Don't wait when shutting down
100   linger lngr;
101   lngr.l_onoff  = 1;
102   lngr.l_linger = 0;
103   if(setsockopt(d_socket, SOL_SOCKET, SO_LINGER, (void*)&lngr, sizeof(linger)) == -1) {
104     perror("SO_LINGER");
105     throw std::runtime_error("can't set socket option SO_LINGER");
106   }
107
108   // Set a timeout on the receive function to not block indefinitely
109   // This value can (and probably should) be changed
110   timeval timeout;
111   timeout.tv_sec = 1;
112   timeout.tv_usec = 0;
113   if(setsockopt(d_socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&timeout, sizeof(timeout)) == -1) {
114     perror("SO_RCVTIMEO");
115     throw std::runtime_error("can't set socket option SO_RCVTIMEO");
116   }
117
118   // bind socket to an address and port number to listen on
119   if(bind (d_socket, (sockaddr*)&d_sockaddr_src, sizeof(struct sockaddr)) == -1) {
120     perror("socket bind");
121     throw std::runtime_error("can't bind socket");
122   }
123   
124   d_updated = true;
125   return d_socket != 0;
126 }
127
128 void
129 gr_udp_source::close()
130 {
131   omni_mutex_lock l(d_mutex);   // hold mutex for duration of this function
132
133   if (d_socket){
134     shutdown(d_socket, SHUT_RDWR);
135     d_socket = 0;
136   }
137   d_updated = true;
138 }
139
140 int 
141 gr_udp_source::work (int noutput_items,
142                      gr_vector_const_void_star &input_items,
143                      gr_vector_void_star &output_items)
144 {
145   char *out = (char *) output_items[0];
146   ssize_t r=0, nbytes=0, bytes_received=0;
147   ssize_t total_bytes = (ssize_t)(d_itemsize*noutput_items);
148
149   #if SRC_VERBOSE
150   printf("\nEntered udp_source\n");
151   #endif
152
153   // Remove items from temp buffer if they are in there
154   if(d_residual) {
155     nbytes = std::min(d_residual, total_bytes);
156     memcpy(out, d_temp_buff+d_temp_offset, nbytes);
157     bytes_received = nbytes;
158
159     #if SRC_VERBOSE
160     printf("\tTemp buff size: %d  offset: %d (bytes_received: %d) (noutput_items: %d)\n", 
161            d_residual, d_temp_offset, bytes_received, noutput_items);
162     #endif
163
164     // Increment pointer
165     out += bytes_received;
166     
167     // Update indexing of amount of bytes left in the buffer
168     d_residual -= nbytes;
169     d_temp_offset = d_temp_offset+d_residual;
170   }
171
172   while(1) {
173     // get the data into our output buffer and record the number of bytes
174     // This is a non-blocking call with a timeout set in the constructor
175     r = recv(d_socket, d_temp_buff, d_payload_size, 0);  // get the entire payload or the what's available
176
177     // Check if there was a problem; forget it if the operation just timed out
178     if(r == -1) {
179       if(errno == EAGAIN) {  // handle non-blocking call timeout
180         #if SRC_VERBOSE
181         printf("UDP receive timed out\n"); 
182         #endif
183
184         // Break here to allow the rest of the flow graph time to run and so ctrl-C breaks
185         break;
186       }
187       else {
188         perror("udp_source");
189         return -1;
190       }
191     }
192     else {
193       // Calculate the number of bytes we can take from the buffer in this call
194       nbytes = std::min(r, total_bytes-bytes_received);
195       
196       // adjust the total number of bytes we have to round down to nearest integer of an itemsize
197       nbytes -= ((bytes_received+nbytes) % d_itemsize);   
198
199       // copy the number of bytes we want to look at here
200       memcpy(out, d_temp_buff, nbytes);    
201
202       d_residual = r - nbytes;                      // save the number of bytes stored
203       d_temp_offset=nbytes;                         // reset buffer index
204
205       // keep track of the total number of bytes received
206       bytes_received += nbytes;
207
208       // increment the pointer
209       out += nbytes;
210
211       // Immediately return when data comes in
212       break;
213     }
214
215     #if SNK_VERBOSE
216     printf("\tbytes received: %d bytes (nbytes: %d)\n", bytes, nbytes);
217     #endif
218   }
219
220   #if SRC_VERBOSE
221   printf("Total Bytes Received: %d (bytes_received / noutput_items = %d / %d)\n", 
222          bytes_received, bytes_received, noutput_items);
223   #endif
224
225   // bytes_received is already set to some integer multiple of itemsize
226   return bytes_received/d_itemsize;
227 }
228