]> sjero.net Git - iperf/blob - src/Client.cpp
Native IPv6 support for iperf
[iperf] / src / Client.cpp
1 /*--------------------------------------------------------------- 
2  * Copyright (c) 1999,2000,2001,2002,2003                              
3  * The Board of Trustees of the University of Illinois            
4  * All Rights Reserved.                                           
5  *--------------------------------------------------------------- 
6  * Permission is hereby granted, free of charge, to any person    
7  * obtaining a copy of this software (Iperf) and associated       
8  * documentation files (the "Software"), to deal in the Software  
9  * without restriction, including without limitation the          
10  * rights to use, copy, modify, merge, publish, distribute,        
11  * sublicense, and/or sell copies of the Software, and to permit     
12  * persons to whom the Software is furnished to do
13  * so, subject to the following conditions: 
14  *
15  *     
16  * Redistributions of source code must retain the above 
17  * copyright notice, this list of conditions and 
18  * the following disclaimers. 
19  *
20  *     
21  * Redistributions in binary form must reproduce the above 
22  * copyright notice, this list of conditions and the following 
23  * disclaimers in the documentation and/or other materials 
24  * provided with the distribution. 
25  * 
26  *     
27  * Neither the names of the University of Illinois, NCSA, 
28  * nor the names of its contributors may be used to endorse 
29  * or promote products derived from this Software without
30  * specific prior written permission. 
31  * 
32  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
33  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
34  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
35  * NONINFRINGEMENT. IN NO EVENT SHALL THE CONTIBUTORS OR COPYRIGHT 
36  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
37  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
38  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE
39  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
40  * ________________________________________________________________
41  * National Laboratory for Applied Network Research 
42  * National Center for Supercomputing Applications 
43  * University of Illinois at Urbana-Champaign 
44  * http://www.ncsa.uiuc.edu
45  * ________________________________________________________________ 
46  *
47  * Client.cpp
48  * by Mark Gates <mgates@nlanr.net>
49  * -------------------------------------------------------------------
50  * A client thread initiates a connect to the server and handles
51  * sending and receiving data, then closes the socket.
52  * ------------------------------------------------------------------- */
53
54 #include "headers.h"
55 #include "Client.hpp"
56 #include "Thread.h"
57 #include "SocketAddr.h"
58 #include "PerfSocket.hpp"
59 #include "Extractor.h"
60 #include "delay.hpp"
61 #include "util.h"
62 #include "Locale.h"
63
64 /* -------------------------------------------------------------------
65  * Store server hostname, optionally local hostname, and socket info.
66  * ------------------------------------------------------------------- */
67
68 Client::Client( thread_Settings *inSettings ) {
69     mSettings = inSettings;
70     mBuf = NULL;
71
72     // connect
73     Connect( );
74
75     // initialize buffer
76     mBuf = new char[ mSettings->mBufLen ];
77     pattern( mBuf, mSettings->mBufLen );
78     if ( isFileInput( mSettings ) ) {
79         if ( !isSTDIN( mSettings ) )
80             Extractor_Initialize( mSettings->mFileName, mSettings->mBufLen, mSettings );
81         else
82             Extractor_InitializeFile( stdin, mSettings->mBufLen, mSettings );
83
84         if ( !Extractor_canRead( mSettings ) ) {
85             unsetFileInput( mSettings );
86         }
87     }
88
89     if ( isReport( inSettings ) ) {
90         ReportSettings( inSettings );
91         if ( mSettings->multihdr && isMultipleReport( inSettings ) ) {
92             mSettings->multihdr->report->connection.peer = mSettings->peer;
93             mSettings->multihdr->report->connection.local = mSettings->local;
94         }
95     }
96
97 } // end Client
98
99 /* -------------------------------------------------------------------
100  * Delete memory (hostname strings).
101  * ------------------------------------------------------------------- */
102
103 Client::~Client() {
104     if ( mSettings->mSock != INVALID_SOCKET ) {
105         int rc = close( mSettings->mSock );
106         WARN_errno( rc == SOCKET_ERROR, "close" );
107         mSettings->mSock = INVALID_SOCKET;
108     }
109     DELETE_ARRAY( mBuf );
110 } // end ~Client
111
112 const double kSecs_to_usecs = 1.0e6;
113 const double kBytes_to_Bits = 8.0;
114
115 /* ------------------------------------------------------------------- 
116  * Send data using the connected UDP/TCP socket, 
117  * until a termination flag is reached. 
118  * Does not close the socket. 
119  * ------------------------------------------------------------------- */ 
120
121 void Client::Run( void ) {
122     struct dgram_record* mBuf_Dgram = (struct dgram_record*) mBuf;
123     long  currLen = 0, packet_gap = 0, delta, loop_time = 0, adjust = 0;
124     char* readAt = mBuf;
125     bool canRead = true,        // Indicates if the stream is readable
126          mMode_Time = isModeTime( mSettings );
127     ReportStruct *reportstruct = NULL;
128
129     // setup termination variables
130     if ( mMode_Time ) {
131         mEndTime.setnow();
132         mEndTime.add( mSettings->mAmount / 100.0 );
133     }
134
135     if ( isPacketOriented( mSettings ) ) {
136         // compute delay for bandwidth restriction, constrained to [0,1] seconds 
137         packet_gap = (long)((double)(mSettings->mBufLen * kSecs_to_usecs * kBytes_to_Bits) /
138                                                                (double)mSettings->mDgramRate);
139
140         if (packet_gap < 0 || packet_gap > kSecs_to_usecs) {
141             fprintf( stderr, warn_delay_large, packet_gap / kSecs_to_usecs );
142             packet_gap = (long)kSecs_to_usecs;
143         }
144         // Initialise adjustment variable: in this way, the first adjustment will be
145         // the latency for sending the first packet, and all sending times are
146         // synchronised with regard to the first timestamp.
147         adjust = -packet_gap;
148
149         // Due to the included timestamps etc,
150         // reduce the read size by an amount equal to the header size
151         if ( isFileInput( mSettings ) ) {
152             size_t offset = sizeof(struct dgram_record);
153
154             if (!isCompat(mSettings))
155                 offset += sizeof(struct client_hdr);
156
157             Extractor_reduceReadSize(offset, mSettings);
158             readAt += offset;
159         }
160     }
161
162     // InitReport handles Barrier for multiple Streams
163     mSettings->reporthdr = InitReport( mSettings );
164     reportstruct = new ReportStruct;
165
166     // Connectionless protocols use the first message as "connect" message (which is
167     // counted, but their FIN is not counted. For connection-oriented protocols we
168     // start at message #1 instead of at #0; and the FIN is not counted.
169     reportstruct->packetID = (!isConnectionLess(mSettings) && isPacketOriented(mSettings));
170
171     // Set a timestamp now corresponding to an imaginary zero-th send time.
172     lastPacketTime.setnow();
173
174     do {
175         // Test case: drop 17 packets and send 2 out-of-order: 
176         // sequence 51, 52, 70, 53, 54, 71, 72 
177         //switch( datagramID ) { 
178         //  case 53: datagramID = 70; break; 
179         //  case 71: datagramID = 53; break; 
180         //  case 55: datagramID = 71; break; 
181         //  default: break; 
182         //} 
183
184         // Note that the timestamp does not account for the time-to-wire of the packet.
185         // This plays a role when looking at jitter/delay values.
186         gettimeofday( &(reportstruct->packetTime), NULL );
187
188         if ( isPacketOriented( mSettings ) ) {
189             // Increment packet ID after sending and before reporting
190             // UDP:  sends from 0..n-1, counts from 1..n
191             // DCCP: sends from 1..n,   counts from 2..n+1
192             // This difference is of interest for the client only (the server sees
193             // 1..n). The client uses cntDatagrams, so that the count is correct.
194             // (Consider the trick in CloseReport() which resetts packetID.)
195             mBuf_Dgram->id      = htonl( reportstruct->packetID++ );
196             mBuf_Dgram->tv_sec  = htonl( reportstruct->packetTime.tv_sec );
197             mBuf_Dgram->tv_usec = htonl( reportstruct->packetTime.tv_usec );
198         } else if (!mMode_Time && mSettings->mAmount < mSettings->mBufLen)
199             mSettings->mBufLen = mSettings->mAmount;
200
201         // Read the next data block from the file if it's file input
202         if ( isFileInput( mSettings ) ) {
203             Extractor_getNextDataBlock( readAt, mSettings ); 
204             canRead = Extractor_canRead( mSettings ) != 0; 
205         }
206
207         // Put the packet onto the wire.
208         // When EAGAIN is returned (DCCP), the internal TX buffer is full: due to
209         // congestion-control issues the packet can not be transported now.
210         do {
211             currLen = write( mSettings->mSock, mBuf, mSettings->mBufLen );
212         } while (currLen < 0 && errno == EAGAIN);
213
214         if (currLen < 0) {
215             WARN_errno(1, "client write");
216             break;
217         }
218         // update statistics
219         reportstruct->packetLen = currLen;
220         ReportPacket( mSettings->reporthdr, reportstruct );
221
222         if (mMode_Time) {
223             // time-oriented mode (-t): termination
224             canRead = mEndTime.after(reportstruct->packetTime);
225         } else {
226             // amount-oriented mode (-n): mAmount is unsigned
227             if (currLen >= mSettings->mAmount)
228                 break;
229             mSettings->mAmount -= currLen;
230         }
231
232         if (isPacketOriented(mSettings)) {
233             // Adjust the inter-packet gap using the following variables:
234             //   delta      is the gap in between calls to send()
235             //   adjust     acts as a token bucket whenever delta != packet_gap
236             //   loop_time  equals packet_gap if adjust==0, it is corrected otherwise
237             //
238             // TODO this doesn't work well in certain cases, like 2 parallel streams
239             //
240             delta = lastPacketTime.delta_usec();
241             adjust += packet_gap - delta;
242             loop_time = packet_gap + adjust;
243
244             if (loop_time > 0)
245                 delay_loop(loop_time);
246        }
247
248     } while (canRead && !sInterupted);
249
250     // stop timing
251     gettimeofday( &(reportstruct->packetTime), NULL );
252     CloseReport( mSettings->reporthdr, reportstruct );
253
254     if ( isPacketOriented( mSettings ) ) {
255         // send a final terminating datagram 
256         // For connectionless protocols, don't count in the mTotalLen.
257         // The server counts this one, but didn't count our first datagram
258         // (connect message), so we're even now.
259
260         // store datagram ID into buffer 
261         // The negative datagram ID signifies termination to the server.
262         mBuf_Dgram->id      = htonl( -(reportstruct->packetID)  );
263         mBuf_Dgram->tv_sec  = htonl( reportstruct->packetTime.tv_sec );
264         mBuf_Dgram->tv_usec = htonl( reportstruct->packetTime.tv_usec );
265
266         if ( isMulticast( mSettings ) )
267             write( mSettings->mSock, mBuf, mSettings->mBufLen ); 
268         else
269             write_dgram_FIN( );
270     }
271     DELETE_PTR( reportstruct );
272     EndReport( mSettings->reporthdr );
273
274
275 void Client::InitiateServer()
276 {
277     client_hdr *temp_hdr = (client_hdr*)mBuf;
278
279     if (isCompat(mSettings))
280         return;
281      // connection-less protocols communicate their settings in the first
282      // packet sent to the server; this packet is not counted by the server
283      if (isConnectionLess(mSettings)) {
284         dgram_record *record_hdr = (dgram_record *)mBuf;
285         temp_hdr = (client_hdr*)(record_hdr + 1);
286       }
287
288       Settings_GenerateClientHdr( mSettings, temp_hdr );
289
290       // connection-oriented protocols use a short "init" message
291       if ( !isConnectionLess( mSettings ) ) {
292         int rc;
293
294         do {
295              rc = send(mSettings->mSock, mBuf, sizeof(client_hdr), 0);
296         } while (rc < 0 && errno == EAGAIN);
297         WARN_errno(rc < 0, "write failed in InitiateServer()");
298       }
299 }
300
301 /* -------------------------------------------------------------------
302  * Setup a socket connected to a server.
303  * If inLocalhost is not null, bind to that address, specifying
304  * which outgoing interface to use.
305  * ------------------------------------------------------------------- */
306 void Client::Connect()
307 {
308     socklen_t size_local = sizeof(mSettings->local);
309
310     MakeSocket(mSettings);
311
312     /* determine local interface after establishing the connection */
313     getsockname(mSettings->mSock, (struct sockaddr *)&mSettings->local, &size_local);
314
315     /* The DCCP packet size must not exceed the MPS (RFC 4340, 14.) */
316     if (mSettings->mProtocol == kProto_DCCP) {
317         unsigned mps = getsock_dccp_mps(mSettings->mSock);
318
319         if (mSettings->mBufLen > mps)
320            die("Buffer length %d exceeds DCCP MPS %d. Use a smaller buffer size "
321                "(-l) on server/client.", mSettings->mBufLen, mps);
322     }
323 }
324
325
326 /* ------------------------------------------------------------------- 
327  * Send a datagram on the socket. The datagram's contents should signify 
328  * a FIN to the application. Keep re-transmitting until an 
329  * acknowledgement datagram is received. 
330  * ------------------------------------------------------------------- */ 
331 void Client::write_dgram_FIN( ) {
332     int rc, count = 0;
333     fd_set readSet; 
334     struct timeval timeout; 
335     size_t len = mSettings->mBufLen;
336
337     // we don't need the full buffer size here - it is not counted
338     if (!isConnectionLess(mSettings))
339         len = sizeof(dgram_record);
340
341     while ( count < 10 ) {
342         count++;
343
344         // write data 
345         write( mSettings->mSock, mBuf, len);
346
347         // wait until the socket is readable, or our timeout expires 
348         FD_ZERO( &readSet ); 
349         FD_SET( mSettings->mSock, &readSet ); 
350         timeout.tv_sec  = 0; 
351         timeout.tv_usec = 250000; // quarter second, 250 ms 
352
353         rc = select( mSettings->mSock+1, &readSet, NULL, NULL, &timeout ); 
354         FAIL_errno( rc == SOCKET_ERROR, "select", mSettings ); 
355
356         if ( rc == 0 ) {
357             // select timed out 
358             continue; 
359         } else {
360             // socket ready to read 
361             rc = read( mSettings->mSock, mBuf, mSettings->mBufLen ); 
362             WARN_errno( rc < 0, "read" );
363             if ( rc < 0 ) {
364                 break;
365             } else if ( rc >= (int) (sizeof(dgram_record) + sizeof(server_hdr)) ) {
366                 ReportServerUDP( mSettings, (server_hdr*) ((dgram_record*)mBuf + 1) );
367             }
368             return; 
369         } 
370     } 
371     fprintf( stderr, warn_no_ack, mSettings->mSock, count ); 
372
373 // end write_dgram_FIN