xref: /iperf/src/iperf_api.c (revision 19dcd39d)
1 /*
2  * iperf, Copyright (c) 2014, The Regents of the University of
3  * California, through Lawrence Berkeley National Laboratory (subject
4  * to receipt of any required approvals from the U.S. Dept. of
5  * Energy).  All rights reserved.
6  *
7  * If you have questions about your rights to use or distribute this
8  * software, please contact Berkeley Lab's Technology Transfer
9  * Department at [email protected].
10  *
11  * NOTICE.  This software is owned by the U.S. Department of Energy.
12  * As such, the U.S. Government has been granted for itself and others
13  * acting on its behalf a paid-up, nonexclusive, irrevocable,
14  * worldwide license in the Software to reproduce, prepare derivative
15  * works, and perform publicly and display publicly.  Beginning five
16  * (5) years after the date permission to assert copyright is obtained
17  * from the U.S. Department of Energy, and subject to any subsequent
18  * five (5) year renewals, the U.S. Government is granted for itself
19  * and others acting on its behalf a paid-up, nonexclusive,
20  * irrevocable, worldwide license in the Software to reproduce,
21  * prepare derivative works, distribute copies to the public, perform
22  * publicly and display publicly, and to permit others to do so.
23  *
24  * This code is distributed under a BSD style license, see the LICENSE file
25  * for complete information.
26  */
27 #define _GNU_SOURCE
28 #define __USE_GNU
29 
30 #include "iperf_config.h"
31 
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <getopt.h>
36 #include <errno.h>
37 #include <signal.h>
38 #include <unistd.h>
39 #include <assert.h>
40 #include <fcntl.h>
41 #include <sys/socket.h>
42 #include <sys/types.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #include <netdb.h>
46 #include <pthread.h>
47 #ifdef HAVE_STDINT_H
48 #include <stdint.h>
49 #endif
50 #include <netinet/tcp.h>
51 #include <sys/time.h>
52 #include <sys/resource.h>
53 #include <sys/mman.h>
54 #include <sys/stat.h>
55 #include <sched.h>
56 #include <setjmp.h>
57 #include <stdarg.h>
58 
59 #if defined(HAVE_CPUSET_SETAFFINITY)
60 #include <sys/param.h>
61 #include <sys/cpuset.h>
62 #endif /* HAVE_CPUSET_SETAFFINITY */
63 
64 #include "net.h"
65 #include "iperf.h"
66 #include "iperf_api.h"
67 #include "iperf_udp.h"
68 #include "iperf_tcp.h"
69 #if defined(HAVE_SCTP)
70 #include "iperf_sctp.h"
71 #endif /* HAVE_SCTP */
72 #include "timer.h"
73 
74 #include "cjson.h"
75 #include "units.h"
76 #include "tcp_window_size.h"
77 #include "iperf_util.h"
78 #include "iperf_locale.h"
79 #include "version.h"
80 
81 /* Forwards. */
82 static int send_parameters(struct iperf_test *test);
83 static int get_parameters(struct iperf_test *test);
84 static int send_results(struct iperf_test *test);
85 static int get_results(struct iperf_test *test);
86 static int diskfile_send(struct iperf_stream *sp);
87 static int diskfile_recv(struct iperf_stream *sp);
88 static int JSON_write(int fd, cJSON *json);
89 static void print_interval_results(struct iperf_test *test, struct iperf_stream *sp, cJSON *json_interval_streams);
90 static cJSON *JSON_read(int fd);
91 
92 
93 /*************************** Print usage functions ****************************/
94 
95 void
96 usage()
97 {
98     fputs(usage_shortstr, stderr);
99 }
100 
101 
102 void
103 usage_long()
104 {
105     fprintf(stderr, usage_longstr, UDP_RATE / (1024*1024), DURATION, DEFAULT_TCP_BLKSIZE / 1024, DEFAULT_UDP_BLKSIZE / 1024);
106 }
107 
108 
109 void warning(char *str)
110 {
111     fprintf(stderr, "warning: %s\n", str);
112 }
113 
114 
115 /************** Getter routines for some fields inside iperf_test *************/
116 
117 int
118 iperf_get_verbose(struct iperf_test *ipt)
119 {
120     return ipt->verbose;
121 }
122 
123 int
124 iperf_get_control_socket(struct iperf_test *ipt)
125 {
126     return ipt->ctrl_sck;
127 }
128 
129 int
130 iperf_get_test_omit(struct iperf_test *ipt)
131 {
132     return ipt->omit;
133 }
134 
135 int
136 iperf_get_test_duration(struct iperf_test *ipt)
137 {
138     return ipt->duration;
139 }
140 
141 uint64_t
142 iperf_get_test_rate(struct iperf_test *ipt)
143 {
144     return ipt->settings->rate;
145 }
146 
147 int
148 iperf_get_test_burst(struct iperf_test *ipt)
149 {
150     return ipt->settings->burst;
151 }
152 
153 char
154 iperf_get_test_role(struct iperf_test *ipt)
155 {
156     return ipt->role;
157 }
158 
159 int
160 iperf_get_test_reverse(struct iperf_test *ipt)
161 {
162     return ipt->reverse;
163 }
164 
165 int
166 iperf_get_test_blksize(struct iperf_test *ipt)
167 {
168     return ipt->settings->blksize;
169 }
170 
171 FILE *
172 iperf_get_test_outfile (struct iperf_test *ipt)
173 {
174     return ipt->outfile;
175 }
176 
177 int
178 iperf_get_test_socket_bufsize(struct iperf_test *ipt)
179 {
180     return ipt->settings->socket_bufsize;
181 }
182 
183 double
184 iperf_get_test_reporter_interval(struct iperf_test *ipt)
185 {
186     return ipt->reporter_interval;
187 }
188 
189 double
190 iperf_get_test_stats_interval(struct iperf_test *ipt)
191 {
192     return ipt->stats_interval;
193 }
194 
195 int
196 iperf_get_test_num_streams(struct iperf_test *ipt)
197 {
198     return ipt->num_streams;
199 }
200 
201 int
202 iperf_get_test_server_port(struct iperf_test *ipt)
203 {
204     return ipt->server_port;
205 }
206 
207 char*
208 iperf_get_test_server_hostname(struct iperf_test *ipt)
209 {
210     return ipt->server_hostname;
211 }
212 
213 int
214 iperf_get_test_protocol_id(struct iperf_test *ipt)
215 {
216     return ipt->protocol->id;
217 }
218 
219 int
220 iperf_get_test_json_output(struct iperf_test *ipt)
221 {
222     return ipt->json_output;
223 }
224 
225 char *
226 iperf_get_test_json_output_string(struct iperf_test *ipt)
227 {
228     return ipt->json_output_string;
229 }
230 
231 int
232 iperf_get_test_zerocopy(struct iperf_test *ipt)
233 {
234     return ipt->zerocopy;
235 }
236 
237 int
238 iperf_get_test_get_server_output(struct iperf_test *ipt)
239 {
240     return ipt->get_server_output;
241 }
242 
243 char
244 iperf_get_test_unit_format(struct iperf_test *ipt)
245 {
246     return ipt->settings->unit_format;
247 }
248 
249 char *
250 iperf_get_test_bind_address(struct iperf_test *ipt)
251 {
252     return ipt->bind_address;
253 }
254 
255 int
256 iperf_get_test_udp_counters_64bit(struct iperf_test *ipt)
257 {
258     return ipt->udp_counters_64bit;
259 }
260 
261 int
262 iperf_get_test_one_off(struct iperf_test *ipt)
263 {
264     return ipt->one_off;
265 }
266 
267 /************** Setter routines for some fields inside iperf_test *************/
268 
269 void
270 iperf_set_verbose(struct iperf_test *ipt, int verbose)
271 {
272     ipt->verbose = verbose;
273 }
274 
275 void
276 iperf_set_control_socket(struct iperf_test *ipt, int ctrl_sck)
277 {
278     ipt->ctrl_sck = ctrl_sck;
279 }
280 
281 void
282 iperf_set_test_omit(struct iperf_test *ipt, int omit)
283 {
284     ipt->omit = omit;
285 }
286 
287 void
288 iperf_set_test_duration(struct iperf_test *ipt, int duration)
289 {
290     ipt->duration = duration;
291 }
292 
293 void
294 iperf_set_test_reporter_interval(struct iperf_test *ipt, double reporter_interval)
295 {
296     ipt->reporter_interval = reporter_interval;
297 }
298 
299 void
300 iperf_set_test_stats_interval(struct iperf_test *ipt, double stats_interval)
301 {
302     ipt->stats_interval = stats_interval;
303 }
304 
305 void
306 iperf_set_test_state(struct iperf_test *ipt, signed char state)
307 {
308     ipt->state = state;
309 }
310 
311 void
312 iperf_set_test_blksize(struct iperf_test *ipt, int blksize)
313 {
314     ipt->settings->blksize = blksize;
315 }
316 
317 void
318 iperf_set_test_rate(struct iperf_test *ipt, uint64_t rate)
319 {
320     ipt->settings->rate = rate;
321 }
322 
323 void
324 iperf_set_test_burst(struct iperf_test *ipt, int burst)
325 {
326     ipt->settings->burst = burst;
327 }
328 
329 void
330 iperf_set_test_server_port(struct iperf_test *ipt, int server_port)
331 {
332     ipt->server_port = server_port;
333 }
334 
335 void
336 iperf_set_test_socket_bufsize(struct iperf_test *ipt, int socket_bufsize)
337 {
338     ipt->settings->socket_bufsize = socket_bufsize;
339 }
340 
341 void
342 iperf_set_test_num_streams(struct iperf_test *ipt, int num_streams)
343 {
344     ipt->num_streams = num_streams;
345 }
346 
347 static void
348 check_sender_has_retransmits(struct iperf_test *ipt)
349 {
350     if (ipt->sender && ipt->protocol->id == Ptcp && has_tcpinfo_retransmits())
351 	ipt->sender_has_retransmits = 1;
352     else
353 	ipt->sender_has_retransmits = 0;
354 }
355 
356 void
357 iperf_set_test_role(struct iperf_test *ipt, char role)
358 {
359     ipt->role = role;
360     if (role == 'c')
361 	ipt->sender = 1;
362     else if (role == 's')
363 	ipt->sender = 0;
364     if (ipt->reverse)
365         ipt->sender = ! ipt->sender;
366     check_sender_has_retransmits(ipt);
367 }
368 
369 void
370 iperf_set_test_server_hostname(struct iperf_test *ipt, char *server_hostname)
371 {
372     ipt->server_hostname = strdup(server_hostname);
373 }
374 
375 void
376 iperf_set_test_reverse(struct iperf_test *ipt, int reverse)
377 {
378     ipt->reverse = reverse;
379     if (ipt->reverse)
380         ipt->sender = ! ipt->sender;
381     check_sender_has_retransmits(ipt);
382 }
383 
384 void
385 iperf_set_test_json_output(struct iperf_test *ipt, int json_output)
386 {
387     ipt->json_output = json_output;
388 }
389 
390 int
391 iperf_has_zerocopy( void )
392 {
393     return has_sendfile();
394 }
395 
396 void
397 iperf_set_test_zerocopy(struct iperf_test *ipt, int zerocopy)
398 {
399     ipt->zerocopy = (zerocopy && has_sendfile());
400 }
401 
402 void
403 iperf_set_test_get_server_output(struct iperf_test *ipt, int get_server_output)
404 {
405     ipt->get_server_output = get_server_output;
406 }
407 
408 void
409 iperf_set_test_unit_format(struct iperf_test *ipt, char unit_format)
410 {
411     ipt->settings->unit_format = unit_format;
412 }
413 
414 void
415 iperf_set_test_bind_address(struct iperf_test *ipt, char *bind_address)
416 {
417     ipt->bind_address = strdup(bind_address);
418 }
419 
420 void
421 iperf_set_test_udp_counters_64bit(struct iperf_test *ipt, int udp_counters_64bit)
422 {
423     ipt->udp_counters_64bit = udp_counters_64bit;
424 }
425 
426 void
427 iperf_set_test_one_off(struct iperf_test *ipt, int one_off)
428 {
429     ipt->one_off = one_off;
430 }
431 
432 /********************** Get/set test protocol structure ***********************/
433 
434 struct protocol *
435 get_protocol(struct iperf_test *test, int prot_id)
436 {
437     struct protocol *prot;
438 
439     SLIST_FOREACH(prot, &test->protocols, protocols) {
440         if (prot->id == prot_id)
441             break;
442     }
443 
444     if (prot == NULL)
445         i_errno = IEPROTOCOL;
446 
447     return prot;
448 }
449 
450 int
451 set_protocol(struct iperf_test *test, int prot_id)
452 {
453     struct protocol *prot = NULL;
454 
455     SLIST_FOREACH(prot, &test->protocols, protocols) {
456         if (prot->id == prot_id) {
457             test->protocol = prot;
458 	    check_sender_has_retransmits(test);
459             return 0;
460         }
461     }
462 
463     i_errno = IEPROTOCOL;
464     return -1;
465 }
466 
467 
468 /************************** Iperf callback functions **************************/
469 
470 void
471 iperf_on_new_stream(struct iperf_stream *sp)
472 {
473     connect_msg(sp);
474 }
475 
476 void
477 iperf_on_test_start(struct iperf_test *test)
478 {
479     if (test->json_output) {
480 	cJSON_AddItemToObject(test->json_start, "test_start", iperf_json_printf("protocol: %s  num_streams: %d  blksize: %d  omit: %d  duration: %d  bytes: %d  blocks: %d  reverse: %d", test->protocol->name, (int64_t) test->num_streams, (int64_t) test->settings->blksize, (int64_t) test->omit, (int64_t) test->duration, (int64_t) test->settings->bytes, (int64_t) test->settings->blocks, test->reverse?(int64_t)1:(int64_t)0));
481     } else {
482 	if (test->verbose) {
483 	    if (test->settings->bytes)
484 		iprintf(test, test_start_bytes, test->protocol->name, test->num_streams, test->settings->blksize, test->omit, test->settings->bytes);
485 	    else if (test->settings->blocks)
486 		iprintf(test, test_start_blocks, test->protocol->name, test->num_streams, test->settings->blksize, test->omit, test->settings->blocks);
487 	    else
488 		iprintf(test, test_start_time, test->protocol->name, test->num_streams, test->settings->blksize, test->omit, test->duration);
489 	}
490     }
491 }
492 
493 /* This converts an IPv6 string address from IPv4-mapped format into regular
494 ** old IPv4 format, which is easier on the eyes of network veterans.
495 **
496 ** If the v6 address is not v4-mapped it is left alone.
497 */
498 static void
499 mapped_v4_to_regular_v4(char *str)
500 {
501     char *prefix = "::ffff:";
502     int prefix_len;
503 
504     prefix_len = strlen(prefix);
505     if (strncmp(str, prefix, prefix_len) == 0) {
506 	int str_len = strlen(str);
507 	memmove(str, str + prefix_len, str_len - prefix_len + 1);
508     }
509 }
510 
511 void
512 iperf_on_connect(struct iperf_test *test)
513 {
514     time_t now_secs;
515     const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT";
516     char now_str[100];
517     char ipr[INET6_ADDRSTRLEN];
518     int port;
519     struct sockaddr_storage sa;
520     struct sockaddr_in *sa_inP;
521     struct sockaddr_in6 *sa_in6P;
522     socklen_t len;
523     int opt;
524 
525     now_secs = time((time_t*) 0);
526     (void) strftime(now_str, sizeof(now_str), rfc1123_fmt, gmtime(&now_secs));
527     if (test->json_output)
528 	cJSON_AddItemToObject(test->json_start, "timestamp", iperf_json_printf("time: %s  timesecs: %d", now_str, (int64_t) now_secs));
529     else if (test->verbose)
530 	iprintf(test, report_time, now_str);
531 
532     if (test->role == 'c') {
533 	if (test->json_output)
534 	    cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s  port: %d", test->server_hostname, (int64_t) test->server_port));
535 	else {
536 	    iprintf(test, report_connecting, test->server_hostname, test->server_port);
537 	    if (test->reverse)
538 		iprintf(test, report_reverse, test->server_hostname);
539 	}
540     } else {
541         len = sizeof(sa);
542         getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len);
543         if (getsockdomain(test->ctrl_sck) == AF_INET) {
544 	    sa_inP = (struct sockaddr_in *) &sa;
545             inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr));
546 	    port = ntohs(sa_inP->sin_port);
547         } else {
548 	    sa_in6P = (struct sockaddr_in6 *) &sa;
549             inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr));
550 	    port = ntohs(sa_in6P->sin6_port);
551         }
552 	mapped_v4_to_regular_v4(ipr);
553 	if (test->json_output)
554 	    cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s  port: %d", ipr, (int64_t) port));
555 	else
556 	    iprintf(test, report_accepted, ipr, port);
557     }
558     if (test->json_output) {
559 	cJSON_AddStringToObject(test->json_start, "cookie", test->cookie);
560         if (test->protocol->id == SOCK_STREAM) {
561 	    if (test->settings->mss)
562 		cJSON_AddIntToObject(test->json_start, "tcp_mss", test->settings->mss);
563 	    else {
564 		len = sizeof(opt);
565 		getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len);
566 		cJSON_AddIntToObject(test->json_start, "tcp_mss_default", opt);
567 	    }
568 	}
569     } else if (test->verbose) {
570         iprintf(test, report_cookie, test->cookie);
571         if (test->protocol->id == SOCK_STREAM) {
572             if (test->settings->mss)
573                 iprintf(test, "      TCP MSS: %d\n", test->settings->mss);
574             else {
575                 len = sizeof(opt);
576                 getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len);
577                 iprintf(test, "      TCP MSS: %d (default)\n", opt);
578             }
579         }
580 
581     }
582 }
583 
584 void
585 iperf_on_test_finish(struct iperf_test *test)
586 {
587 }
588 
589 
590 /******************************************************************************/
591 
592 int
593 iperf_parse_arguments(struct iperf_test *test, int argc, char **argv)
594 {
595     static struct option longopts[] =
596     {
597         {"port", required_argument, NULL, 'p'},
598         {"format", required_argument, NULL, 'f'},
599         {"interval", required_argument, NULL, 'i'},
600         {"daemon", no_argument, NULL, 'D'},
601         {"one-off", no_argument, NULL, '1'},
602         {"verbose", no_argument, NULL, 'V'},
603         {"json", no_argument, NULL, 'J'},
604         {"version", no_argument, NULL, 'v'},
605         {"server", no_argument, NULL, 's'},
606         {"client", required_argument, NULL, 'c'},
607         {"udp", no_argument, NULL, 'u'},
608         {"bandwidth", required_argument, NULL, 'b'},
609         {"time", required_argument, NULL, 't'},
610         {"bytes", required_argument, NULL, 'n'},
611         {"blockcount", required_argument, NULL, 'k'},
612         {"length", required_argument, NULL, 'l'},
613         {"parallel", required_argument, NULL, 'P'},
614         {"reverse", no_argument, NULL, 'R'},
615         {"window", required_argument, NULL, 'w'},
616         {"bind", required_argument, NULL, 'B'},
617         {"cport", required_argument, NULL, OPT_CLIENT_PORT},
618         {"set-mss", required_argument, NULL, 'M'},
619         {"no-delay", no_argument, NULL, 'N'},
620         {"version4", no_argument, NULL, '4'},
621         {"version6", no_argument, NULL, '6'},
622         {"tos", required_argument, NULL, 'S'},
623 #if defined(HAVE_FLOWLABEL)
624         {"flowlabel", required_argument, NULL, 'L'},
625 #endif /* HAVE_FLOWLABEL */
626         {"zerocopy", no_argument, NULL, 'Z'},
627         {"omit", required_argument, NULL, 'O'},
628         {"file", required_argument, NULL, 'F'},
629 #if defined(HAVE_CPU_AFFINITY)
630         {"affinity", required_argument, NULL, 'A'},
631 #endif /* HAVE_CPU_AFFINITY */
632         {"title", required_argument, NULL, 'T'},
633 #if defined(HAVE_TCP_CONGESTION)
634         {"congestion", required_argument, NULL, 'C'},
635         {"linux-congestion", required_argument, NULL, 'C'},
636 #endif /* HAVE_TCP_CONGESTION */
637 #if defined(HAVE_SCTP)
638         {"sctp", no_argument, NULL, OPT_SCTP},
639         {"nstreams", required_argument, NULL, OPT_NUMSTREAMS},
640         {"xbind", required_argument, NULL, 'X'},
641 #endif
642 	{"pidfile", required_argument, NULL, 'I'},
643 	{"logfile", required_argument, NULL, OPT_LOGFILE},
644 	{"get-server-output", no_argument, NULL, OPT_GET_SERVER_OUTPUT},
645 	{"udp-counters-64bit", no_argument, NULL, OPT_UDP_COUNTERS_64BIT},
646         {"debug", no_argument, NULL, 'd'},
647         {"help", no_argument, NULL, 'h'},
648         {NULL, 0, NULL, 0}
649     };
650     int flag;
651     int blksize;
652     int server_flag, client_flag, rate_flag, duration_flag;
653 #if defined(HAVE_CPU_AFFINITY)
654     char* comma;
655 #endif /* HAVE_CPU_AFFINITY */
656     char* slash;
657     struct xbind_entry *xbe;
658 
659     blksize = 0;
660     server_flag = client_flag = rate_flag = duration_flag = 0;
661     while ((flag = getopt_long(argc, argv, "p:f:i:D1VJvsc:ub:t:n:k:l:P:Rw:B:M:N46S:L:ZO:F:A:T:C:dI:hX:", longopts, NULL)) != -1) {
662         switch (flag) {
663             case 'p':
664                 test->server_port = atoi(optarg);
665                 break;
666             case 'f':
667                 test->settings->unit_format = *optarg;
668                 break;
669             case 'i':
670                 /* XXX: could potentially want separate stat collection and reporting intervals,
671                    but just set them to be the same for now */
672                 test->stats_interval = test->reporter_interval = atof(optarg);
673                 if ((test->stats_interval < MIN_INTERVAL || test->stats_interval > MAX_INTERVAL) && test->stats_interval != 0) {
674                     i_errno = IEINTERVAL;
675                     return -1;
676                 }
677                 break;
678             case 'D':
679 		test->daemon = 1;
680 		server_flag = 1;
681 	        break;
682             case '1':
683 		test->one_off = 1;
684 		server_flag = 1;
685 	        break;
686             case 'V':
687                 test->verbose = 1;
688                 break;
689             case 'J':
690                 test->json_output = 1;
691                 break;
692             case 'v':
693                 printf("%s\n%s\n%s\n", version, get_system_info(),
694 		       get_optional_features());
695                 exit(0);
696             case 's':
697                 if (test->role == 'c') {
698                     i_errno = IESERVCLIENT;
699                     return -1;
700                 }
701 		iperf_set_test_role(test, 's');
702                 break;
703             case 'c':
704                 if (test->role == 's') {
705                     i_errno = IESERVCLIENT;
706                     return -1;
707                 }
708 		iperf_set_test_role(test, 'c');
709 		iperf_set_test_server_hostname(test, optarg);
710                 break;
711             case 'u':
712                 set_protocol(test, Pudp);
713 		client_flag = 1;
714                 break;
715             case OPT_SCTP:
716 #if defined(HAVE_SCTP)
717                 set_protocol(test, Psctp);
718                 client_flag = 1;
719 #else /* HAVE_SCTP */
720                 i_errno = IEUNIMP;
721                 return -1;
722 #endif /* HAVE_SCTP */
723             break;
724 
725             case OPT_NUMSTREAMS:
726 #if defined(linux) || defined(__FreeBSD__)
727                 test->settings->num_ostreams = unit_atoi(optarg);
728                 client_flag = 1;
729 #else /* linux */
730                 i_errno = IEUNIMP;
731                 return -1;
732 #endif /* linux */
733             case 'b':
734 		slash = strchr(optarg, '/');
735 		if (slash) {
736 		    *slash = '\0';
737 		    ++slash;
738 		    test->settings->burst = atoi(slash);
739 		    if (test->settings->burst <= 0 ||
740 		        test->settings->burst > MAX_BURST) {
741 			i_errno = IEBURST;
742 			return -1;
743 		    }
744 		}
745                 test->settings->rate = unit_atof_rate(optarg);
746 		rate_flag = 1;
747 		client_flag = 1;
748                 break;
749             case 't':
750                 test->duration = atoi(optarg);
751                 if (test->duration > MAX_TIME) {
752                     i_errno = IEDURATION;
753                     return -1;
754                 }
755 		duration_flag = 1;
756 		client_flag = 1;
757                 break;
758             case 'n':
759                 test->settings->bytes = unit_atoi(optarg);
760 		client_flag = 1;
761                 break;
762             case 'k':
763                 test->settings->blocks = unit_atoi(optarg);
764 		client_flag = 1;
765                 break;
766             case 'l':
767                 blksize = unit_atoi(optarg);
768 		client_flag = 1;
769                 break;
770             case 'P':
771                 test->num_streams = atoi(optarg);
772                 if (test->num_streams > MAX_STREAMS) {
773                     i_errno = IENUMSTREAMS;
774                     return -1;
775                 }
776 		client_flag = 1;
777                 break;
778             case 'R':
779 		iperf_set_test_reverse(test, 1);
780 		client_flag = 1;
781                 break;
782             case 'w':
783                 // XXX: This is a socket buffer, not specific to TCP
784                 test->settings->socket_bufsize = unit_atof(optarg);
785                 if (test->settings->socket_bufsize > MAX_TCP_BUFFER) {
786                     i_errno = IEBUFSIZE;
787                     return -1;
788                 }
789 		client_flag = 1;
790                 break;
791             case 'B':
792                 test->bind_address = strdup(optarg);
793                 break;
794             case OPT_CLIENT_PORT:
795                 test->bind_port = atoi(optarg);
796                 break;
797             case 'M':
798                 test->settings->mss = atoi(optarg);
799                 if (test->settings->mss > MAX_MSS) {
800                     i_errno = IEMSS;
801                     return -1;
802                 }
803 		client_flag = 1;
804                 break;
805             case 'N':
806                 test->no_delay = 1;
807 		client_flag = 1;
808                 break;
809             case '4':
810                 test->settings->domain = AF_INET;
811                 break;
812             case '6':
813                 test->settings->domain = AF_INET6;
814                 break;
815             case 'S':
816                 test->settings->tos = strtol(optarg, NULL, 0);
817 		client_flag = 1;
818                 break;
819             case 'L':
820 #if defined(HAVE_FLOWLABEL)
821                 test->settings->flowlabel = strtol(optarg, NULL, 0);
822 		if (test->settings->flowlabel < 1 || test->settings->flowlabel > 0xfffff) {
823                     i_errno = IESETFLOW;
824                     return -1;
825 		}
826 		client_flag = 1;
827 #else /* HAVE_FLOWLABEL */
828                 i_errno = IEUNIMP;
829                 return -1;
830 #endif /* HAVE_FLOWLABEL */
831                 break;
832             case 'X':
833 		xbe = (struct xbind_entry *)malloc(sizeof(struct xbind_entry));
834                 if (!xbe) {
835 		    i_errno = IESETSCTPBINDX;
836                     return -1;
837                 }
838 	        memset(xbe, 0, sizeof(*xbe));
839                 xbe->name = strdup(optarg);
840                 if (!xbe->name) {
841 		    i_errno = IESETSCTPBINDX;
842                     return -1;
843                 }
844 		TAILQ_INSERT_TAIL(&test->xbind_addrs, xbe, link);
845                 break;
846             case 'Z':
847                 if (!has_sendfile()) {
848                     i_errno = IENOSENDFILE;
849                     return -1;
850                 }
851                 test->zerocopy = 1;
852 		client_flag = 1;
853                 break;
854             case 'O':
855                 test->omit = atoi(optarg);
856                 if (test->omit < 0 || test->omit > 60) {
857                     i_errno = IEOMIT;
858                     return -1;
859                 }
860 		client_flag = 1;
861                 break;
862             case 'F':
863                 test->diskfile_name = optarg;
864                 break;
865             case 'A':
866 #if defined(HAVE_CPU_AFFINITY)
867                 test->affinity = atoi(optarg);
868                 if (test->affinity < 0 || test->affinity > 1024) {
869                     i_errno = IEAFFINITY;
870                     return -1;
871                 }
872 		comma = strchr(optarg, ',');
873 		if (comma != NULL) {
874 		    test->server_affinity = atoi(comma+1);
875 		    if (test->server_affinity < 0 || test->server_affinity > 1024) {
876 			i_errno = IEAFFINITY;
877 			return -1;
878 		    }
879 		    client_flag = 1;
880 		}
881 #else /* HAVE_CPU_AFFINITY */
882                 i_errno = IEUNIMP;
883                 return -1;
884 #endif /* HAVE_CPU_AFFINITY */
885                 break;
886             case 'T':
887                 test->title = strdup(optarg);
888 		client_flag = 1;
889                 break;
890 	    case 'C':
891 #if defined(HAVE_TCP_CONGESTION)
892 		test->congestion = strdup(optarg);
893 		client_flag = 1;
894 #else /* HAVE_TCP_CONGESTION */
895 		i_errno = IEUNIMP;
896 		return -1;
897 #endif /* HAVE_TCP_CONGESTION */
898 		break;
899 	    case 'd':
900 		test->debug = 1;
901 		break;
902 	    case 'I':
903 		test->pidfile = strdup(optarg);
904 		server_flag = 1;
905 	        break;
906 	    case OPT_LOGFILE:
907 		test->logfile = strdup(optarg);
908 		break;
909 	    case OPT_GET_SERVER_OUTPUT:
910 		test->get_server_output = 1;
911 		client_flag = 1;
912 		break;
913 	    case OPT_UDP_COUNTERS_64BIT:
914 		test->udp_counters_64bit = 1;
915 		break;
916             case 'h':
917             default:
918                 usage_long();
919                 exit(1);
920         }
921     }
922 
923     /* Set logging to a file if specified, otherwise use the default (stdout) */
924     if (test->logfile) {
925 	test->outfile = fopen(test->logfile, "a+");
926 	if (test->outfile == NULL) {
927 	    i_errno = IELOGFILE;
928 	    return -1;
929 	}
930     }
931 
932     /* Check flag / role compatibility. */
933     if (test->role == 'c' && server_flag) {
934 	i_errno = IESERVERONLY;
935 	return -1;
936     }
937     if (test->role == 's' && client_flag) {
938 	i_errno = IECLIENTONLY;
939 	return -1;
940     }
941 
942     if (!test->bind_address && test->bind_port) {
943         i_errno = IEBIND;
944         return -1;
945     }
946     if (blksize == 0) {
947 	if (test->protocol->id == Pudp)
948 	    blksize = DEFAULT_UDP_BLKSIZE;
949 	else if (test->protocol->id == Psctp)
950 	    blksize = DEFAULT_SCTP_BLKSIZE;
951 	else
952 	    blksize = DEFAULT_TCP_BLKSIZE;
953     }
954     if (blksize <= 0 || blksize > MAX_BLOCKSIZE) {
955 	i_errno = IEBLOCKSIZE;
956 	return -1;
957     }
958     if (test->protocol->id == Pudp &&
959 	blksize > MAX_UDP_BLOCKSIZE) {
960 	i_errno = IEUDPBLOCKSIZE;
961 	return -1;
962     }
963     test->settings->blksize = blksize;
964 
965     if (!rate_flag)
966 	test->settings->rate = test->protocol->id == Pudp ? UDP_RATE : 0;
967 
968     if ((test->settings->bytes != 0 || test->settings->blocks != 0) && ! duration_flag)
969         test->duration = 0;
970 
971     /* Disallow specifying multiple test end conditions. The code actually
972     ** works just fine without this prohibition. As soon as any one of the
973     ** three possible end conditions is met, the test ends. So this check
974     ** could be removed if desired.
975     */
976     if ((duration_flag && test->settings->bytes != 0) ||
977         (duration_flag && test->settings->blocks != 0) ||
978 	(test->settings->bytes != 0 && test->settings->blocks != 0)) {
979         i_errno = IEENDCONDITIONS;
980         return -1;
981     }
982 
983     /* For subsequent calls to getopt */
984 #ifdef __APPLE__
985     optreset = 1;
986 #endif
987     optind = 0;
988 
989     if ((test->role != 'c') && (test->role != 's')) {
990         i_errno = IENOROLE;
991         return -1;
992     }
993 
994     return 0;
995 }
996 
997 int
998 iperf_set_send_state(struct iperf_test *test, signed char state)
999 {
1000     test->state = state;
1001     if (Nwrite(test->ctrl_sck, (char*) &state, sizeof(state), Ptcp) < 0) {
1002 	i_errno = IESENDMESSAGE;
1003 	return -1;
1004     }
1005     return 0;
1006 }
1007 
1008 void
1009 iperf_check_throttle(struct iperf_stream *sp, struct timeval *nowP)
1010 {
1011     double seconds;
1012     uint64_t bits_per_second;
1013 
1014     if (sp->test->done)
1015         return;
1016     seconds = timeval_diff(&sp->result->start_time, nowP);
1017     bits_per_second = sp->result->bytes_sent * 8 / seconds;
1018     if (bits_per_second < sp->test->settings->rate) {
1019         sp->green_light = 1;
1020         FD_SET(sp->socket, &sp->test->write_set);
1021     } else {
1022         sp->green_light = 0;
1023         FD_CLR(sp->socket, &sp->test->write_set);
1024     }
1025 }
1026 
1027 int
1028 iperf_send(struct iperf_test *test, fd_set *write_setP)
1029 {
1030     register int multisend, r, streams_active;
1031     register struct iperf_stream *sp;
1032     struct timeval now;
1033 
1034     /* Can we do multisend mode? */
1035     if (test->settings->burst != 0)
1036         multisend = test->settings->burst;
1037     else if (test->settings->rate == 0)
1038         multisend = test->multisend;
1039     else
1040         multisend = 1;	/* nope */
1041 
1042     for (; multisend > 0; --multisend) {
1043 	if (test->settings->rate != 0 && test->settings->burst == 0)
1044 	    gettimeofday(&now, NULL);
1045 	streams_active = 0;
1046 	SLIST_FOREACH(sp, &test->streams, streams) {
1047 	    if (sp->green_light &&
1048 	        (write_setP == NULL || FD_ISSET(sp->socket, write_setP))) {
1049 		if ((r = sp->snd(sp)) < 0) {
1050 		    if (r == NET_SOFTERROR)
1051 			break;
1052 		    i_errno = IESTREAMWRITE;
1053 		    return r;
1054 		}
1055 		streams_active = 1;
1056 		test->bytes_sent += r;
1057 		++test->blocks_sent;
1058 		if (test->settings->rate != 0 && test->settings->burst == 0)
1059 		    iperf_check_throttle(sp, &now);
1060 		if (multisend > 1 && test->settings->bytes != 0 && test->bytes_sent >= test->settings->bytes)
1061 		    break;
1062 		if (multisend > 1 && test->settings->blocks != 0 && test->blocks_sent >= test->settings->blocks)
1063 		    break;
1064 	    }
1065 	}
1066 	if (!streams_active)
1067 	    break;
1068     }
1069     if (test->settings->burst != 0) {
1070 	gettimeofday(&now, NULL);
1071 	SLIST_FOREACH(sp, &test->streams, streams)
1072 	    iperf_check_throttle(sp, &now);
1073     }
1074     if (write_setP != NULL)
1075 	SLIST_FOREACH(sp, &test->streams, streams)
1076 	    if (FD_ISSET(sp->socket, write_setP))
1077 		FD_CLR(sp->socket, write_setP);
1078 
1079     return 0;
1080 }
1081 
1082 int
1083 iperf_recv(struct iperf_test *test, fd_set *read_setP)
1084 {
1085     int r;
1086     struct iperf_stream *sp;
1087 
1088     SLIST_FOREACH(sp, &test->streams, streams) {
1089 	if (FD_ISSET(sp->socket, read_setP)) {
1090 	    if ((r = sp->rcv(sp)) < 0) {
1091 		i_errno = IESTREAMREAD;
1092 		return r;
1093 	    }
1094 	    test->bytes_sent += r;
1095 	    ++test->blocks_sent;
1096 	    FD_CLR(sp->socket, read_setP);
1097 	}
1098     }
1099 
1100     return 0;
1101 }
1102 
1103 int
1104 iperf_init_test(struct iperf_test *test)
1105 {
1106     struct timeval now;
1107     struct iperf_stream *sp;
1108 
1109     if (test->protocol->init) {
1110         if (test->protocol->init(test) < 0)
1111             return -1;
1112     }
1113 
1114     /* Init each stream. */
1115     if (gettimeofday(&now, NULL) < 0) {
1116 	i_errno = IEINITTEST;
1117 	return -1;
1118     }
1119     SLIST_FOREACH(sp, &test->streams, streams) {
1120 	sp->result->start_time = now;
1121     }
1122 
1123     if (test->on_test_start)
1124         test->on_test_start(test);
1125 
1126     return 0;
1127 }
1128 
1129 static void
1130 send_timer_proc(TimerClientData client_data, struct timeval *nowP)
1131 {
1132     struct iperf_stream *sp = client_data.p;
1133 
1134     /* All we do here is set or clear the flag saying that this stream may
1135     ** be sent to.  The actual sending gets done in the send proc, after
1136     ** checking the flag.
1137     */
1138     iperf_check_throttle(sp, nowP);
1139 }
1140 
1141 int
1142 iperf_create_send_timers(struct iperf_test * test)
1143 {
1144     struct timeval now;
1145     struct iperf_stream *sp;
1146     TimerClientData cd;
1147 
1148     if (gettimeofday(&now, NULL) < 0) {
1149 	i_errno = IEINITTEST;
1150 	return -1;
1151     }
1152     SLIST_FOREACH(sp, &test->streams, streams) {
1153         sp->green_light = 1;
1154 	if (test->settings->rate != 0) {
1155 	    cd.p = sp;
1156 	    sp->send_timer = tmr_create((struct timeval*) 0, send_timer_proc, cd, 100000L, 1);
1157 	    /* (Repeat every tenth second - arbitrary often value.) */
1158 	    if (sp->send_timer == NULL) {
1159 		i_errno = IEINITTEST;
1160 		return -1;
1161 	    }
1162 	}
1163     }
1164     return 0;
1165 }
1166 
1167 /**
1168  * iperf_exchange_parameters - handles the param_Exchange part for client
1169  *
1170  */
1171 
1172 int
1173 iperf_exchange_parameters(struct iperf_test *test)
1174 {
1175     int s;
1176     int32_t err;
1177 
1178     if (test->role == 'c') {
1179 
1180         if (send_parameters(test) < 0)
1181             return -1;
1182 
1183     } else {
1184 
1185         if (get_parameters(test) < 0)
1186             return -1;
1187 
1188         if ((s = test->protocol->listen(test)) < 0) {
1189 	    if (iperf_set_send_state(test, SERVER_ERROR) != 0)
1190                 return -1;
1191             err = htonl(i_errno);
1192             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
1193                 i_errno = IECTRLWRITE;
1194                 return -1;
1195             }
1196             err = htonl(errno);
1197             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
1198                 i_errno = IECTRLWRITE;
1199                 return -1;
1200             }
1201             return -1;
1202         }
1203         FD_SET(s, &test->read_set);
1204         test->max_fd = (s > test->max_fd) ? s : test->max_fd;
1205         test->prot_listener = s;
1206 
1207         // Send the control message to create streams and start the test
1208 	if (iperf_set_send_state(test, CREATE_STREAMS) != 0)
1209             return -1;
1210 
1211     }
1212 
1213     return 0;
1214 }
1215 
1216 /*************************************************************/
1217 
1218 int
1219 iperf_exchange_results(struct iperf_test *test)
1220 {
1221     if (test->role == 'c') {
1222         /* Send results to server. */
1223 	if (send_results(test) < 0)
1224             return -1;
1225         /* Get server results. */
1226         if (get_results(test) < 0)
1227             return -1;
1228     } else {
1229         /* Get client results. */
1230         if (get_results(test) < 0)
1231             return -1;
1232         /* Send results to client. */
1233 	if (send_results(test) < 0)
1234             return -1;
1235     }
1236     return 0;
1237 }
1238 
1239 /*************************************************************/
1240 
1241 static int
1242 send_parameters(struct iperf_test *test)
1243 {
1244     int r = 0;
1245     cJSON *j;
1246 
1247     j = cJSON_CreateObject();
1248     if (j == NULL) {
1249 	i_errno = IESENDPARAMS;
1250 	r = -1;
1251     } else {
1252 	if (test->protocol->id == Ptcp)
1253 	    cJSON_AddTrueToObject(j, "tcp");
1254 	else if (test->protocol->id == Pudp)
1255 	    cJSON_AddTrueToObject(j, "udp");
1256         else if (test->protocol->id == Psctp)
1257             cJSON_AddTrueToObject(j, "sctp");
1258 	cJSON_AddIntToObject(j, "omit", test->omit);
1259 	if (test->server_affinity != -1)
1260 	    cJSON_AddIntToObject(j, "server_affinity", test->server_affinity);
1261 	if (test->duration)
1262 	    cJSON_AddIntToObject(j, "time", test->duration);
1263 	if (test->settings->bytes)
1264 	    cJSON_AddIntToObject(j, "num", test->settings->bytes);
1265 	if (test->settings->blocks)
1266 	    cJSON_AddIntToObject(j, "blockcount", test->settings->blocks);
1267 	if (test->settings->mss)
1268 	    cJSON_AddIntToObject(j, "MSS", test->settings->mss);
1269 	if (test->no_delay)
1270 	    cJSON_AddTrueToObject(j, "nodelay");
1271 	cJSON_AddIntToObject(j, "parallel", test->num_streams);
1272 	if (test->reverse)
1273 	    cJSON_AddTrueToObject(j, "reverse");
1274 	if (test->settings->socket_bufsize)
1275 	    cJSON_AddIntToObject(j, "window", test->settings->socket_bufsize);
1276 	if (test->settings->blksize)
1277 	    cJSON_AddIntToObject(j, "len", test->settings->blksize);
1278 	if (test->settings->rate)
1279 	    cJSON_AddIntToObject(j, "bandwidth", test->settings->rate);
1280 	if (test->settings->burst)
1281 	    cJSON_AddIntToObject(j, "burst", test->settings->burst);
1282 	if (test->settings->tos)
1283 	    cJSON_AddIntToObject(j, "TOS", test->settings->tos);
1284 	if (test->settings->flowlabel)
1285 	    cJSON_AddIntToObject(j, "flowlabel", test->settings->flowlabel);
1286 	if (test->title)
1287 	    cJSON_AddStringToObject(j, "title", test->title);
1288 	if (test->congestion)
1289 	    cJSON_AddStringToObject(j, "congestion", test->congestion);
1290 	if (test->get_server_output)
1291 	    cJSON_AddIntToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
1292 	if (test->udp_counters_64bit)
1293 	    cJSON_AddIntToObject(j, "udp_counters_64bit", iperf_get_test_udp_counters_64bit(test));
1294 
1295 	cJSON_AddStringToObject(j, "client_version", IPERF_VERSION);
1296 
1297 	if (test->debug) {
1298 	    printf("send_parameters:\n%s\n", cJSON_Print(j));
1299 	}
1300 
1301 	if (JSON_write(test->ctrl_sck, j) < 0) {
1302 	    i_errno = IESENDPARAMS;
1303 	    r = -1;
1304 	}
1305 	cJSON_Delete(j);
1306     }
1307     return r;
1308 }
1309 
1310 /*************************************************************/
1311 
1312 static int
1313 get_parameters(struct iperf_test *test)
1314 {
1315     int r = 0;
1316     cJSON *j;
1317     cJSON *j_p;
1318 
1319     j = JSON_read(test->ctrl_sck);
1320     if (j == NULL) {
1321 	i_errno = IERECVPARAMS;
1322         r = -1;
1323     } else {
1324 	if (test->debug) {
1325 	    printf("get_parameters:\n%s\n", cJSON_Print(j));
1326 	}
1327 
1328 	if ((j_p = cJSON_GetObjectItem(j, "tcp")) != NULL)
1329 	    set_protocol(test, Ptcp);
1330 	if ((j_p = cJSON_GetObjectItem(j, "udp")) != NULL)
1331 	    set_protocol(test, Pudp);
1332         if ((j_p = cJSON_GetObjectItem(j, "sctp")) != NULL)
1333             set_protocol(test, Psctp);
1334 	if ((j_p = cJSON_GetObjectItem(j, "omit")) != NULL)
1335 	    test->omit = j_p->valueint;
1336 	if ((j_p = cJSON_GetObjectItem(j, "server_affinity")) != NULL)
1337 	    test->server_affinity = j_p->valueint;
1338 	if ((j_p = cJSON_GetObjectItem(j, "time")) != NULL)
1339 	    test->duration = j_p->valueint;
1340 	if ((j_p = cJSON_GetObjectItem(j, "num")) != NULL)
1341 	    test->settings->bytes = j_p->valueint;
1342 	if ((j_p = cJSON_GetObjectItem(j, "blockcount")) != NULL)
1343 	    test->settings->blocks = j_p->valueint;
1344 	if ((j_p = cJSON_GetObjectItem(j, "MSS")) != NULL)
1345 	    test->settings->mss = j_p->valueint;
1346 	if ((j_p = cJSON_GetObjectItem(j, "nodelay")) != NULL)
1347 	    test->no_delay = 1;
1348 	if ((j_p = cJSON_GetObjectItem(j, "parallel")) != NULL)
1349 	    test->num_streams = j_p->valueint;
1350 	if ((j_p = cJSON_GetObjectItem(j, "reverse")) != NULL)
1351 	    iperf_set_test_reverse(test, 1);
1352 	if ((j_p = cJSON_GetObjectItem(j, "window")) != NULL)
1353 	    test->settings->socket_bufsize = j_p->valueint;
1354 	if ((j_p = cJSON_GetObjectItem(j, "len")) != NULL)
1355 	    test->settings->blksize = j_p->valueint;
1356 	if ((j_p = cJSON_GetObjectItem(j, "bandwidth")) != NULL)
1357 	    test->settings->rate = j_p->valueint;
1358 	if ((j_p = cJSON_GetObjectItem(j, "burst")) != NULL)
1359 	    test->settings->burst = j_p->valueint;
1360 	if ((j_p = cJSON_GetObjectItem(j, "TOS")) != NULL)
1361 	    test->settings->tos = j_p->valueint;
1362 	if ((j_p = cJSON_GetObjectItem(j, "flowlabel")) != NULL)
1363 	    test->settings->flowlabel = j_p->valueint;
1364 	if ((j_p = cJSON_GetObjectItem(j, "title")) != NULL)
1365 	    test->title = strdup(j_p->valuestring);
1366 	if ((j_p = cJSON_GetObjectItem(j, "congestion")) != NULL)
1367 	    test->congestion = strdup(j_p->valuestring);
1368 	if ((j_p = cJSON_GetObjectItem(j, "get_server_output")) != NULL)
1369 	    iperf_set_test_get_server_output(test, 1);
1370 	if ((j_p = cJSON_GetObjectItem(j, "udp_counters_64bit")) != NULL)
1371 	    iperf_set_test_udp_counters_64bit(test, 1);
1372 	if (test->sender && test->protocol->id == Ptcp && has_tcpinfo_retransmits())
1373 	    test->sender_has_retransmits = 1;
1374 	cJSON_Delete(j);
1375     }
1376     return r;
1377 }
1378 
1379 /*************************************************************/
1380 
1381 static int
1382 send_results(struct iperf_test *test)
1383 {
1384     int r = 0;
1385     cJSON *j;
1386     cJSON *j_streams;
1387     struct iperf_stream *sp;
1388     cJSON *j_stream;
1389     int sender_has_retransmits;
1390     iperf_size_t bytes_transferred;
1391     int retransmits;
1392 
1393     j = cJSON_CreateObject();
1394     if (j == NULL) {
1395 	i_errno = IEPACKAGERESULTS;
1396 	r = -1;
1397     } else {
1398 	cJSON_AddFloatToObject(j, "cpu_util_total", test->cpu_util[0]);
1399 	cJSON_AddFloatToObject(j, "cpu_util_user", test->cpu_util[1]);
1400 	cJSON_AddFloatToObject(j, "cpu_util_system", test->cpu_util[2]);
1401 	if ( ! test->sender )
1402 	    sender_has_retransmits = -1;
1403 	else
1404 	    sender_has_retransmits = test->sender_has_retransmits;
1405 	cJSON_AddIntToObject(j, "sender_has_retransmits", sender_has_retransmits);
1406 
1407 	/* If on the server and sending server output, then do this */
1408 	if (test->role == 's' && test->get_server_output) {
1409 	    if (test->json_output) {
1410 		/* Add JSON output */
1411 		cJSON_AddItemReferenceToObject(j, "server_output_json", test->json_top);
1412 	    }
1413 	    else {
1414 		/* Add textual output */
1415 		size_t buflen = 0;
1416 
1417 		/* Figure out how much room we need to hold the complete output string */
1418 		struct iperf_textline *t;
1419 		TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
1420 		    buflen += strlen(t->line);
1421 		}
1422 
1423 		/* Allocate and build it up from the component lines */
1424 		char *output = calloc(buflen + 1, 1);
1425 		TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
1426 		    strncat(output, t->line, buflen);
1427 		    buflen -= strlen(t->line);
1428 		}
1429 
1430 		cJSON_AddStringToObject(j, "server_output_text", output);
1431 	    }
1432 	}
1433 
1434 	j_streams = cJSON_CreateArray();
1435 	if (j_streams == NULL) {
1436 	    i_errno = IEPACKAGERESULTS;
1437 	    r = -1;
1438 	} else {
1439 	    cJSON_AddItemToObject(j, "streams", j_streams);
1440 	    SLIST_FOREACH(sp, &test->streams, streams) {
1441 		j_stream = cJSON_CreateObject();
1442 		if (j_stream == NULL) {
1443 		    i_errno = IEPACKAGERESULTS;
1444 		    r = -1;
1445 		} else {
1446 		    cJSON_AddItemToArray(j_streams, j_stream);
1447 		    bytes_transferred = test->sender ? sp->result->bytes_sent : sp->result->bytes_received;
1448 		    retransmits = (test->sender && test->sender_has_retransmits) ? sp->result->stream_retrans : -1;
1449 		    cJSON_AddIntToObject(j_stream, "id", sp->id);
1450 		    cJSON_AddIntToObject(j_stream, "bytes", bytes_transferred);
1451 		    cJSON_AddIntToObject(j_stream, "retransmits", retransmits);
1452 		    cJSON_AddFloatToObject(j_stream, "jitter", sp->jitter);
1453 		    cJSON_AddIntToObject(j_stream, "errors", sp->cnt_error);
1454 		    cJSON_AddIntToObject(j_stream, "packets", sp->packet_count);
1455 		}
1456 	    }
1457 	    if (r == 0 && test->debug) {
1458 		printf("send_results\n%s\n", cJSON_Print(j));
1459 	    }
1460 	    if (r == 0 && JSON_write(test->ctrl_sck, j) < 0) {
1461 		i_errno = IESENDRESULTS;
1462 		r = -1;
1463 	    }
1464 	}
1465 	cJSON_Delete(j);
1466     }
1467     return r;
1468 }
1469 
1470 /*************************************************************/
1471 
1472 static int
1473 get_results(struct iperf_test *test)
1474 {
1475     int r = 0;
1476     cJSON *j;
1477     cJSON *j_cpu_util_total;
1478     cJSON *j_cpu_util_user;
1479     cJSON *j_cpu_util_system;
1480     cJSON *j_sender_has_retransmits;
1481     int result_has_retransmits;
1482     cJSON *j_streams;
1483     int n, i;
1484     cJSON *j_stream;
1485     cJSON *j_id;
1486     cJSON *j_bytes;
1487     cJSON *j_retransmits;
1488     cJSON *j_jitter;
1489     cJSON *j_errors;
1490     cJSON *j_packets;
1491     cJSON *j_server_output;
1492     int sid, cerror, pcount;
1493     double jitter;
1494     iperf_size_t bytes_transferred;
1495     int retransmits;
1496     struct iperf_stream *sp;
1497 
1498     j = JSON_read(test->ctrl_sck);
1499     if (j == NULL) {
1500 	i_errno = IERECVRESULTS;
1501         r = -1;
1502     } else {
1503 	j_cpu_util_total = cJSON_GetObjectItem(j, "cpu_util_total");
1504 	j_cpu_util_user = cJSON_GetObjectItem(j, "cpu_util_user");
1505 	j_cpu_util_system = cJSON_GetObjectItem(j, "cpu_util_system");
1506 	j_sender_has_retransmits = cJSON_GetObjectItem(j, "sender_has_retransmits");
1507 	if (j_cpu_util_total == NULL || j_cpu_util_user == NULL || j_cpu_util_system == NULL || j_sender_has_retransmits == NULL) {
1508 	    i_errno = IERECVRESULTS;
1509 	    r = -1;
1510 	} else {
1511 	    if (test->debug) {
1512 		printf("get_results\n%s\n", cJSON_Print(j));
1513 	    }
1514 
1515 	    test->remote_cpu_util[0] = j_cpu_util_total->valuefloat;
1516 	    test->remote_cpu_util[1] = j_cpu_util_user->valuefloat;
1517 	    test->remote_cpu_util[2] = j_cpu_util_system->valuefloat;
1518 	    result_has_retransmits = j_sender_has_retransmits->valueint;
1519 	    if (! test->sender)
1520 		test->sender_has_retransmits = result_has_retransmits;
1521 	    j_streams = cJSON_GetObjectItem(j, "streams");
1522 	    if (j_streams == NULL) {
1523 		i_errno = IERECVRESULTS;
1524 		r = -1;
1525 	    } else {
1526 	        n = cJSON_GetArraySize(j_streams);
1527 		for (i=0; i<n; ++i) {
1528 		    j_stream = cJSON_GetArrayItem(j_streams, i);
1529 		    if (j_stream == NULL) {
1530 			i_errno = IERECVRESULTS;
1531 			r = -1;
1532 		    } else {
1533 			j_id = cJSON_GetObjectItem(j_stream, "id");
1534 			j_bytes = cJSON_GetObjectItem(j_stream, "bytes");
1535 			j_retransmits = cJSON_GetObjectItem(j_stream, "retransmits");
1536 			j_jitter = cJSON_GetObjectItem(j_stream, "jitter");
1537 			j_errors = cJSON_GetObjectItem(j_stream, "errors");
1538 			j_packets = cJSON_GetObjectItem(j_stream, "packets");
1539 			if (j_id == NULL || j_bytes == NULL || j_retransmits == NULL || j_jitter == NULL || j_errors == NULL || j_packets == NULL) {
1540 			    i_errno = IERECVRESULTS;
1541 			    r = -1;
1542 			} else {
1543 			    sid = j_id->valueint;
1544 			    bytes_transferred = j_bytes->valueint;
1545 			    retransmits = j_retransmits->valueint;
1546 			    jitter = j_jitter->valuefloat;
1547 			    cerror = j_errors->valueint;
1548 			    pcount = j_packets->valueint;
1549 			    SLIST_FOREACH(sp, &test->streams, streams)
1550 				if (sp->id == sid) break;
1551 			    if (sp == NULL) {
1552 				i_errno = IESTREAMID;
1553 				r = -1;
1554 			    } else {
1555 				if (test->sender) {
1556 				    sp->jitter = jitter;
1557 				    sp->cnt_error = cerror;
1558 				    sp->packet_count = pcount;
1559 				    sp->result->bytes_received = bytes_transferred;
1560 				} else {
1561 				    sp->result->bytes_sent = bytes_transferred;
1562 				    sp->result->stream_retrans = retransmits;
1563 				}
1564 			    }
1565 			}
1566 		    }
1567 		}
1568 		/*
1569 		 * If we're the client and we're supposed to get remote results,
1570 		 * look them up and process accordingly.
1571 		 */
1572 		if (test->role == 'c' && iperf_get_test_get_server_output(test)) {
1573 		    /* Look for JSON.  If we find it, grab the object so it doesn't get deleted. */
1574 		    j_server_output = cJSON_DetachItemFromObject(j, "server_output_json");
1575 		    if (j_server_output != NULL) {
1576 			test->json_server_output = j_server_output;
1577 		    }
1578 		    else {
1579 			/* No JSON, look for textual output.  Make a copy of the text for later. */
1580 			j_server_output = cJSON_GetObjectItem(j, "server_output_text");
1581 			if (j_server_output != NULL) {
1582 			    test->server_output_text = strdup(j_server_output->valuestring);
1583 			}
1584 		    }
1585 		}
1586 	    }
1587 	}
1588 	cJSON_Delete(j);
1589     }
1590     return r;
1591 }
1592 
1593 /*************************************************************/
1594 
1595 static int
1596 JSON_write(int fd, cJSON *json)
1597 {
1598     uint32_t hsize, nsize;
1599     char *str;
1600     int r = 0;
1601 
1602     str = cJSON_PrintUnformatted(json);
1603     if (str == NULL)
1604 	r = -1;
1605     else {
1606 	hsize = strlen(str);
1607 	nsize = htonl(hsize);
1608 	if (Nwrite(fd, (char*) &nsize, sizeof(nsize), Ptcp) < 0)
1609 	    r = -1;
1610 	else {
1611 	    if (Nwrite(fd, str, hsize, Ptcp) < 0)
1612 		r = -1;
1613 	}
1614 	free(str);
1615     }
1616     return r;
1617 }
1618 
1619 /*************************************************************/
1620 
1621 static cJSON *
1622 JSON_read(int fd)
1623 {
1624     uint32_t hsize, nsize;
1625     char *str;
1626     cJSON *json = NULL;
1627 
1628     if (Nread(fd, (char*) &nsize, sizeof(nsize), Ptcp) >= 0) {
1629 	hsize = ntohl(nsize);
1630 	str = (char *) malloc(hsize+1);	/* +1 for EOS */
1631 	if (str != NULL) {
1632 	    if (Nread(fd, str, hsize, Ptcp) >= 0) {
1633 		str[hsize] = '\0';	/* add the EOS */
1634 		json = cJSON_Parse(str);
1635 	    }
1636 	}
1637 	free(str);
1638     }
1639     return json;
1640 }
1641 
1642 /*************************************************************/
1643 /**
1644  * add_to_interval_list -- adds new interval to the interval_list
1645  */
1646 
1647 void
1648 add_to_interval_list(struct iperf_stream_result * rp, struct iperf_interval_results * new)
1649 {
1650     struct iperf_interval_results *irp;
1651 
1652     irp = (struct iperf_interval_results *) malloc(sizeof(struct iperf_interval_results));
1653     memcpy(irp, new, sizeof(struct iperf_interval_results));
1654     TAILQ_INSERT_TAIL(&rp->interval_results, irp, irlistentries);
1655 }
1656 
1657 
1658 /************************************************************/
1659 
1660 /**
1661  * connect_msg -- displays connection message
1662  * denoting sender/receiver details
1663  *
1664  */
1665 
1666 void
1667 connect_msg(struct iperf_stream *sp)
1668 {
1669     char ipl[INET6_ADDRSTRLEN], ipr[INET6_ADDRSTRLEN];
1670     int lport, rport;
1671 
1672     if (getsockdomain(sp->socket) == AF_INET) {
1673         inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->local_addr)->sin_addr, ipl, sizeof(ipl));
1674 	mapped_v4_to_regular_v4(ipl);
1675         inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->remote_addr)->sin_addr, ipr, sizeof(ipr));
1676 	mapped_v4_to_regular_v4(ipr);
1677         lport = ntohs(((struct sockaddr_in *) &sp->local_addr)->sin_port);
1678         rport = ntohs(((struct sockaddr_in *) &sp->remote_addr)->sin_port);
1679     } else {
1680         inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->local_addr)->sin6_addr, ipl, sizeof(ipl));
1681 	mapped_v4_to_regular_v4(ipl);
1682         inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->remote_addr)->sin6_addr, ipr, sizeof(ipr));
1683 	mapped_v4_to_regular_v4(ipr);
1684         lport = ntohs(((struct sockaddr_in6 *) &sp->local_addr)->sin6_port);
1685         rport = ntohs(((struct sockaddr_in6 *) &sp->remote_addr)->sin6_port);
1686     }
1687 
1688     if (sp->test->json_output)
1689         cJSON_AddItemToArray(sp->test->json_connected, iperf_json_printf("socket: %d  local_host: %s  local_port: %d  remote_host: %s  remote_port: %d", (int64_t) sp->socket, ipl, (int64_t) lport, ipr, (int64_t) rport));
1690     else
1691 	iprintf(sp->test, report_connected, sp->socket, ipl, lport, ipr, rport);
1692 }
1693 
1694 
1695 /**************************************************************************/
1696 
1697 struct iperf_test *
1698 iperf_new_test()
1699 {
1700     struct iperf_test *test;
1701 
1702     test = (struct iperf_test *) malloc(sizeof(struct iperf_test));
1703     if (!test) {
1704         i_errno = IENEWTEST;
1705         return NULL;
1706     }
1707     /* initialize everything to zero */
1708     memset(test, 0, sizeof(struct iperf_test));
1709 
1710     test->settings = (struct iperf_settings *) malloc(sizeof(struct iperf_settings));
1711     if (!test->settings) {
1712         free(test);
1713 	i_errno = IENEWTEST;
1714 	return NULL;
1715     }
1716     memset(test->settings, 0, sizeof(struct iperf_settings));
1717 
1718     /* By default all output goes to stdout */
1719     test->outfile = stdout;
1720 
1721     return test;
1722 }
1723 
1724 /**************************************************************************/
1725 
1726 struct protocol *
1727 protocol_new(void)
1728 {
1729     struct protocol *proto;
1730 
1731     proto = malloc(sizeof(struct protocol));
1732     if(!proto) {
1733         return NULL;
1734     }
1735     memset(proto, 0, sizeof(struct protocol));
1736 
1737     return proto;
1738 }
1739 
1740 void
1741 protocol_free(struct protocol *proto)
1742 {
1743     free(proto);
1744 }
1745 
1746 /**************************************************************************/
1747 int
1748 iperf_defaults(struct iperf_test *testp)
1749 {
1750     struct protocol *tcp, *udp;
1751 #if defined(HAVE_SCTP)
1752     struct protocol *sctp;
1753 #endif /* HAVE_SCTP */
1754 
1755     testp->omit = OMIT;
1756     testp->duration = DURATION;
1757     testp->diskfile_name = (char*) 0;
1758     testp->affinity = -1;
1759     testp->server_affinity = -1;
1760     TAILQ_INIT(&testp->xbind_addrs);
1761 #if defined(HAVE_CPUSET_SETAFFINITY)
1762     CPU_ZERO(&testp->cpumask);
1763 #endif /* HAVE_CPUSET_SETAFFINITY */
1764     testp->title = NULL;
1765     testp->congestion = NULL;
1766     testp->server_port = PORT;
1767     testp->ctrl_sck = -1;
1768     testp->prot_listener = -1;
1769 
1770     testp->stats_callback = iperf_stats_callback;
1771     testp->reporter_callback = iperf_reporter_callback;
1772 
1773     testp->stats_interval = testp->reporter_interval = 1;
1774     testp->num_streams = 1;
1775 
1776     testp->settings->domain = AF_UNSPEC;
1777     testp->settings->unit_format = 'a';
1778     testp->settings->socket_bufsize = 0;    /* use autotuning */
1779     testp->settings->blksize = DEFAULT_TCP_BLKSIZE;
1780     testp->settings->rate = 0;
1781     testp->settings->burst = 0;
1782     testp->settings->mss = 0;
1783     testp->settings->bytes = 0;
1784     testp->settings->blocks = 0;
1785     memset(testp->cookie, 0, COOKIE_SIZE);
1786 
1787     testp->multisend = 10;	/* arbitrary */
1788 
1789     /* Set up protocol list */
1790     SLIST_INIT(&testp->streams);
1791     SLIST_INIT(&testp->protocols);
1792 
1793     tcp = protocol_new();
1794     if (!tcp)
1795         return -1;
1796 
1797     tcp->id = Ptcp;
1798     tcp->name = "TCP";
1799     tcp->accept = iperf_tcp_accept;
1800     tcp->listen = iperf_tcp_listen;
1801     tcp->connect = iperf_tcp_connect;
1802     tcp->send = iperf_tcp_send;
1803     tcp->recv = iperf_tcp_recv;
1804     tcp->init = NULL;
1805     SLIST_INSERT_HEAD(&testp->protocols, tcp, protocols);
1806 
1807     udp = protocol_new();
1808     if (!udp) {
1809         protocol_free(tcp);
1810         return -1;
1811     }
1812 
1813     udp->id = Pudp;
1814     udp->name = "UDP";
1815     udp->accept = iperf_udp_accept;
1816     udp->listen = iperf_udp_listen;
1817     udp->connect = iperf_udp_connect;
1818     udp->send = iperf_udp_send;
1819     udp->recv = iperf_udp_recv;
1820     udp->init = iperf_udp_init;
1821     SLIST_INSERT_AFTER(tcp, udp, protocols);
1822 
1823     set_protocol(testp, Ptcp);
1824 
1825 #if defined(HAVE_SCTP)
1826     sctp = protocol_new();
1827     if (!sctp) {
1828         protocol_free(tcp);
1829         protocol_free(udp);
1830         return -1;
1831     }
1832 
1833     sctp->id = Psctp;
1834     sctp->name = "SCTP";
1835     sctp->accept = iperf_sctp_accept;
1836     sctp->listen = iperf_sctp_listen;
1837     sctp->connect = iperf_sctp_connect;
1838     sctp->send = iperf_sctp_send;
1839     sctp->recv = iperf_sctp_recv;
1840     sctp->init = iperf_sctp_init;
1841 
1842     SLIST_INSERT_AFTER(udp, sctp, protocols);
1843 #endif /* HAVE_SCTP */
1844 
1845     testp->on_new_stream = iperf_on_new_stream;
1846     testp->on_test_start = iperf_on_test_start;
1847     testp->on_connect = iperf_on_connect;
1848     testp->on_test_finish = iperf_on_test_finish;
1849 
1850     TAILQ_INIT(&testp->server_output_list);
1851 
1852     return 0;
1853 }
1854 
1855 
1856 /**************************************************************************/
1857 void
1858 iperf_free_test(struct iperf_test *test)
1859 {
1860     struct protocol *prot;
1861     struct iperf_stream *sp;
1862 
1863     /* Free streams */
1864     while (!SLIST_EMPTY(&test->streams)) {
1865         sp = SLIST_FIRST(&test->streams);
1866         SLIST_REMOVE_HEAD(&test->streams, streams);
1867         iperf_free_stream(sp);
1868     }
1869 
1870     if (test->server_hostname)
1871 	free(test->server_hostname);
1872     if (test->bind_address)
1873 	free(test->bind_address);
1874     if (!TAILQ_EMPTY(&test->xbind_addrs)) {
1875         struct xbind_entry *xbe;
1876 
1877         while (!TAILQ_EMPTY(&test->xbind_addrs)) {
1878             xbe = TAILQ_FIRST(&test->xbind_addrs);
1879             TAILQ_REMOVE(&test->xbind_addrs, xbe, link);
1880             if (xbe->ai)
1881                 freeaddrinfo(xbe->ai);
1882             free(xbe->name);
1883             free(xbe);
1884         }
1885     }
1886     free(test->settings);
1887     if (test->title)
1888 	free(test->title);
1889     if (test->congestion)
1890 	free(test->congestion);
1891     if (test->omit_timer != NULL)
1892 	tmr_cancel(test->omit_timer);
1893     if (test->timer != NULL)
1894 	tmr_cancel(test->timer);
1895     if (test->stats_timer != NULL)
1896 	tmr_cancel(test->stats_timer);
1897     if (test->reporter_timer != NULL)
1898 	tmr_cancel(test->reporter_timer);
1899 
1900     /* Free protocol list */
1901     while (!SLIST_EMPTY(&test->protocols)) {
1902         prot = SLIST_FIRST(&test->protocols);
1903         SLIST_REMOVE_HEAD(&test->protocols, protocols);
1904         free(prot);
1905     }
1906 
1907     if (test->server_output_text) {
1908 	free(test->server_output_text);
1909 	test->server_output_text = NULL;
1910     }
1911 
1912     if (test->json_output_string) {
1913 	free(test->json_output_string);
1914 	test->json_output_string = NULL;
1915     }
1916 
1917     /* Free output line buffers, if any (on the server only) */
1918     struct iperf_textline *t;
1919     while (!TAILQ_EMPTY(&test->server_output_list)) {
1920 	t = TAILQ_FIRST(&test->server_output_list);
1921 	TAILQ_REMOVE(&test->server_output_list, t, textlineentries);
1922 	free(t->line);
1923 	free(t);
1924     }
1925 
1926     /* sctp_bindx: do not free the arguments, only the resolver results */
1927     if (!TAILQ_EMPTY(&test->xbind_addrs)) {
1928         struct xbind_entry *xbe;
1929 
1930         TAILQ_FOREACH(xbe, &test->xbind_addrs, link) {
1931             if (xbe->ai) {
1932                 freeaddrinfo(xbe->ai);
1933                 xbe->ai = NULL;
1934             }
1935         }
1936     }
1937 
1938     /* XXX: Why are we setting these values to NULL? */
1939     // test->streams = NULL;
1940     test->stats_callback = NULL;
1941     test->reporter_callback = NULL;
1942     free(test);
1943 }
1944 
1945 
1946 void
1947 iperf_reset_test(struct iperf_test *test)
1948 {
1949     struct iperf_stream *sp;
1950 
1951     /* Free streams */
1952     while (!SLIST_EMPTY(&test->streams)) {
1953         sp = SLIST_FIRST(&test->streams);
1954         SLIST_REMOVE_HEAD(&test->streams, streams);
1955         iperf_free_stream(sp);
1956     }
1957     if (test->omit_timer != NULL) {
1958 	tmr_cancel(test->omit_timer);
1959 	test->omit_timer = NULL;
1960     }
1961     if (test->timer != NULL) {
1962 	tmr_cancel(test->timer);
1963 	test->timer = NULL;
1964     }
1965     if (test->stats_timer != NULL) {
1966 	tmr_cancel(test->stats_timer);
1967 	test->stats_timer = NULL;
1968     }
1969     if (test->reporter_timer != NULL) {
1970 	tmr_cancel(test->reporter_timer);
1971 	test->reporter_timer = NULL;
1972     }
1973     test->done = 0;
1974 
1975     SLIST_INIT(&test->streams);
1976 
1977     test->role = 's';
1978     test->sender = 0;
1979     test->sender_has_retransmits = 0;
1980     set_protocol(test, Ptcp);
1981     test->omit = OMIT;
1982     test->duration = DURATION;
1983     test->server_affinity = -1;
1984 #if defined(HAVE_CPUSET_SETAFFINITY)
1985     CPU_ZERO(&test->cpumask);
1986 #endif /* HAVE_CPUSET_SETAFFINITY */
1987     test->state = 0;
1988 
1989     test->ctrl_sck = -1;
1990     test->prot_listener = -1;
1991 
1992     test->bytes_sent = 0;
1993     test->blocks_sent = 0;
1994 
1995     test->reverse = 0;
1996     test->no_delay = 0;
1997 
1998     FD_ZERO(&test->read_set);
1999     FD_ZERO(&test->write_set);
2000 
2001     test->num_streams = 1;
2002     test->settings->socket_bufsize = 0;
2003     test->settings->blksize = DEFAULT_TCP_BLKSIZE;
2004     test->settings->rate = 0;
2005     test->settings->burst = 0;
2006     test->settings->mss = 0;
2007     memset(test->cookie, 0, COOKIE_SIZE);
2008     test->multisend = 10;	/* arbitrary */
2009     test->udp_counters_64bit = 0;
2010 
2011     /* Free output line buffers, if any (on the server only) */
2012     struct iperf_textline *t;
2013     while (!TAILQ_EMPTY(&test->server_output_list)) {
2014 	t = TAILQ_FIRST(&test->server_output_list);
2015 	TAILQ_REMOVE(&test->server_output_list, t, textlineentries);
2016 	free(t->line);
2017 	free(t);
2018     }
2019 }
2020 
2021 
2022 /* Reset all of a test's stats back to zero.  Called when the omitting
2023 ** period is over.
2024 */
2025 void
2026 iperf_reset_stats(struct iperf_test *test)
2027 {
2028     struct timeval now;
2029     struct iperf_stream *sp;
2030     struct iperf_stream_result *rp;
2031 
2032     test->bytes_sent = 0;
2033     test->blocks_sent = 0;
2034     gettimeofday(&now, NULL);
2035     SLIST_FOREACH(sp, &test->streams, streams) {
2036 	sp->omitted_packet_count = sp->packet_count;
2037 	sp->jitter = 0;
2038 	sp->outoforder_packets = 0;
2039 	sp->cnt_error = 0;
2040 	rp = sp->result;
2041         rp->bytes_sent = rp->bytes_received = 0;
2042         rp->bytes_sent_this_interval = rp->bytes_received_this_interval = 0;
2043 	if (test->sender && test->sender_has_retransmits) {
2044 	    struct iperf_interval_results ir; /* temporary results structure */
2045 	    save_tcpinfo(sp, &ir);
2046 	    rp->stream_prev_total_retrans = get_total_retransmits(&ir);
2047 	}
2048 	rp->stream_retrans = 0;
2049 	rp->start_time = now;
2050     }
2051 }
2052 
2053 
2054 /**************************************************************************/
2055 
2056 /**
2057  * Gather statistics during a test.
2058  * This function works for both the client and server side.
2059  */
2060 void
2061 iperf_stats_callback(struct iperf_test *test)
2062 {
2063     struct iperf_stream *sp;
2064     struct iperf_stream_result *rp = NULL;
2065     struct iperf_interval_results *irp, temp;
2066 
2067     temp.omitted = test->omitting;
2068     SLIST_FOREACH(sp, &test->streams, streams) {
2069         rp = sp->result;
2070 
2071 	temp.bytes_transferred = test->sender ? rp->bytes_sent_this_interval : rp->bytes_received_this_interval;
2072 
2073 	irp = TAILQ_LAST(&rp->interval_results, irlisthead);
2074         /* result->end_time contains timestamp of previous interval */
2075         if ( irp != NULL ) /* not the 1st interval */
2076             memcpy(&temp.interval_start_time, &rp->end_time, sizeof(struct timeval));
2077         else /* or use timestamp from beginning */
2078             memcpy(&temp.interval_start_time, &rp->start_time, sizeof(struct timeval));
2079         /* now save time of end of this interval */
2080         gettimeofday(&rp->end_time, NULL);
2081         memcpy(&temp.interval_end_time, &rp->end_time, sizeof(struct timeval));
2082         temp.interval_duration = timeval_diff(&temp.interval_start_time, &temp.interval_end_time);
2083         //temp.interval_duration = timeval_diff(&temp.interval_start_time, &temp.interval_end_time);
2084 	if (test->protocol->id == Ptcp) {
2085 	    if ( has_tcpinfo()) {
2086 		save_tcpinfo(sp, &temp);
2087 		if (test->sender && test->sender_has_retransmits) {
2088 		    long total_retrans = get_total_retransmits(&temp);
2089 		    temp.interval_retrans = total_retrans - rp->stream_prev_total_retrans;
2090 		    rp->stream_retrans += temp.interval_retrans;
2091 		    rp->stream_prev_total_retrans = total_retrans;
2092 
2093 		    temp.snd_cwnd = get_snd_cwnd(&temp);
2094 		    if (temp.snd_cwnd > rp->stream_max_snd_cwnd) {
2095 			rp->stream_max_snd_cwnd = temp.snd_cwnd;
2096 		    }
2097 
2098 		    temp.rtt = get_rtt(&temp);
2099 		    if (temp.rtt > rp->stream_max_rtt) {
2100 			rp->stream_max_rtt = temp.rtt;
2101 		    }
2102 		    if (rp->stream_min_rtt == 0 ||
2103 			temp.rtt < rp->stream_min_rtt) {
2104 			rp->stream_min_rtt = temp.rtt;
2105 		    }
2106 		    rp->stream_sum_rtt += temp.rtt;
2107 		    rp->stream_count_rtt++;
2108 		}
2109 	    }
2110 	} else {
2111 	    if (irp == NULL) {
2112 		temp.interval_packet_count = sp->packet_count;
2113 		temp.interval_outoforder_packets = sp->outoforder_packets;
2114 		temp.interval_cnt_error = sp->cnt_error;
2115 	    } else {
2116 		temp.interval_packet_count = sp->packet_count - irp->packet_count;
2117 		temp.interval_outoforder_packets = sp->outoforder_packets - irp->outoforder_packets;
2118 		temp.interval_cnt_error = sp->cnt_error - irp->cnt_error;
2119 	    }
2120 	    temp.packet_count = sp->packet_count;
2121 	    temp.jitter = sp->jitter;
2122 	    temp.outoforder_packets = sp->outoforder_packets;
2123 	    temp.cnt_error = sp->cnt_error;
2124 	}
2125         add_to_interval_list(rp, &temp);
2126         rp->bytes_sent_this_interval = rp->bytes_received_this_interval = 0;
2127     }
2128 }
2129 
2130 /**
2131  * Print intermediate results during a test (interval report).
2132  * Uses print_interval_results to print the results for each stream,
2133  * then prints an interval summary for all streams in this
2134  * interval.
2135  */
2136 static void
2137 iperf_print_intermediate(struct iperf_test *test)
2138 {
2139     char ubuf[UNIT_LEN];
2140     char nbuf[UNIT_LEN];
2141     struct iperf_stream *sp = NULL;
2142     struct iperf_interval_results *irp;
2143     iperf_size_t bytes = 0;
2144     double bandwidth;
2145     int retransmits = 0;
2146     double start_time, end_time;
2147     cJSON *json_interval;
2148     cJSON *json_interval_streams;
2149     int total_packets = 0, lost_packets = 0;
2150     double avg_jitter = 0.0, lost_percent;
2151 
2152     if (test->json_output) {
2153         json_interval = cJSON_CreateObject();
2154 	if (json_interval == NULL)
2155 	    return;
2156 	cJSON_AddItemToArray(test->json_intervals, json_interval);
2157         json_interval_streams = cJSON_CreateArray();
2158 	if (json_interval_streams == NULL)
2159 	    return;
2160 	cJSON_AddItemToObject(json_interval, "streams", json_interval_streams);
2161     } else {
2162         json_interval = NULL;
2163         json_interval_streams = NULL;
2164     }
2165 
2166     SLIST_FOREACH(sp, &test->streams, streams) {
2167         print_interval_results(test, sp, json_interval_streams);
2168 	/* sum up all streams */
2169 	irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);
2170 	if (irp == NULL) {
2171 	    iperf_err(test, "iperf_print_intermediate error: interval_results is NULL");
2172 	    return;
2173 	}
2174         bytes += irp->bytes_transferred;
2175 	if (test->protocol->id == Ptcp) {
2176 	    if (test->sender && test->sender_has_retransmits) {
2177 		retransmits += irp->interval_retrans;
2178 	    }
2179 	} else {
2180             total_packets += irp->interval_packet_count;
2181             lost_packets += irp->interval_cnt_error;
2182             avg_jitter += irp->jitter;
2183 	}
2184     }
2185 
2186     /* next build string with sum of all streams */
2187     if (test->num_streams > 1 || test->json_output) {
2188         sp = SLIST_FIRST(&test->streams); /* reset back to 1st stream */
2189 	/* Only do this of course if there was a first stream */
2190 	if (sp) {
2191         irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);    /* use 1st stream for timing info */
2192 
2193         unit_snprintf(ubuf, UNIT_LEN, (double) bytes, 'A');
2194 	bandwidth = (double) bytes / (double) irp->interval_duration;
2195         unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2196 
2197         start_time = timeval_diff(&sp->result->start_time,&irp->interval_start_time);
2198         end_time = timeval_diff(&sp->result->start_time,&irp->interval_end_time);
2199 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2200 	    if (test->sender && test->sender_has_retransmits) {
2201 		/* Interval sum, TCP with retransmits. */
2202 		if (test->json_output)
2203 		    cJSON_AddItemToObject(json_interval, "sum", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  retransmits: %d  omitted: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, (int64_t) retransmits, irp->omitted)); /* XXX irp->omitted or test->omitting? */
2204 		else
2205 		    iprintf(test, report_sum_bw_retrans_format, start_time, end_time, ubuf, nbuf, retransmits, irp->omitted?report_omitted:""); /* XXX irp->omitted or test->omitting? */
2206 	    } else {
2207 		/* Interval sum, TCP without retransmits. */
2208 		if (test->json_output)
2209 		    cJSON_AddItemToObject(json_interval, "sum", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  omitted: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, test->omitting));
2210 		else
2211 		    iprintf(test, report_sum_bw_format, start_time, end_time, ubuf, nbuf, test->omitting?report_omitted:"");
2212 	    }
2213 	} else {
2214 	    /* Interval sum, UDP. */
2215 	    if (test->sender) {
2216 		if (test->json_output)
2217 		    cJSON_AddItemToObject(json_interval, "sum", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  packets: %d  omitted: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, (int64_t) total_packets, test->omitting));
2218 		else
2219 		    iprintf(test, report_sum_bw_udp_sender_format, start_time, end_time, ubuf, nbuf, total_packets, test->omitting?report_omitted:"");
2220 	    } else {
2221 		avg_jitter /= test->num_streams;
2222 		lost_percent = 100.0 * lost_packets / total_packets;
2223 		if (test->json_output)
2224 		    cJSON_AddItemToObject(json_interval, "sum", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  jitter_ms: %f  lost_packets: %d  packets: %d  lost_percent: %f  omitted: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, (double) avg_jitter * 1000.0, (int64_t) lost_packets, (int64_t) total_packets, (double) lost_percent, test->omitting));
2225 		else
2226 		    iprintf(test, report_sum_bw_udp_format, start_time, end_time, ubuf, nbuf, avg_jitter * 1000.0, lost_packets, total_packets, lost_percent, test->omitting?report_omitted:"");
2227 	    }
2228 	}
2229 	}
2230     }
2231 }
2232 
2233 /**
2234  * Print overall summary statistics at the end of a test.
2235  */
2236 static void
2237 iperf_print_results(struct iperf_test *test)
2238 {
2239 
2240     cJSON *json_summary_streams = NULL;
2241     cJSON *json_summary_stream = NULL;
2242     int total_retransmits = 0;
2243     int total_packets = 0, lost_packets = 0;
2244     char ubuf[UNIT_LEN];
2245     char nbuf[UNIT_LEN];
2246     struct stat sb;
2247     char sbuf[UNIT_LEN];
2248     struct iperf_stream *sp = NULL;
2249     iperf_size_t bytes_sent, total_sent = 0;
2250     iperf_size_t bytes_received, total_received = 0;
2251     double start_time, end_time, avg_jitter = 0.0, lost_percent;
2252     double bandwidth;
2253 
2254     /* print final summary for all intervals */
2255 
2256     if (test->json_output) {
2257         json_summary_streams = cJSON_CreateArray();
2258 	if (json_summary_streams == NULL)
2259 	    return;
2260 	cJSON_AddItemToObject(test->json_end, "streams", json_summary_streams);
2261     } else {
2262 	iprintf(test, "%s", report_bw_separator);
2263 	if (test->verbose)
2264 	    iprintf(test, "%s", report_summary);
2265 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2266 	    if (test->sender_has_retransmits)
2267 		iprintf(test, "%s", report_bw_retrans_header);
2268 	    else
2269 		iprintf(test, "%s", report_bw_header);
2270 	} else
2271 	    iprintf(test, "%s", report_bw_udp_header);
2272     }
2273 
2274     start_time = 0.;
2275     sp = SLIST_FIRST(&test->streams);
2276     /*
2277      * If there is at least one stream, then figure out the length of time
2278      * we were running the tests and print out some statistics about
2279      * the streams.  It's possible to not have any streams at all
2280      * if the client got interrupted before it got to do anything.
2281      */
2282     if (sp) {
2283     end_time = timeval_diff(&sp->result->start_time, &sp->result->end_time);
2284     SLIST_FOREACH(sp, &test->streams, streams) {
2285 	if (test->json_output) {
2286 	    json_summary_stream = cJSON_CreateObject();
2287 	    if (json_summary_stream == NULL)
2288 		return;
2289 	    cJSON_AddItemToArray(json_summary_streams, json_summary_stream);
2290 	}
2291 
2292         bytes_sent = sp->result->bytes_sent;
2293         bytes_received = sp->result->bytes_received;
2294         total_sent += bytes_sent;
2295         total_received += bytes_received;
2296 
2297         if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2298 	    if (test->sender_has_retransmits) {
2299 		total_retransmits += sp->result->stream_retrans;
2300 	    }
2301 	} else {
2302             total_packets += (sp->packet_count - sp->omitted_packet_count);
2303             lost_packets += sp->cnt_error;
2304             avg_jitter += sp->jitter;
2305         }
2306 
2307 	unit_snprintf(ubuf, UNIT_LEN, (double) bytes_sent, 'A');
2308 	bandwidth = (double) bytes_sent / (double) end_time;
2309 	unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2310 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2311 	    if (test->sender_has_retransmits) {
2312 		/* Summary, TCP with retransmits. */
2313 		if (test->json_output)
2314 		    cJSON_AddItemToObject(json_summary_stream, "sender", iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  retransmits: %d  max_snd_cwnd:  %d  max_rtt:  %d  min_rtt:  %d  mean_rtt:  %d", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_sent, bandwidth * 8, (int64_t) sp->result->stream_retrans, (int64_t) sp->result->stream_max_snd_cwnd, (int64_t) sp->result->stream_max_rtt, (int64_t) sp->result->stream_min_rtt, (int64_t) ((sp->result->stream_count_rtt == 0) ? 0 : sp->result->stream_sum_rtt / sp->result->stream_count_rtt)));
2315 		else
2316 		    iprintf(test, report_bw_retrans_format, sp->socket, start_time, end_time, ubuf, nbuf, sp->result->stream_retrans, report_sender);
2317 	    } else {
2318 		/* Summary, TCP without retransmits. */
2319 		if (test->json_output)
2320 		    cJSON_AddItemToObject(json_summary_stream, "sender", iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_sent, bandwidth * 8));
2321 		else
2322 		    iprintf(test, report_bw_format, sp->socket, start_time, end_time, ubuf, nbuf, report_sender);
2323 	    }
2324 	} else {
2325 	    /* Summary, UDP. */
2326 	    lost_percent = 100.0 * sp->cnt_error / (sp->packet_count - sp->omitted_packet_count);
2327 	    if (test->json_output)
2328 		cJSON_AddItemToObject(json_summary_stream, "udp", iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  jitter_ms: %f  lost_packets: %d  packets: %d  lost_percent: %f", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_sent, bandwidth * 8, (double) sp->jitter * 1000.0, (int64_t) sp->cnt_error, (int64_t) (sp->packet_count - sp->omitted_packet_count), (double) lost_percent));
2329 	    else {
2330 		iprintf(test, report_bw_udp_format, sp->socket, start_time, end_time, ubuf, nbuf, sp->jitter * 1000.0, sp->cnt_error, (sp->packet_count - sp->omitted_packet_count), lost_percent, "");
2331 		if (test->role == 'c')
2332 		    iprintf(test, report_datagrams, sp->socket, (sp->packet_count - sp->omitted_packet_count));
2333 		if (sp->outoforder_packets > 0)
2334 		    iprintf(test, report_sum_outoforder, start_time, end_time, sp->cnt_error);
2335 	    }
2336 	}
2337 
2338 	if (sp->diskfile_fd >= 0) {
2339 	    if (fstat(sp->diskfile_fd, &sb) == 0) {
2340 		int percent = (int) ( ( (double) bytes_sent / (double) sb.st_size ) * 100.0 );
2341 		unit_snprintf(sbuf, UNIT_LEN, (double) sb.st_size, 'A');
2342 		if (test->json_output)
2343 		    cJSON_AddItemToObject(json_summary_stream, "diskfile", iperf_json_printf("sent: %d  size: %d  percent: %d  filename: %s", (int64_t) bytes_sent, (int64_t) sb.st_size, (int64_t) percent, test->diskfile_name));
2344 		else
2345 		    iprintf(test, report_diskfile, ubuf, sbuf, percent, test->diskfile_name);
2346 	    }
2347 	}
2348 
2349 	unit_snprintf(ubuf, UNIT_LEN, (double) bytes_received, 'A');
2350 	bandwidth = (double) bytes_received / (double) end_time;
2351 	unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2352 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2353 	    if (test->json_output)
2354 		cJSON_AddItemToObject(json_summary_stream, "receiver", iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_received, bandwidth * 8));
2355 	    else
2356 		iprintf(test, report_bw_format, sp->socket, start_time, end_time, ubuf, nbuf, report_receiver);
2357 	}
2358     }
2359     }
2360 
2361     if (test->num_streams > 1 || test->json_output) {
2362         unit_snprintf(ubuf, UNIT_LEN, (double) total_sent, 'A');
2363 	/* If no tests were run, arbitrariliy set bandwidth to 0. */
2364 	if (end_time > 0.0) {
2365 	    bandwidth = (double) total_sent / (double) end_time;
2366 	}
2367 	else {
2368 	    bandwidth = 0.0;
2369 	}
2370         unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2371         if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2372 	    if (test->sender_has_retransmits) {
2373 		/* Summary sum, TCP with retransmits. */
2374 		if (test->json_output)
2375 		    cJSON_AddItemToObject(test->json_end, "sum_sent", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  retransmits: %d", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_sent, bandwidth * 8, (int64_t) total_retransmits));
2376 		else
2377 		    iprintf(test, report_sum_bw_retrans_format, start_time, end_time, ubuf, nbuf, total_retransmits, report_sender);
2378 	    } else {
2379 		/* Summary sum, TCP without retransmits. */
2380 		if (test->json_output)
2381 		    cJSON_AddItemToObject(test->json_end, "sum_sent", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_sent, bandwidth * 8));
2382 		else
2383 		    iprintf(test, report_sum_bw_format, start_time, end_time, ubuf, nbuf, report_sender);
2384 	    }
2385             unit_snprintf(ubuf, UNIT_LEN, (double) total_received, 'A');
2386 	    /* If no tests were run, set received bandwidth to 0 */
2387 	    if (end_time > 0.0) {
2388 		bandwidth = (double) total_received / (double) end_time;
2389 	    }
2390 	    else {
2391 		bandwidth = 0.0;
2392 	    }
2393             unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2394 	    if (test->json_output)
2395 		cJSON_AddItemToObject(test->json_end, "sum_received", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_received, bandwidth * 8));
2396 	    else
2397 		iprintf(test, report_sum_bw_format, start_time, end_time, ubuf, nbuf, report_receiver);
2398         } else {
2399 	    /* Summary sum, UDP. */
2400             avg_jitter /= test->num_streams;
2401 	    /* If no packets were sent, arbitrarily set loss percentage to 100. */
2402 	    if (total_packets > 0) {
2403 		lost_percent = 100.0 * lost_packets / total_packets;
2404 	    }
2405 	    else {
2406 		lost_percent = 100.0;
2407 	    }
2408 	    if (test->json_output)
2409 		cJSON_AddItemToObject(test->json_end, "sum", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  jitter_ms: %f  lost_packets: %d  packets: %d  lost_percent: %f", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_sent, bandwidth * 8, (double) avg_jitter * 1000.0, (int64_t) lost_packets, (int64_t) total_packets, (double) lost_percent));
2410 	    else
2411 		iprintf(test, report_sum_bw_udp_format, start_time, end_time, ubuf, nbuf, avg_jitter * 1000.0, lost_packets, total_packets, lost_percent, "");
2412         }
2413     }
2414 
2415     if (test->json_output)
2416 	cJSON_AddItemToObject(test->json_end, "cpu_utilization_percent", iperf_json_printf("host_total: %f  host_user: %f  host_system: %f  remote_total: %f  remote_user: %f  remote_system: %f", (double) test->cpu_util[0], (double) test->cpu_util[1], (double) test->cpu_util[2], (double) test->remote_cpu_util[0], (double) test->remote_cpu_util[1], (double) test->remote_cpu_util[2]));
2417     else {
2418 	if (test->verbose) {
2419 	    iprintf(test, report_cpu, report_local, test->sender?report_sender:report_receiver, test->cpu_util[0], test->cpu_util[1], test->cpu_util[2], report_remote, test->sender?report_receiver:report_sender, test->remote_cpu_util[0], test->remote_cpu_util[1], test->remote_cpu_util[2]);
2420 	}
2421 
2422 	/* Print server output if we're on the client and it was requested/provided */
2423 	if (test->role == 'c' && iperf_get_test_get_server_output(test)) {
2424 	    if (test->json_server_output) {
2425 		iprintf(test, "\nServer JSON output:\n%s\n", cJSON_Print(test->json_server_output));
2426 		cJSON_Delete(test->json_server_output);
2427 		test->json_server_output = NULL;
2428 	    }
2429 	    if (test->server_output_text) {
2430 		iprintf(test, "\nServer output:\n%s\n", test->server_output_text);
2431 		test->server_output_text = NULL;
2432 	    }
2433 	}
2434     }
2435 }
2436 
2437 /**************************************************************************/
2438 
2439 /**
2440  * Main report-printing callback.
2441  * Prints results either during a test (interval report only) or
2442  * after the entire test has been run (last interval report plus
2443  * overall summary).
2444  */
2445 void
2446 iperf_reporter_callback(struct iperf_test *test)
2447 {
2448     switch (test->state) {
2449         case TEST_RUNNING:
2450         case STREAM_RUNNING:
2451             /* print interval results for each stream */
2452             iperf_print_intermediate(test);
2453             break;
2454         case DISPLAY_RESULTS:
2455             iperf_print_intermediate(test);
2456             iperf_print_results(test);
2457             break;
2458     }
2459 
2460 }
2461 
2462 /**
2463  * Print the interval results for one stream.
2464  * This function needs to know about the overall test so it can determine the
2465  * context for printing headers, separators, etc.
2466  */
2467 static void
2468 print_interval_results(struct iperf_test *test, struct iperf_stream *sp, cJSON *json_interval_streams)
2469 {
2470     char ubuf[UNIT_LEN];
2471     char nbuf[UNIT_LEN];
2472     char cbuf[UNIT_LEN];
2473     double st = 0., et = 0.;
2474     struct iperf_interval_results *irp = NULL;
2475     double bandwidth, lost_percent;
2476 
2477     irp = TAILQ_LAST(&sp->result->interval_results, irlisthead); /* get last entry in linked list */
2478     if (irp == NULL) {
2479 	iperf_err(test, "print_interval_results error: interval_results is NULL");
2480         return;
2481     }
2482     if (!test->json_output) {
2483 	/* First stream? */
2484 	if (sp == SLIST_FIRST(&test->streams)) {
2485 	    /* It it's the first interval, print the header;
2486 	    ** else if there's more than one stream, print the separator;
2487 	    ** else nothing.
2488 	    */
2489 	    if (timeval_equals(&sp->result->start_time, &irp->interval_start_time)) {
2490 		if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2491 		    if (test->sender && test->sender_has_retransmits)
2492 			iprintf(test, "%s", report_bw_retrans_cwnd_header);
2493 		    else
2494 			iprintf(test, "%s", report_bw_header);
2495 		} else {
2496 		    if (test->sender)
2497 			iprintf(test, "%s", report_bw_udp_sender_header);
2498 		    else
2499 			iprintf(test, "%s", report_bw_udp_header);
2500 		}
2501 	    } else if (test->num_streams > 1)
2502 		iprintf(test, "%s", report_bw_separator);
2503 	}
2504     }
2505 
2506     unit_snprintf(ubuf, UNIT_LEN, (double) (irp->bytes_transferred), 'A');
2507     bandwidth = (double) irp->bytes_transferred / (double) irp->interval_duration;
2508     unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2509 
2510     st = timeval_diff(&sp->result->start_time, &irp->interval_start_time);
2511     et = timeval_diff(&sp->result->start_time, &irp->interval_end_time);
2512 
2513     if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2514 	if (test->sender && test->sender_has_retransmits) {
2515 	    /* Interval, TCP with retransmits. */
2516 	    if (test->json_output)
2517 		cJSON_AddItemToArray(json_interval_streams, iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  retransmits: %d  snd_cwnd:  %d  rtt:  %d  omitted: %b", (int64_t) sp->socket, (double) st, (double) et, (double) irp->interval_duration, (int64_t) irp->bytes_transferred, bandwidth * 8, (int64_t) irp->interval_retrans, (int64_t) irp->snd_cwnd, (int64_t) irp->rtt, irp->omitted));
2518 	    else {
2519 		unit_snprintf(cbuf, UNIT_LEN, irp->snd_cwnd, 'A');
2520 		iprintf(test, report_bw_retrans_cwnd_format, sp->socket, st, et, ubuf, nbuf, irp->interval_retrans, cbuf, irp->omitted?report_omitted:"");
2521 	    }
2522 	} else {
2523 	    /* Interval, TCP without retransmits. */
2524 	    if (test->json_output)
2525 		cJSON_AddItemToArray(json_interval_streams, iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  omitted: %b", (int64_t) sp->socket, (double) st, (double) et, (double) irp->interval_duration, (int64_t) irp->bytes_transferred, bandwidth * 8, irp->omitted));
2526 	    else
2527 		iprintf(test, report_bw_format, sp->socket, st, et, ubuf, nbuf, irp->omitted?report_omitted:"");
2528 	}
2529     } else {
2530 	/* Interval, UDP. */
2531 	if (test->sender) {
2532 	    if (test->json_output)
2533 		cJSON_AddItemToArray(json_interval_streams, iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  packets: %d  omitted: %b", (int64_t) sp->socket, (double) st, (double) et, (double) irp->interval_duration, (int64_t) irp->bytes_transferred, bandwidth * 8, (int64_t) irp->interval_packet_count, irp->omitted));
2534 	    else
2535 		iprintf(test, report_bw_udp_sender_format, sp->socket, st, et, ubuf, nbuf, irp->interval_packet_count, irp->omitted?report_omitted:"");
2536 	} else {
2537 	    lost_percent = 100.0 * irp->interval_cnt_error / irp->interval_packet_count;
2538 	    if (test->json_output)
2539 		cJSON_AddItemToArray(json_interval_streams, iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  jitter_ms: %f  lost_packets: %d  packets: %d  lost_percent: %f  omitted: %b", (int64_t) sp->socket, (double) st, (double) et, (double) irp->interval_duration, (int64_t) irp->bytes_transferred, bandwidth * 8, (double) irp->jitter * 1000.0, (int64_t) irp->interval_cnt_error, (int64_t) irp->interval_packet_count, (double) lost_percent, irp->omitted));
2540 	    else
2541 		iprintf(test, report_bw_udp_format, sp->socket, st, et, ubuf, nbuf, irp->jitter * 1000.0, irp->interval_cnt_error, irp->interval_packet_count, lost_percent, irp->omitted?report_omitted:"");
2542 	}
2543     }
2544 }
2545 
2546 /**************************************************************************/
2547 void
2548 iperf_free_stream(struct iperf_stream *sp)
2549 {
2550     struct iperf_interval_results *irp, *nirp;
2551 
2552     /* XXX: need to free interval list too! */
2553     munmap(sp->buffer, sp->test->settings->blksize);
2554     close(sp->buffer_fd);
2555     if (sp->diskfile_fd >= 0)
2556 	close(sp->diskfile_fd);
2557     for (irp = TAILQ_FIRST(&sp->result->interval_results); irp != TAILQ_END(sp->result->interval_results); irp = nirp) {
2558         nirp = TAILQ_NEXT(irp, irlistentries);
2559         free(irp);
2560     }
2561     free(sp->result);
2562     if (sp->send_timer != NULL)
2563 	tmr_cancel(sp->send_timer);
2564     free(sp);
2565 }
2566 
2567 /**************************************************************************/
2568 struct iperf_stream *
2569 iperf_new_stream(struct iperf_test *test, int s)
2570 {
2571     int i;
2572     struct iperf_stream *sp;
2573     char template[] = "/tmp/iperf3.XXXXXX";
2574 
2575     h_errno = 0;
2576 
2577     sp = (struct iperf_stream *) malloc(sizeof(struct iperf_stream));
2578     if (!sp) {
2579         i_errno = IECREATESTREAM;
2580         return NULL;
2581     }
2582 
2583     memset(sp, 0, sizeof(struct iperf_stream));
2584 
2585     sp->test = test;
2586     sp->settings = test->settings;
2587     sp->result = (struct iperf_stream_result *) malloc(sizeof(struct iperf_stream_result));
2588     if (!sp->result) {
2589         free(sp);
2590         i_errno = IECREATESTREAM;
2591         return NULL;
2592     }
2593 
2594     memset(sp->result, 0, sizeof(struct iperf_stream_result));
2595     TAILQ_INIT(&sp->result->interval_results);
2596 
2597     /* Create and randomize the buffer */
2598     sp->buffer_fd = mkstemp(template);
2599     if (sp->buffer_fd == -1) {
2600         i_errno = IECREATESTREAM;
2601         free(sp->result);
2602         free(sp);
2603         return NULL;
2604     }
2605     if (unlink(template) < 0) {
2606         i_errno = IECREATESTREAM;
2607         free(sp->result);
2608         free(sp);
2609         return NULL;
2610     }
2611     if (ftruncate(sp->buffer_fd, test->settings->blksize) < 0) {
2612         i_errno = IECREATESTREAM;
2613         free(sp->result);
2614         free(sp);
2615         return NULL;
2616     }
2617     sp->buffer = (char *) mmap(NULL, test->settings->blksize, PROT_READ|PROT_WRITE, MAP_PRIVATE, sp->buffer_fd, 0);
2618     if (sp->buffer == MAP_FAILED) {
2619         i_errno = IECREATESTREAM;
2620         free(sp->result);
2621         free(sp);
2622         return NULL;
2623     }
2624     srandom(time(NULL));
2625     for (i = 0; i < test->settings->blksize; ++i)
2626         sp->buffer[i] = random();
2627 
2628     /* Set socket */
2629     sp->socket = s;
2630 
2631     sp->snd = test->protocol->send;
2632     sp->rcv = test->protocol->recv;
2633 
2634     if (test->diskfile_name != (char*) 0) {
2635 	sp->diskfile_fd = open(test->diskfile_name, test->sender ? O_RDONLY : (O_WRONLY|O_CREAT|O_TRUNC), S_IRUSR|S_IWUSR);
2636 	if (sp->diskfile_fd == -1) {
2637 	    i_errno = IEFILE;
2638             munmap(sp->buffer, sp->test->settings->blksize);
2639             free(sp->result);
2640             free(sp);
2641 	    return NULL;
2642 	}
2643         sp->snd2 = sp->snd;
2644 	sp->snd = diskfile_send;
2645 	sp->rcv2 = sp->rcv;
2646 	sp->rcv = diskfile_recv;
2647     } else
2648         sp->diskfile_fd = -1;
2649 
2650     /* Initialize stream */
2651     if (iperf_init_stream(sp, test) < 0) {
2652         close(sp->buffer_fd);
2653         munmap(sp->buffer, sp->test->settings->blksize);
2654         free(sp->result);
2655         free(sp);
2656         return NULL;
2657     }
2658     iperf_add_stream(test, sp);
2659 
2660     return sp;
2661 }
2662 
2663 /**************************************************************************/
2664 int
2665 iperf_init_stream(struct iperf_stream *sp, struct iperf_test *test)
2666 {
2667     socklen_t len;
2668     int opt;
2669 
2670     len = sizeof(struct sockaddr_storage);
2671     if (getsockname(sp->socket, (struct sockaddr *) &sp->local_addr, &len) < 0) {
2672         i_errno = IEINITSTREAM;
2673         return -1;
2674     }
2675     len = sizeof(struct sockaddr_storage);
2676     if (getpeername(sp->socket, (struct sockaddr *) &sp->remote_addr, &len) < 0) {
2677         i_errno = IEINITSTREAM;
2678         return -1;
2679     }
2680 
2681     /* Set IP TOS */
2682     if ((opt = test->settings->tos)) {
2683         if (getsockdomain(sp->socket) == AF_INET6) {
2684 #ifdef IPV6_TCLASS
2685             if (setsockopt(sp->socket, IPPROTO_IPV6, IPV6_TCLASS, &opt, sizeof(opt)) < 0) {
2686                 i_errno = IESETCOS;
2687                 return -1;
2688             }
2689 #else
2690             i_errno = IESETCOS;
2691             return -1;
2692 #endif
2693         } else {
2694             if (setsockopt(sp->socket, IPPROTO_IP, IP_TOS, &opt, sizeof(opt)) < 0) {
2695                 i_errno = IESETTOS;
2696                 return -1;
2697             }
2698         }
2699     }
2700 
2701     return 0;
2702 }
2703 
2704 /**************************************************************************/
2705 void
2706 iperf_add_stream(struct iperf_test *test, struct iperf_stream *sp)
2707 {
2708     int i;
2709     struct iperf_stream *n, *prev;
2710 
2711     if (SLIST_EMPTY(&test->streams)) {
2712         SLIST_INSERT_HEAD(&test->streams, sp, streams);
2713         sp->id = 1;
2714     } else {
2715         // for (n = test->streams, i = 2; n->next; n = n->next, ++i);
2716         i = 2;
2717         SLIST_FOREACH(n, &test->streams, streams) {
2718             prev = n;
2719             ++i;
2720         }
2721         SLIST_INSERT_AFTER(prev, sp, streams);
2722         sp->id = i;
2723     }
2724 }
2725 
2726 /* This pair of routines gets inserted into the snd/rcv function pointers
2727 ** when there's a -F flag. They handle the file stuff and call the real
2728 ** snd/rcv functions, which have been saved in snd2/rcv2.
2729 **
2730 ** The advantage of doing it this way is that in the much more common
2731 ** case of no -F flag, there is zero extra overhead.
2732 */
2733 
2734 static int
2735 diskfile_send(struct iperf_stream *sp)
2736 {
2737     int r;
2738 
2739     r = read(sp->diskfile_fd, sp->buffer, sp->test->settings->blksize);
2740     if (r == 0)
2741         sp->test->done = 1;
2742     else
2743 	r = sp->snd2(sp);
2744     return r;
2745 }
2746 
2747 static int
2748 diskfile_recv(struct iperf_stream *sp)
2749 {
2750     int r;
2751 
2752     r = sp->rcv2(sp);
2753     if (r > 0) {
2754 	(void) write(sp->diskfile_fd, sp->buffer, r);
2755 	(void) fsync(sp->diskfile_fd);
2756     }
2757     return r;
2758 }
2759 
2760 
2761 void
2762 iperf_catch_sigend(void (*handler)(int))
2763 {
2764     signal(SIGINT, handler);
2765     signal(SIGTERM, handler);
2766     signal(SIGHUP, handler);
2767 }
2768 
2769 /**
2770  * Called as a result of getting a signal.
2771  * Depending on the current state of the test (and the role of this
2772  * process) compute and report one more set of ending statistics
2773  * before cleaning up and exiting.
2774  */
2775 void
2776 iperf_got_sigend(struct iperf_test *test)
2777 {
2778     /*
2779      * If we're the client, or if we're a server and running a test,
2780      * then dump out the accumulated stats so far.
2781      */
2782     if (test->role == 'c' ||
2783       (test->role == 's' && test->state == TEST_RUNNING)) {
2784 
2785 	test->done = 1;
2786 	cpu_util(test->cpu_util);
2787 	test->stats_callback(test);
2788 	test->state = DISPLAY_RESULTS; /* change local state only */
2789 	if (test->on_test_finish)
2790 	    test->on_test_finish(test);
2791 	test->reporter_callback(test);
2792     }
2793 
2794     if (test->ctrl_sck >= 0) {
2795 	test->state = (test->role == 'c') ? CLIENT_TERMINATE : SERVER_TERMINATE;
2796 	(void) Nwrite(test->ctrl_sck, (char*) &test->state, sizeof(signed char), Ptcp);
2797     }
2798     i_errno = (test->role == 'c') ? IECLIENTTERM : IESERVERTERM;
2799     iperf_errexit(test, "interrupt - %s", iperf_strerror(i_errno));
2800 }
2801 
2802 /* Try to write a PID file if requested, return -1 on an error. */
2803 int
2804 iperf_create_pidfile(struct iperf_test *test)
2805 {
2806     if (test->pidfile) {
2807 	int fd;
2808 	char buf[8];
2809 	fd = open(test->pidfile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR|S_IWUSR);
2810 	if (fd < 0) {
2811 	    return -1;
2812 	}
2813 	snprintf(buf, sizeof(buf), "%d", getpid()); /* no trailing newline */
2814 	if (write(fd, buf, strlen(buf) + 1) < 0) {
2815 	    return -1;
2816 	}
2817 	if (close(fd) < 0) {
2818 	    return -1;
2819 	};
2820     }
2821     return 0;
2822 }
2823 
2824 /* Get rid of a PID file, return -1 on error. */
2825 int
2826 iperf_delete_pidfile(struct iperf_test *test)
2827 {
2828     if (test->pidfile) {
2829 	if (unlink(test->pidfile) < 0) {
2830 	    return -1;
2831 	}
2832     }
2833     return 0;
2834 }
2835 
2836 int
2837 iperf_json_start(struct iperf_test *test)
2838 {
2839     test->json_top = cJSON_CreateObject();
2840     if (test->json_top == NULL)
2841         return -1;
2842     if (test->title)
2843 	cJSON_AddStringToObject(test->json_top, "title", test->title);
2844     test->json_start = cJSON_CreateObject();
2845     if (test->json_start == NULL)
2846         return -1;
2847     cJSON_AddItemToObject(test->json_top, "start", test->json_start);
2848     test->json_connected = cJSON_CreateArray();
2849     if (test->json_connected == NULL)
2850         return -1;
2851     cJSON_AddItemToObject(test->json_start, "connected", test->json_connected);
2852     test->json_intervals = cJSON_CreateArray();
2853     if (test->json_intervals == NULL)
2854         return -1;
2855     cJSON_AddItemToObject(test->json_top, "intervals", test->json_intervals);
2856     test->json_end = cJSON_CreateObject();
2857     if (test->json_end == NULL)
2858         return -1;
2859     cJSON_AddItemToObject(test->json_top, "end", test->json_end);
2860     return 0;
2861 }
2862 
2863 int
2864 iperf_json_finish(struct iperf_test *test)
2865 {
2866     /* Include server output */
2867     if (test->json_server_output) {
2868 	cJSON_AddItemToObject(test->json_top, "server_output_json", test->json_server_output);
2869     }
2870     if (test->server_output_text) {
2871 	cJSON_AddStringToObject(test->json_top, "server_output_text", test->server_output_text);
2872     }
2873     test->json_output_string = cJSON_Print(test->json_top);
2874     if (test->json_output_string == NULL)
2875         return -1;
2876     fprintf(test->outfile, "%s\n", test->json_output_string);
2877     iflush(test);
2878     cJSON_Delete(test->json_top);
2879     test->json_top = test->json_start = test->json_connected = test->json_intervals = test->json_server_output = test->json_end = NULL;
2880     return 0;
2881 }
2882 
2883 
2884 /* CPU affinity stuff - Linux and FreeBSD only. */
2885 
2886 int
2887 iperf_setaffinity(struct iperf_test *test, int affinity)
2888 {
2889 #if defined(HAVE_SCHED_SETAFFINITY)
2890     cpu_set_t cpu_set;
2891 
2892     CPU_ZERO(&cpu_set);
2893     CPU_SET(affinity, &cpu_set);
2894     if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0) {
2895 	i_errno = IEAFFINITY;
2896         return -1;
2897     }
2898     return 0;
2899 #elif defined(HAVE_CPUSET_SETAFFINITY)
2900     cpuset_t cpumask;
2901 
2902     if(cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1,
2903                           sizeof(cpuset_t), &test->cpumask) != 0) {
2904         i_errno = IEAFFINITY;
2905         return -1;
2906     }
2907 
2908     CPU_ZERO(&cpumask);
2909     CPU_SET(affinity, &cpumask);
2910 
2911     if(cpuset_setaffinity(CPU_LEVEL_WHICH,CPU_WHICH_PID, -1,
2912                           sizeof(cpuset_t), &cpumask) != 0) {
2913         i_errno = IEAFFINITY;
2914         return -1;
2915     }
2916     return 0;
2917 #else /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY */
2918     i_errno = IEAFFINITY;
2919     return -1;
2920 #endif /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY */
2921 }
2922 
2923 int
2924 iperf_clearaffinity(struct iperf_test *test)
2925 {
2926 #if defined(HAVE_SCHED_SETAFFINITY)
2927     cpu_set_t cpu_set;
2928     int i;
2929 
2930     CPU_ZERO(&cpu_set);
2931     for (i = 0; i < CPU_SETSIZE; ++i)
2932 	CPU_SET(i, &cpu_set);
2933     if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0) {
2934 	i_errno = IEAFFINITY;
2935         return -1;
2936     }
2937     return 0;
2938 #elif defined(HAVE_CPUSET_SETAFFINITY)
2939     if(cpuset_setaffinity(CPU_LEVEL_WHICH,CPU_WHICH_PID, -1,
2940                           sizeof(cpuset_t), &test->cpumask) != 0) {
2941         i_errno = IEAFFINITY;
2942         return -1;
2943     }
2944     return 0;
2945 #else /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY */
2946     i_errno = IEAFFINITY;
2947     return -1;
2948 #endif /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY */
2949 }
2950 
2951 int
2952 iprintf(struct iperf_test *test, const char* format, ...)
2953 {
2954     va_list argp;
2955     int r = -1;
2956 
2957     /*
2958      * There are roughly two use cases here.  If we're the client,
2959      * want to print stuff directly to the output stream.
2960      * If we're the sender we might need to buffer up output to send
2961      * to the client.
2962      *
2963      * This doesn't make a whole lot of difference except there are
2964      * some chunks of output on the client (on particular the whole
2965      * of the server output with --get-server-output) that could
2966      * easily exceed the size of the line buffer, but which don't need
2967      * to be buffered up anyway.
2968      */
2969     if (test->role == 'c') {
2970 	if (test->title)
2971 	    fprintf(test->outfile, "%s:  ", test->title);
2972 	va_start(argp, format);
2973 	r = vfprintf(test->outfile, format, argp);
2974 	va_end(argp);
2975     }
2976     else if (test->role == 's') {
2977 	char linebuffer[1024];
2978 	va_start(argp, format);
2979 	r = vsnprintf(linebuffer, sizeof(linebuffer), format, argp);
2980 	va_end(argp);
2981 	fprintf(test->outfile, "%s", linebuffer);
2982 
2983 	if (test->role == 's' && iperf_get_test_get_server_output(test)) {
2984 	    struct iperf_textline *l = (struct iperf_textline *) malloc(sizeof(struct iperf_textline));
2985 	    l->line = strdup(linebuffer);
2986 	    TAILQ_INSERT_TAIL(&(test->server_output_list), l, textlineentries);
2987 	}
2988     }
2989     return r;
2990 }
2991 
2992 int
2993 iflush(struct iperf_test *test)
2994 {
2995     return fflush(test->outfile);
2996 }
2997