xref: /iperf/src/iperf_api.c (revision 11fadc3f)
1 /*
2  * iperf, Copyright (c) 2014-2022, 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 #ifndef _GNU_SOURCE
28 # define _GNU_SOURCE
29 #endif
30 #define __USE_GNU
31 
32 #include "iperf_config.h"
33 
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <time.h>
38 #include <getopt.h>
39 #include <errno.h>
40 #include <signal.h>
41 #include <unistd.h>
42 #include <assert.h>
43 #include <fcntl.h>
44 #include <sys/socket.h>
45 #include <sys/types.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netdb.h>
49 #ifdef HAVE_STDINT_H
50 #include <stdint.h>
51 #endif
52 #include <sys/time.h>
53 #include <sys/resource.h>
54 #include <sys/mman.h>
55 #include <sys/stat.h>
56 #include <sched.h>
57 #include <setjmp.h>
58 #include <stdarg.h>
59 #include <math.h>
60 
61 #if defined(HAVE_CPUSET_SETAFFINITY)
62 #include <sys/param.h>
63 #include <sys/cpuset.h>
64 #endif /* HAVE_CPUSET_SETAFFINITY */
65 
66 #if defined(__CYGWIN__) || defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
67 #define CPU_SETSIZE __CPU_SETSIZE
68 #endif /* __CYGWIN__, _WIN32, _WIN64, __WINDOWS__ */
69 
70 #if defined(HAVE_SETPROCESSAFFINITYMASK)
71 #include <Windows.h>
72 #endif /* HAVE_SETPROCESSAFFINITYMASK */
73 
74 #include "net.h"
75 #include "iperf.h"
76 #include "iperf_api.h"
77 #include "iperf_udp.h"
78 #include "iperf_tcp.h"
79 #if defined(HAVE_SCTP_H)
80 #include "iperf_sctp.h"
81 #endif /* HAVE_SCTP_H */
82 #include "timer.h"
83 
84 #include "cjson.h"
85 #include "units.h"
86 #include "iperf_util.h"
87 #include "iperf_locale.h"
88 #include "version.h"
89 #if defined(HAVE_SSL)
90 #include <openssl/bio.h>
91 #include <openssl/err.h>
92 #include "iperf_auth.h"
93 #endif /* HAVE_SSL */
94 
95 /* Forwards. */
96 static int send_parameters(struct iperf_test *test);
97 static int get_parameters(struct iperf_test *test);
98 static int send_results(struct iperf_test *test);
99 static int get_results(struct iperf_test *test);
100 static int diskfile_send(struct iperf_stream *sp);
101 static int diskfile_recv(struct iperf_stream *sp);
102 static int JSON_write(int fd, cJSON *json);
103 static void print_interval_results(struct iperf_test *test, struct iperf_stream *sp, cJSON *json_interval_streams);
104 static cJSON *JSON_read(int fd);
105 
106 
107 /*************************** Print usage functions ****************************/
108 
109 void
110 usage()
111 {
112     fputs(usage_shortstr, stderr);
113 }
114 
115 
116 void
117 usage_long(FILE *f)
118 {
119     fprintf(f, usage_longstr, DEFAULT_NO_MSG_RCVD_TIMEOUT, UDP_RATE / (1024*1024), DEFAULT_PACING_TIMER, DURATION, DEFAULT_TCP_BLKSIZE / 1024, DEFAULT_UDP_BLKSIZE);
120 }
121 
122 
123 void warning(const char *str)
124 {
125     fprintf(stderr, "warning: %s\n", str);
126 }
127 
128 
129 /************** Getter routines for some fields inside iperf_test *************/
130 
131 int
132 iperf_get_verbose(struct iperf_test *ipt)
133 {
134     return ipt->verbose;
135 }
136 
137 int
138 iperf_get_control_socket(struct iperf_test *ipt)
139 {
140     return ipt->ctrl_sck;
141 }
142 
143 int
144 iperf_get_control_socket_mss(struct iperf_test *ipt)
145 {
146     return ipt->ctrl_sck_mss;
147 }
148 
149 int
150 iperf_get_test_omit(struct iperf_test *ipt)
151 {
152     return ipt->omit;
153 }
154 
155 int
156 iperf_get_test_duration(struct iperf_test *ipt)
157 {
158     return ipt->duration;
159 }
160 
161 uint64_t
162 iperf_get_test_rate(struct iperf_test *ipt)
163 {
164     return ipt->settings->rate;
165 }
166 
167 uint64_t
168 iperf_get_test_bitrate_limit(struct iperf_test *ipt)
169 {
170     return ipt->settings->bitrate_limit;
171 }
172 
173 double
174 iperf_get_test_bitrate_limit_interval(struct iperf_test *ipt)
175 {
176     return ipt->settings->bitrate_limit_interval;
177 }
178 
179 int
180 iperf_get_test_bitrate_limit_stats_per_interval(struct iperf_test *ipt)
181 {
182     return ipt->settings->bitrate_limit_stats_per_interval;
183 }
184 
185 uint64_t
186 iperf_get_test_fqrate(struct iperf_test *ipt)
187 {
188     return ipt->settings->fqrate;
189 }
190 
191 int
192 iperf_get_test_pacing_timer(struct iperf_test *ipt)
193 {
194     return ipt->settings->pacing_timer;
195 }
196 
197 uint64_t
198 iperf_get_test_bytes(struct iperf_test *ipt)
199 {
200     return (uint64_t) ipt->settings->bytes;
201 }
202 
203 uint64_t
204 iperf_get_test_blocks(struct iperf_test *ipt)
205 {
206     return (uint64_t) ipt->settings->blocks;
207 }
208 
209 int
210 iperf_get_test_burst(struct iperf_test *ipt)
211 {
212     return ipt->settings->burst;
213 }
214 
215 char
216 iperf_get_test_role(struct iperf_test *ipt)
217 {
218     return ipt->role;
219 }
220 
221 int
222 iperf_get_test_reverse(struct iperf_test *ipt)
223 {
224     return ipt->reverse;
225 }
226 
227 int
228 iperf_get_test_blksize(struct iperf_test *ipt)
229 {
230     return ipt->settings->blksize;
231 }
232 
233 FILE *
234 iperf_get_test_outfile (struct iperf_test *ipt)
235 {
236     return ipt->outfile;
237 }
238 
239 int
240 iperf_get_test_socket_bufsize(struct iperf_test *ipt)
241 {
242     return ipt->settings->socket_bufsize;
243 }
244 
245 double
246 iperf_get_test_reporter_interval(struct iperf_test *ipt)
247 {
248     return ipt->reporter_interval;
249 }
250 
251 double
252 iperf_get_test_stats_interval(struct iperf_test *ipt)
253 {
254     return ipt->stats_interval;
255 }
256 
257 int
258 iperf_get_test_num_streams(struct iperf_test *ipt)
259 {
260     return ipt->num_streams;
261 }
262 
263 int
264 iperf_get_test_timestamps(struct iperf_test *ipt)
265 {
266     return ipt->timestamps;
267 }
268 
269 const char *
270 iperf_get_test_timestamp_format(struct iperf_test *ipt)
271 {
272     return ipt->timestamp_format;
273 }
274 
275 int
276 iperf_get_test_repeating_payload(struct iperf_test *ipt)
277 {
278     return ipt->repeating_payload;
279 }
280 
281 int
282 iperf_get_test_bind_port(struct iperf_test *ipt)
283 {
284     return ipt->bind_port;
285 }
286 
287 int
288 iperf_get_test_server_port(struct iperf_test *ipt)
289 {
290     return ipt->server_port;
291 }
292 
293 char*
294 iperf_get_test_server_hostname(struct iperf_test *ipt)
295 {
296     return ipt->server_hostname;
297 }
298 
299 char*
300 iperf_get_test_template(struct iperf_test *ipt)
301 {
302     return ipt->tmp_template;
303 }
304 
305 int
306 iperf_get_test_protocol_id(struct iperf_test *ipt)
307 {
308     return ipt->protocol->id;
309 }
310 
311 int
312 iperf_get_test_json_output(struct iperf_test *ipt)
313 {
314     return ipt->json_output;
315 }
316 
317 char *
318 iperf_get_test_json_output_string(struct iperf_test *ipt)
319 {
320     return ipt->json_output_string;
321 }
322 
323 int
324 iperf_get_test_zerocopy(struct iperf_test *ipt)
325 {
326     return ipt->zerocopy;
327 }
328 
329 int
330 iperf_get_test_get_server_output(struct iperf_test *ipt)
331 {
332     return ipt->get_server_output;
333 }
334 
335 char
336 iperf_get_test_unit_format(struct iperf_test *ipt)
337 {
338     return ipt->settings->unit_format;
339 }
340 
341 char *
342 iperf_get_test_bind_address(struct iperf_test *ipt)
343 {
344     return ipt->bind_address;
345 }
346 
347 char *
348 iperf_get_test_bind_dev(struct iperf_test *ipt)
349 {
350     return ipt->bind_dev;
351 }
352 
353 int
354 iperf_get_test_udp_counters_64bit(struct iperf_test *ipt)
355 {
356     return ipt->udp_counters_64bit;
357 }
358 
359 int
360 iperf_get_test_one_off(struct iperf_test *ipt)
361 {
362     return ipt->one_off;
363 }
364 
365 int
366 iperf_get_test_tos(struct iperf_test *ipt)
367 {
368     return ipt->settings->tos;
369 }
370 
371 char *
372 iperf_get_test_extra_data(struct iperf_test *ipt)
373 {
374     return ipt->extra_data;
375 }
376 
377 static const char iperf_version[] = IPERF_VERSION;
378 char *
379 iperf_get_iperf_version(void)
380 {
381     return (char*)iperf_version;
382 }
383 
384 int
385 iperf_get_test_no_delay(struct iperf_test *ipt)
386 {
387     return ipt->no_delay;
388 }
389 
390 int
391 iperf_get_test_connect_timeout(struct iperf_test *ipt)
392 {
393     return ipt->settings->connect_timeout;
394 }
395 
396 int
397 iperf_get_test_idle_timeout(struct iperf_test *ipt)
398 {
399     return ipt->settings->idle_timeout;
400 }
401 
402 int
403 iperf_get_dont_fragment(struct iperf_test *ipt)
404 {
405     return ipt->settings->dont_fragment;
406 }
407 
408 struct iperf_time*
409 iperf_get_test_rcv_timeout(struct iperf_test *ipt)
410 {
411     return &ipt->settings->rcv_timeout;
412 }
413 
414 char*
415 iperf_get_test_congestion_control(struct iperf_test* ipt)
416 {
417     return ipt->congestion;
418 }
419 
420 int
421 iperf_get_test_mss(struct iperf_test *ipt)
422 {
423     return ipt->settings->mss;
424 }
425 
426 /************** Setter routines for some fields inside iperf_test *************/
427 
428 void
429 iperf_set_verbose(struct iperf_test *ipt, int verbose)
430 {
431     ipt->verbose = verbose;
432 }
433 
434 void
435 iperf_set_control_socket(struct iperf_test *ipt, int ctrl_sck)
436 {
437     ipt->ctrl_sck = ctrl_sck;
438 }
439 
440 void
441 iperf_set_test_omit(struct iperf_test *ipt, int omit)
442 {
443     ipt->omit = omit;
444 }
445 
446 void
447 iperf_set_test_duration(struct iperf_test *ipt, int duration)
448 {
449     ipt->duration = duration;
450 }
451 
452 void
453 iperf_set_test_reporter_interval(struct iperf_test *ipt, double reporter_interval)
454 {
455     ipt->reporter_interval = reporter_interval;
456 }
457 
458 void
459 iperf_set_test_stats_interval(struct iperf_test *ipt, double stats_interval)
460 {
461     ipt->stats_interval = stats_interval;
462 }
463 
464 void
465 iperf_set_test_state(struct iperf_test *ipt, signed char state)
466 {
467     ipt->state = state;
468 }
469 
470 void
471 iperf_set_test_blksize(struct iperf_test *ipt, int blksize)
472 {
473     ipt->settings->blksize = blksize;
474 }
475 
476 void
477 iperf_set_test_logfile(struct iperf_test *ipt, const char *logfile)
478 {
479     ipt->logfile = strdup(logfile);
480 }
481 
482 void
483 iperf_set_test_rate(struct iperf_test *ipt, uint64_t rate)
484 {
485     ipt->settings->rate = rate;
486 }
487 
488 void
489 iperf_set_test_bitrate_limit_maximum(struct iperf_test *ipt, uint64_t total_rate)
490 {
491     ipt->settings->bitrate_limit = total_rate;
492 }
493 
494 void
495 iperf_set_test_bitrate_limit_interval(struct iperf_test *ipt, uint64_t bitrate_limit_interval)
496 {
497     ipt->settings->bitrate_limit_interval = bitrate_limit_interval;
498 }
499 
500 void
501 iperf_set_test_bitrate_limit_stats_per_interval(struct iperf_test *ipt, uint64_t bitrate_limit_stats_per_interval)
502 {
503     ipt->settings->bitrate_limit_stats_per_interval = bitrate_limit_stats_per_interval;
504 }
505 
506 void
507 iperf_set_test_fqrate(struct iperf_test *ipt, uint64_t fqrate)
508 {
509     ipt->settings->fqrate = fqrate;
510 }
511 
512 void
513 iperf_set_test_pacing_timer(struct iperf_test *ipt, int pacing_timer)
514 {
515     ipt->settings->pacing_timer = pacing_timer;
516 }
517 
518 void
519 iperf_set_test_bytes(struct iperf_test *ipt, uint64_t bytes)
520 {
521     ipt->settings->bytes = (iperf_size_t) bytes;
522 }
523 
524 void
525 iperf_set_test_blocks(struct iperf_test *ipt, uint64_t blocks)
526 {
527     ipt->settings->blocks = (iperf_size_t) blocks;
528 }
529 
530 void
531 iperf_set_test_burst(struct iperf_test *ipt, int burst)
532 {
533     ipt->settings->burst = burst;
534 }
535 
536 void
537 iperf_set_test_bind_port(struct iperf_test *ipt, int bind_port)
538 {
539     ipt->bind_port = bind_port;
540 }
541 
542 void
543 iperf_set_test_server_port(struct iperf_test *ipt, int srv_port)
544 {
545     ipt->server_port = srv_port;
546 }
547 
548 void
549 iperf_set_test_socket_bufsize(struct iperf_test *ipt, int socket_bufsize)
550 {
551     ipt->settings->socket_bufsize = socket_bufsize;
552 }
553 
554 void
555 iperf_set_test_num_streams(struct iperf_test *ipt, int num_streams)
556 {
557     ipt->num_streams = num_streams;
558 }
559 
560 void
561 iperf_set_test_repeating_payload(struct iperf_test *ipt, int repeating_payload)
562 {
563     ipt->repeating_payload = repeating_payload;
564 }
565 
566 void
567 iperf_set_test_timestamps(struct iperf_test *ipt, int timestamps)
568 {
569     ipt->timestamps = timestamps;
570 }
571 
572 void
573 iperf_set_test_timestamp_format(struct iperf_test *ipt, const char *tf)
574 {
575     ipt->timestamp_format = strdup(tf);
576 }
577 
578 static void
579 check_sender_has_retransmits(struct iperf_test *ipt)
580 {
581     if (ipt->mode != RECEIVER && ipt->protocol->id == Ptcp && has_tcpinfo_retransmits())
582 	ipt->sender_has_retransmits = 1;
583     else
584 	ipt->sender_has_retransmits = 0;
585 }
586 
587 void
588 iperf_set_test_role(struct iperf_test *ipt, char role)
589 {
590     ipt->role = role;
591     if (!ipt->reverse) {
592         if (ipt->bidirectional)
593             ipt->mode = BIDIRECTIONAL;
594         else if (role == 'c')
595             ipt->mode = SENDER;
596         else if (role == 's')
597             ipt->mode = RECEIVER;
598     } else {
599         if (role == 'c')
600             ipt->mode = RECEIVER;
601         else if (role == 's')
602             ipt->mode = SENDER;
603     }
604     check_sender_has_retransmits(ipt);
605 }
606 
607 void
608 iperf_set_test_server_hostname(struct iperf_test *ipt, const char *server_hostname)
609 {
610     ipt->server_hostname = strdup(server_hostname);
611 }
612 
613 void
614 iperf_set_test_template(struct iperf_test *ipt, const char *tmp_template)
615 {
616     ipt->tmp_template = strdup(tmp_template);
617 }
618 
619 void
620 iperf_set_test_reverse(struct iperf_test *ipt, int reverse)
621 {
622     ipt->reverse = reverse;
623     if (!ipt->reverse) {
624         if (ipt->role == 'c')
625             ipt->mode = SENDER;
626         else if (ipt->role == 's')
627             ipt->mode = RECEIVER;
628     } else {
629         if (ipt->role == 'c')
630             ipt->mode = RECEIVER;
631         else if (ipt->role == 's')
632             ipt->mode = SENDER;
633     }
634     check_sender_has_retransmits(ipt);
635 }
636 
637 void
638 iperf_set_test_json_output(struct iperf_test *ipt, int json_output)
639 {
640     ipt->json_output = json_output;
641 }
642 
643 int
644 iperf_has_zerocopy( void )
645 {
646     return has_sendfile();
647 }
648 
649 void
650 iperf_set_test_zerocopy(struct iperf_test *ipt, int zerocopy)
651 {
652     ipt->zerocopy = (zerocopy && has_sendfile());
653 }
654 
655 void
656 iperf_set_test_get_server_output(struct iperf_test *ipt, int get_server_output)
657 {
658     ipt->get_server_output = get_server_output;
659 }
660 
661 void
662 iperf_set_test_unit_format(struct iperf_test *ipt, char unit_format)
663 {
664     ipt->settings->unit_format = unit_format;
665 }
666 
667 #if defined(HAVE_SSL)
668 void
669 iperf_set_test_client_username(struct iperf_test *ipt, const char *client_username)
670 {
671     ipt->settings->client_username = strdup(client_username);
672 }
673 
674 void
675 iperf_set_test_client_password(struct iperf_test *ipt, const char *client_password)
676 {
677     ipt->settings->client_password = strdup(client_password);
678 }
679 
680 void
681 iperf_set_test_client_rsa_pubkey(struct iperf_test *ipt, const char *client_rsa_pubkey_base64)
682 {
683     ipt->settings->client_rsa_pubkey = load_pubkey_from_base64(client_rsa_pubkey_base64);
684 }
685 
686 void
687 iperf_set_test_server_authorized_users(struct iperf_test *ipt, const char *server_authorized_users)
688 {
689     ipt->server_authorized_users = strdup(server_authorized_users);
690 }
691 
692 void
693 iperf_set_test_server_skew_threshold(struct iperf_test *ipt, int server_skew_threshold)
694 {
695     ipt->server_skew_threshold = server_skew_threshold;
696 }
697 
698 void
699 iperf_set_test_server_rsa_privkey(struct iperf_test *ipt, const char *server_rsa_privkey_base64)
700 {
701     ipt->server_rsa_private_key = load_privkey_from_base64(server_rsa_privkey_base64);
702 }
703 #endif // HAVE_SSL
704 
705 void
706 iperf_set_test_bind_address(struct iperf_test *ipt, const char *bnd_address)
707 {
708     ipt->bind_address = strdup(bnd_address);
709 }
710 
711 void
712 iperf_set_test_bind_dev(struct iperf_test *ipt, char *bnd_dev)
713 {
714     ipt->bind_dev = strdup(bnd_dev);
715 }
716 
717 void
718 iperf_set_test_udp_counters_64bit(struct iperf_test *ipt, int udp_counters_64bit)
719 {
720     ipt->udp_counters_64bit = udp_counters_64bit;
721 }
722 
723 void
724 iperf_set_test_one_off(struct iperf_test *ipt, int one_off)
725 {
726     ipt->one_off = one_off;
727 }
728 
729 void
730 iperf_set_test_tos(struct iperf_test *ipt, int tos)
731 {
732     ipt->settings->tos = tos;
733 }
734 
735 void
736 iperf_set_test_extra_data(struct iperf_test *ipt, const char *dat)
737 {
738     ipt->extra_data = strdup(dat);
739 }
740 
741 void
742 iperf_set_test_bidirectional(struct iperf_test* ipt, int bidirectional)
743 {
744     ipt->bidirectional = bidirectional;
745     if (bidirectional)
746         ipt->mode = BIDIRECTIONAL;
747     else
748         iperf_set_test_reverse(ipt, ipt->reverse);
749 }
750 
751 void
752 iperf_set_test_no_delay(struct iperf_test* ipt, int no_delay)
753 {
754     ipt->no_delay = no_delay;
755 }
756 
757 void
758 iperf_set_test_connect_timeout(struct iperf_test* ipt, int ct)
759 {
760     ipt->settings->connect_timeout = ct;
761 }
762 
763 void
764 iperf_set_test_idle_timeout(struct iperf_test* ipt, int to)
765 {
766     ipt->settings->idle_timeout = to;
767 }
768 
769 void
770 iperf_set_dont_fragment(struct iperf_test* ipt, int dnf)
771 {
772     ipt->settings->dont_fragment = dnf;
773 }
774 
775 void
776 iperf_set_test_rcv_timeout(struct iperf_test* ipt, struct iperf_time* to)
777 {
778     ipt->settings->rcv_timeout.secs = to->secs;
779     ipt->settings->rcv_timeout.usecs = to->usecs;
780 }
781 
782 void
783 iperf_set_test_congestion_control(struct iperf_test* ipt, char* cc)
784 {
785     ipt->congestion = strdup(cc);
786 }
787 
788 void
789 iperf_set_test_mss(struct iperf_test *ipt, int mss)
790 {
791     ipt->settings->mss = mss;
792 }
793 
794 /********************** Get/set test protocol structure ***********************/
795 
796 struct protocol *
797 get_protocol(struct iperf_test *test, int prot_id)
798 {
799     struct protocol *prot;
800 
801     SLIST_FOREACH(prot, &test->protocols, protocols) {
802         if (prot->id == prot_id)
803             break;
804     }
805 
806     if (prot == NULL)
807         i_errno = IEPROTOCOL;
808 
809     return prot;
810 }
811 
812 int
813 set_protocol(struct iperf_test *test, int prot_id)
814 {
815     struct protocol *prot = NULL;
816 
817     SLIST_FOREACH(prot, &test->protocols, protocols) {
818         if (prot->id == prot_id) {
819             test->protocol = prot;
820 	    check_sender_has_retransmits(test);
821             return 0;
822         }
823     }
824 
825     i_errno = IEPROTOCOL;
826     return -1;
827 }
828 
829 
830 /************************** Iperf callback functions **************************/
831 
832 void
833 iperf_on_new_stream(struct iperf_stream *sp)
834 {
835     connect_msg(sp);
836 }
837 
838 void
839 iperf_on_test_start(struct iperf_test *test)
840 {
841     if (test->json_output) {
842 	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  tos: %d  target_bitrate: %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, (int64_t) test->settings->tos, (int64_t) test->settings->rate));
843     } else {
844 	if (test->verbose) {
845 	    if (test->settings->bytes)
846 		iperf_printf(test, test_start_bytes, test->protocol->name, test->num_streams, test->settings->blksize, test->omit, test->settings->bytes, test->settings->tos);
847 	    else if (test->settings->blocks)
848 		iperf_printf(test, test_start_blocks, test->protocol->name, test->num_streams, test->settings->blksize, test->omit, test->settings->blocks, test->settings->tos);
849 	    else
850 		iperf_printf(test, test_start_time, test->protocol->name, test->num_streams, test->settings->blksize, test->omit, test->duration, test->settings->tos);
851 	}
852     }
853 }
854 
855 /* This converts an IPv6 string address from IPv4-mapped format into regular
856 ** old IPv4 format, which is easier on the eyes of network veterans.
857 **
858 ** If the v6 address is not v4-mapped it is left alone.
859 */
860 static void
861 mapped_v4_to_regular_v4(char *str)
862 {
863     char *prefix = "::ffff:";
864     int prefix_len;
865 
866     prefix_len = strlen(prefix);
867     if (strncmp(str, prefix, prefix_len) == 0) {
868 	int str_len = strlen(str);
869 	memmove(str, str + prefix_len, str_len - prefix_len + 1);
870     }
871 }
872 
873 void
874 iperf_on_connect(struct iperf_test *test)
875 {
876     time_t now_secs;
877     const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S %Z";
878     char now_str[100];
879     char ipr[INET6_ADDRSTRLEN];
880     int port;
881     struct sockaddr_storage sa;
882     struct sockaddr_in *sa_inP;
883     struct sockaddr_in6 *sa_in6P;
884     socklen_t len;
885 
886     now_secs = time((time_t*) 0);
887     (void) strftime(now_str, sizeof(now_str), rfc1123_fmt, gmtime(&now_secs));
888     if (test->json_output)
889 	cJSON_AddItemToObject(test->json_start, "timestamp", iperf_json_printf("time: %s  timesecs: %d", now_str, (int64_t) now_secs));
890     else if (test->verbose)
891 	iperf_printf(test, report_time, now_str);
892 
893     if (test->role == 'c') {
894 	if (test->json_output)
895 	    cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s  port: %d", test->server_hostname, (int64_t) test->server_port));
896 	else {
897 	    iperf_printf(test, report_connecting, test->server_hostname, test->server_port);
898 	    if (test->reverse)
899 		iperf_printf(test, report_reverse, test->server_hostname);
900 	}
901     } else {
902         len = sizeof(sa);
903         getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len);
904         if (getsockdomain(test->ctrl_sck) == AF_INET) {
905 	    sa_inP = (struct sockaddr_in *) &sa;
906             inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr));
907 	    port = ntohs(sa_inP->sin_port);
908         } else {
909 	    sa_in6P = (struct sockaddr_in6 *) &sa;
910             inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr));
911 	    port = ntohs(sa_in6P->sin6_port);
912         }
913 	mapped_v4_to_regular_v4(ipr);
914 	if (test->json_output)
915 	    cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s  port: %d", ipr, (int64_t) port));
916 	else
917 	    iperf_printf(test, report_accepted, ipr, port);
918     }
919     if (test->json_output) {
920 	cJSON_AddStringToObject(test->json_start, "cookie", test->cookie);
921         if (test->protocol->id == SOCK_STREAM) {
922 	    if (test->settings->mss)
923 		cJSON_AddNumberToObject(test->json_start, "tcp_mss", test->settings->mss);
924 	    else {
925 		cJSON_AddNumberToObject(test->json_start, "tcp_mss_default", test->ctrl_sck_mss);
926 	    }
927         }
928         cJSON_AddNumberToObject(test->json_start, "target_bitrate", test->settings->rate);
929     } else if (test->verbose) {
930         iperf_printf(test, report_cookie, test->cookie);
931         if (test->protocol->id == SOCK_STREAM) {
932             if (test->settings->mss)
933                 iperf_printf(test, "      TCP MSS: %d\n", test->settings->mss);
934             else {
935                 iperf_printf(test, "      TCP MSS: %d (default)\n", test->ctrl_sck_mss);
936             }
937         }
938         if (test->settings->rate)
939             iperf_printf(test, "      Target Bitrate: %"PRIu64"\n", test->settings->rate);
940     }
941 }
942 
943 void
944 iperf_on_test_finish(struct iperf_test *test)
945 {
946 }
947 
948 
949 /******************************************************************************/
950 
951 /*
952  * iperf_parse_hostname tries to split apart a string into hostname %
953  * interface parts, which are returned in **p and **p1, if they
954  * exist. If the %interface part is detected, and it's not an IPv6
955  * link local address, then returns 1, else returns 0.
956  *
957  * Modifies the string pointed to by spec in-place due to the use of
958  * strtok(3). The caller should strdup(3) or otherwise copy the string
959  * if an unmodified copy is needed.
960  */
961 int
962 iperf_parse_hostname(struct iperf_test *test, char *spec, char **p, char **p1) {
963     struct in6_addr ipv6_addr;
964 
965     // Format is <addr>[%<device>]
966     if ((*p = strtok(spec, "%")) != NULL &&
967         (*p1 = strtok(NULL, "%")) != NULL) {
968 
969         /*
970          * If an IPv6 literal for a link-local address, then
971          * tell the caller to leave the "%" in the hostname.
972          */
973         if (inet_pton(AF_INET6, *p, &ipv6_addr) == 1 &&
974             IN6_IS_ADDR_LINKLOCAL(&ipv6_addr)) {
975             if (test->debug) {
976                 iperf_printf(test, "IPv6 link-local address literal detected\n");
977             }
978             return 0;
979         }
980         /*
981          * Other kind of address or FQDN. The interface name after
982          * "%" is a shorthand for --bind-dev.
983          */
984         else {
985             if (test->debug) {
986                 iperf_printf(test, "p %s p1 %s\n", *p, *p1);
987             }
988             return 1;
989         }
990     }
991     else {
992         if (test->debug) {
993             iperf_printf(test, "noparse\n");
994         }
995         return 0;
996     }
997 }
998 
999 int
1000 iperf_parse_arguments(struct iperf_test *test, int argc, char **argv)
1001 {
1002     static struct option longopts[] =
1003     {
1004         {"port", required_argument, NULL, 'p'},
1005         {"format", required_argument, NULL, 'f'},
1006         {"interval", required_argument, NULL, 'i'},
1007         {"daemon", no_argument, NULL, 'D'},
1008         {"one-off", no_argument, NULL, '1'},
1009         {"verbose", no_argument, NULL, 'V'},
1010         {"json", no_argument, NULL, 'J'},
1011         {"version", no_argument, NULL, 'v'},
1012         {"server", no_argument, NULL, 's'},
1013         {"client", required_argument, NULL, 'c'},
1014         {"udp", no_argument, NULL, 'u'},
1015         {"bitrate", required_argument, NULL, 'b'},
1016         {"bandwidth", required_argument, NULL, 'b'},
1017 	{"server-bitrate-limit", required_argument, NULL, OPT_SERVER_BITRATE_LIMIT},
1018         {"time", required_argument, NULL, 't'},
1019         {"bytes", required_argument, NULL, 'n'},
1020         {"blockcount", required_argument, NULL, 'k'},
1021         {"length", required_argument, NULL, 'l'},
1022         {"parallel", required_argument, NULL, 'P'},
1023         {"reverse", no_argument, NULL, 'R'},
1024         {"bidir", no_argument, NULL, OPT_BIDIRECTIONAL},
1025         {"window", required_argument, NULL, 'w'},
1026         {"bind", required_argument, NULL, 'B'},
1027 #if defined(HAVE_SO_BINDTODEVICE)
1028         {"bind-dev", required_argument, NULL, OPT_BIND_DEV},
1029 #endif /* HAVE_SO_BINDTODEVICE */
1030         {"cport", required_argument, NULL, OPT_CLIENT_PORT},
1031         {"set-mss", required_argument, NULL, 'M'},
1032         {"no-delay", no_argument, NULL, 'N'},
1033         {"version4", no_argument, NULL, '4'},
1034         {"version6", no_argument, NULL, '6'},
1035         {"tos", required_argument, NULL, 'S'},
1036         {"dscp", required_argument, NULL, OPT_DSCP},
1037 	{"extra-data", required_argument, NULL, OPT_EXTRA_DATA},
1038 #if defined(HAVE_FLOWLABEL)
1039         {"flowlabel", required_argument, NULL, 'L'},
1040 #endif /* HAVE_FLOWLABEL */
1041         {"zerocopy", no_argument, NULL, 'Z'},
1042         {"omit", required_argument, NULL, 'O'},
1043         {"file", required_argument, NULL, 'F'},
1044         {"repeating-payload", no_argument, NULL, OPT_REPEATING_PAYLOAD},
1045         {"timestamps", optional_argument, NULL, OPT_TIMESTAMPS},
1046 #if defined(HAVE_CPU_AFFINITY)
1047         {"affinity", required_argument, NULL, 'A'},
1048 #endif /* HAVE_CPU_AFFINITY */
1049         {"title", required_argument, NULL, 'T'},
1050 #if defined(HAVE_TCP_CONGESTION)
1051         {"congestion", required_argument, NULL, 'C'},
1052         {"linux-congestion", required_argument, NULL, 'C'},
1053 #endif /* HAVE_TCP_CONGESTION */
1054 #if defined(HAVE_SCTP_H)
1055         {"sctp", no_argument, NULL, OPT_SCTP},
1056         {"nstreams", required_argument, NULL, OPT_NUMSTREAMS},
1057         {"xbind", required_argument, NULL, 'X'},
1058 #endif
1059 	{"pidfile", required_argument, NULL, 'I'},
1060 	{"logfile", required_argument, NULL, OPT_LOGFILE},
1061 	{"forceflush", no_argument, NULL, OPT_FORCEFLUSH},
1062 	{"get-server-output", no_argument, NULL, OPT_GET_SERVER_OUTPUT},
1063 	{"udp-counters-64bit", no_argument, NULL, OPT_UDP_COUNTERS_64BIT},
1064  	{"no-fq-socket-pacing", no_argument, NULL, OPT_NO_FQ_SOCKET_PACING},
1065 #if defined(HAVE_DONT_FRAGMENT)
1066 	{"dont-fragment", no_argument, NULL, OPT_DONT_FRAGMENT},
1067 #endif /* HAVE_DONT_FRAGMENT */
1068 #if defined(HAVE_SSL)
1069     {"username", required_argument, NULL, OPT_CLIENT_USERNAME},
1070     {"rsa-public-key-path", required_argument, NULL, OPT_CLIENT_RSA_PUBLIC_KEY},
1071     {"rsa-private-key-path", required_argument, NULL, OPT_SERVER_RSA_PRIVATE_KEY},
1072     {"authorized-users-path", required_argument, NULL, OPT_SERVER_AUTHORIZED_USERS},
1073     {"time-skew-threshold", required_argument, NULL, OPT_SERVER_SKEW_THRESHOLD},
1074 #endif /* HAVE_SSL */
1075 	{"fq-rate", required_argument, NULL, OPT_FQ_RATE},
1076 	{"pacing-timer", required_argument, NULL, OPT_PACING_TIMER},
1077 	{"connect-timeout", required_argument, NULL, OPT_CONNECT_TIMEOUT},
1078         {"idle-timeout", required_argument, NULL, OPT_IDLE_TIMEOUT},
1079         {"rcv-timeout", required_argument, NULL, OPT_RCV_TIMEOUT},
1080         {"debug", no_argument, NULL, 'd'},
1081         {"help", no_argument, NULL, 'h'},
1082         {NULL, 0, NULL, 0}
1083     };
1084     int flag;
1085     int portno;
1086     int blksize;
1087     int server_flag, client_flag, rate_flag, duration_flag, rcv_timeout_flag;
1088     char *endptr;
1089 #if defined(HAVE_CPU_AFFINITY)
1090     char* comma;
1091 #endif /* HAVE_CPU_AFFINITY */
1092     char* slash;
1093     char *p, *p1;
1094     struct xbind_entry *xbe;
1095     double farg;
1096     int rcv_timeout_in = 0;
1097 
1098     blksize = 0;
1099     server_flag = client_flag = rate_flag = duration_flag = rcv_timeout_flag = 0;
1100 #if defined(HAVE_SSL)
1101     char *client_username = NULL, *client_rsa_public_key = NULL, *server_rsa_private_key = NULL;
1102 #endif /* HAVE_SSL */
1103 
1104     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) {
1105         switch (flag) {
1106             case 'p':
1107 		portno = atoi(optarg);
1108 		if (portno < 1 || portno > 65535) {
1109 		    i_errno = IEBADPORT;
1110 		    return -1;
1111 		}
1112 		test->server_port = portno;
1113                 break;
1114             case 'f':
1115 		if (!optarg) {
1116 		    i_errno = IEBADFORMAT;
1117 		    return -1;
1118 		}
1119 		test->settings->unit_format = *optarg;
1120 		if (test->settings->unit_format == 'k' ||
1121 		    test->settings->unit_format == 'K' ||
1122 		    test->settings->unit_format == 'm' ||
1123 		    test->settings->unit_format == 'M' ||
1124 		    test->settings->unit_format == 'g' ||
1125 		    test->settings->unit_format == 'G' ||
1126 		    test->settings->unit_format == 't' ||
1127 		    test->settings->unit_format == 'T') {
1128 			break;
1129 		}
1130 		else {
1131 		    i_errno = IEBADFORMAT;
1132 		    return -1;
1133 		}
1134                 break;
1135             case 'i':
1136                 /* XXX: could potentially want separate stat collection and reporting intervals,
1137                    but just set them to be the same for now */
1138                 test->stats_interval = test->reporter_interval = atof(optarg);
1139                 if ((test->stats_interval < MIN_INTERVAL || test->stats_interval > MAX_INTERVAL) && test->stats_interval != 0) {
1140                     i_errno = IEINTERVAL;
1141                     return -1;
1142                 }
1143                 break;
1144             case 'D':
1145 		test->daemon = 1;
1146 		server_flag = 1;
1147 	        break;
1148             case '1':
1149 		test->one_off = 1;
1150 		server_flag = 1;
1151 	        break;
1152             case 'V':
1153                 test->verbose = 1;
1154                 break;
1155             case 'J':
1156                 test->json_output = 1;
1157                 break;
1158             case 'v':
1159                 printf("%s (cJSON %s)\n%s\n%s\n", version, cJSON_Version(), get_system_info(),
1160 		       get_optional_features());
1161                 exit(0);
1162             case 's':
1163                 if (test->role == 'c') {
1164                     i_errno = IESERVCLIENT;
1165                     return -1;
1166                 }
1167 		iperf_set_test_role(test, 's');
1168                 break;
1169             case 'c':
1170                 if (test->role == 's') {
1171                     i_errno = IESERVCLIENT;
1172                     return -1;
1173                 }
1174 		iperf_set_test_role(test, 'c');
1175 		iperf_set_test_server_hostname(test, optarg);
1176 
1177                 if (iperf_parse_hostname(test, optarg, &p, &p1)) {
1178 #if defined(HAVE_SO_BINDTODEVICE)
1179                     /* Get rid of the hostname we saved earlier. */
1180                     free(iperf_get_test_server_hostname(test));
1181                     iperf_set_test_server_hostname(test, p);
1182                     iperf_set_test_bind_dev(test, p1);
1183 #else /* HAVE_SO_BINDTODEVICE */
1184                     i_errno = IEBINDDEVNOSUPPORT;
1185                     return -1;
1186 #endif /* HAVE_SO_BINDTODEVICE */
1187                 }
1188                 break;
1189             case 'u':
1190                 set_protocol(test, Pudp);
1191 		client_flag = 1;
1192                 break;
1193             case OPT_SCTP:
1194 #if defined(HAVE_SCTP_H)
1195                 set_protocol(test, Psctp);
1196                 client_flag = 1;
1197                 break;
1198 #else /* HAVE_SCTP_H */
1199                 i_errno = IEUNIMP;
1200                 return -1;
1201 #endif /* HAVE_SCTP_H */
1202 
1203             case OPT_NUMSTREAMS:
1204 #if defined(linux) || defined(__FreeBSD__)
1205                 test->settings->num_ostreams = unit_atoi(optarg);
1206                 client_flag = 1;
1207 #else /* linux */
1208                 i_errno = IEUNIMP;
1209                 return -1;
1210 #endif /* linux */
1211             case 'b':
1212 		slash = strchr(optarg, '/');
1213 		if (slash) {
1214 		    *slash = '\0';
1215 		    ++slash;
1216 		    test->settings->burst = atoi(slash);
1217 		    if (test->settings->burst <= 0 ||
1218 		        test->settings->burst > MAX_BURST) {
1219 			i_errno = IEBURST;
1220 			return -1;
1221 		    }
1222 		}
1223                 test->settings->rate = unit_atof_rate(optarg);
1224 		rate_flag = 1;
1225 		client_flag = 1;
1226                 break;
1227             case OPT_SERVER_BITRATE_LIMIT:
1228 		slash = strchr(optarg, '/');
1229 		if (slash) {
1230 		    *slash = '\0';
1231 		    ++slash;
1232 		    test->settings->bitrate_limit_interval = atof(slash);
1233 		    if (test->settings->bitrate_limit_interval != 0 &&	/* Using same Max/Min limits as for Stats Interval */
1234 		        (test->settings->bitrate_limit_interval < MIN_INTERVAL || test->settings->bitrate_limit_interval > MAX_INTERVAL) ) {
1235 			i_errno = IETOTALINTERVAL;
1236 			return -1;
1237 		    }
1238 		}
1239 		test->settings->bitrate_limit = unit_atof_rate(optarg);
1240 		server_flag = 1;
1241 	        break;
1242             case 't':
1243                 test->duration = atoi(optarg);
1244                 if (test->duration > MAX_TIME) {
1245                     i_errno = IEDURATION;
1246                     return -1;
1247                 }
1248 		duration_flag = 1;
1249 		client_flag = 1;
1250                 break;
1251             case 'n':
1252                 test->settings->bytes = unit_atoi(optarg);
1253 		client_flag = 1;
1254                 break;
1255             case 'k':
1256                 test->settings->blocks = unit_atoi(optarg);
1257 		client_flag = 1;
1258                 break;
1259             case 'l':
1260                 blksize = unit_atoi(optarg);
1261 		client_flag = 1;
1262                 break;
1263             case 'P':
1264                 test->num_streams = atoi(optarg);
1265                 if (test->num_streams > MAX_STREAMS) {
1266                     i_errno = IENUMSTREAMS;
1267                     return -1;
1268                 }
1269 		client_flag = 1;
1270                 break;
1271             case 'R':
1272                 if (test->bidirectional) {
1273                     i_errno = IEREVERSEBIDIR;
1274                     return -1;
1275                 }
1276 		iperf_set_test_reverse(test, 1);
1277 		client_flag = 1;
1278                 break;
1279             case OPT_BIDIRECTIONAL:
1280                 if (test->reverse) {
1281                     i_errno = IEREVERSEBIDIR;
1282                     return -1;
1283                 }
1284                 iperf_set_test_bidirectional(test, 1);
1285                 client_flag = 1;
1286                 break;
1287             case 'w':
1288                 // XXX: This is a socket buffer, not specific to TCP
1289 		// Do sanity checks as double-precision floating point
1290 		// to avoid possible integer overflows.
1291                 farg = unit_atof(optarg);
1292                 if (farg > (double) MAX_TCP_BUFFER) {
1293                     i_errno = IEBUFSIZE;
1294                     return -1;
1295                 }
1296                 test->settings->socket_bufsize = (int) farg;
1297 		client_flag = 1;
1298                 break;
1299 
1300             case 'B':
1301                 iperf_set_test_bind_address(test, optarg);
1302 
1303                 if (iperf_parse_hostname(test, optarg, &p, &p1)) {
1304 #if defined(HAVE_SO_BINDTODEVICE)
1305                     /* Get rid of the hostname we saved earlier. */
1306                     free(iperf_get_test_server_hostname(test));
1307                     iperf_set_test_server_hostname(test, p);
1308                     iperf_set_test_bind_dev(test, p1);
1309 #else /* HAVE_SO_BINDTODEVICE */
1310                     i_errno = IEBINDDEVNOSUPPORT;
1311                     return -1;
1312 #endif /* HAVE_SO_BINDTODEVICE */
1313                 }
1314                 break;
1315 #if defined (HAVE_SO_BINDTODEVICE)
1316             case OPT_BIND_DEV:
1317                 iperf_set_test_bind_dev(test, optarg);
1318                 break;
1319 #endif /* HAVE_SO_BINDTODEVICE */
1320             case OPT_CLIENT_PORT:
1321 		portno = atoi(optarg);
1322 		if (portno < 1 || portno > 65535) {
1323 		    i_errno = IEBADPORT;
1324 		    return -1;
1325 		}
1326                 test->bind_port = portno;
1327                 break;
1328             case 'M':
1329                 test->settings->mss = atoi(optarg);
1330                 if (test->settings->mss > MAX_MSS) {
1331                     i_errno = IEMSS;
1332                     return -1;
1333                 }
1334 		client_flag = 1;
1335                 break;
1336             case 'N':
1337                 test->no_delay = 1;
1338 		client_flag = 1;
1339                 break;
1340             case '4':
1341                 test->settings->domain = AF_INET;
1342                 break;
1343             case '6':
1344                 test->settings->domain = AF_INET6;
1345                 break;
1346             case 'S':
1347                 test->settings->tos = strtol(optarg, &endptr, 0);
1348 		if (endptr == optarg ||
1349 		    test->settings->tos < 0 ||
1350 		    test->settings->tos > 255) {
1351 		    i_errno = IEBADTOS;
1352 		    return -1;
1353 		}
1354 		client_flag = 1;
1355                 break;
1356 	    case OPT_DSCP:
1357                 test->settings->tos = parse_qos(optarg);
1358 		if(test->settings->tos < 0) {
1359 			i_errno = IEBADTOS;
1360 			return -1;
1361 		}
1362 		client_flag = 1;
1363                 break;
1364 	    case OPT_EXTRA_DATA:
1365 		test->extra_data = strdup(optarg);
1366 		client_flag = 1;
1367 	        break;
1368             case 'L':
1369 #if defined(HAVE_FLOWLABEL)
1370                 test->settings->flowlabel = strtol(optarg, &endptr, 0);
1371 		if (endptr == optarg ||
1372 		    test->settings->flowlabel < 1 || test->settings->flowlabel > 0xfffff) {
1373                     i_errno = IESETFLOW;
1374                     return -1;
1375 		}
1376 		client_flag = 1;
1377 #else /* HAVE_FLOWLABEL */
1378                 i_errno = IEUNIMP;
1379                 return -1;
1380 #endif /* HAVE_FLOWLABEL */
1381                 break;
1382             case 'X':
1383 		xbe = (struct xbind_entry *)malloc(sizeof(struct xbind_entry));
1384                 if (!xbe) {
1385 		    i_errno = IESETSCTPBINDX;
1386                     return -1;
1387                 }
1388 	        memset(xbe, 0, sizeof(*xbe));
1389                 xbe->name = strdup(optarg);
1390                 if (!xbe->name) {
1391 		    i_errno = IESETSCTPBINDX;
1392                     return -1;
1393                 }
1394 		TAILQ_INSERT_TAIL(&test->xbind_addrs, xbe, link);
1395                 break;
1396             case 'Z':
1397                 if (!has_sendfile()) {
1398                     i_errno = IENOSENDFILE;
1399                     return -1;
1400                 }
1401                 test->zerocopy = 1;
1402 		client_flag = 1;
1403                 break;
1404             case OPT_REPEATING_PAYLOAD:
1405                 test->repeating_payload = 1;
1406                 client_flag = 1;
1407                 break;
1408             case OPT_TIMESTAMPS:
1409                 iperf_set_test_timestamps(test, 1);
1410 		if (optarg) {
1411 		    iperf_set_test_timestamp_format(test, optarg);
1412 		}
1413 		else {
1414 		    iperf_set_test_timestamp_format(test, TIMESTAMP_FORMAT);
1415 		}
1416                 break;
1417             case 'O':
1418                 test->omit = atoi(optarg);
1419                 if (test->omit < 0 || test->omit > 60) {
1420                     i_errno = IEOMIT;
1421                     return -1;
1422                 }
1423 		client_flag = 1;
1424                 break;
1425             case 'F':
1426                 test->diskfile_name = optarg;
1427                 break;
1428             case OPT_IDLE_TIMEOUT:
1429                 test->settings->idle_timeout = atoi(optarg);
1430                 if (test->settings->idle_timeout < 1 || test->settings->idle_timeout > MAX_TIME) {
1431                     i_errno = IEIDLETIMEOUT;
1432                     return -1;
1433                 }
1434 		server_flag = 1;
1435 	        break;
1436             case OPT_RCV_TIMEOUT:
1437                 rcv_timeout_in = atoi(optarg);
1438                 if (rcv_timeout_in < MIN_NO_MSG_RCVD_TIMEOUT || rcv_timeout_in > MAX_TIME * SEC_TO_mS) {
1439                     i_errno = IERCVTIMEOUT;
1440                     return -1;
1441                 }
1442                 test->settings->rcv_timeout.secs = rcv_timeout_in / SEC_TO_mS;
1443                 test->settings->rcv_timeout.usecs = (rcv_timeout_in % SEC_TO_mS) * mS_TO_US;
1444                 rcv_timeout_flag = 1;
1445 	        break;
1446             case 'A':
1447 #if defined(HAVE_CPU_AFFINITY)
1448                 test->affinity = strtol(optarg, &endptr, 0);
1449                 if (endptr == optarg ||
1450 		    test->affinity < 0 || test->affinity > 1024) {
1451                     i_errno = IEAFFINITY;
1452                     return -1;
1453                 }
1454 		comma = strchr(optarg, ',');
1455 		if (comma != NULL) {
1456 		    test->server_affinity = atoi(comma+1);
1457 		    if (test->server_affinity < 0 || test->server_affinity > 1024) {
1458 			i_errno = IEAFFINITY;
1459 			return -1;
1460 		    }
1461 		    client_flag = 1;
1462 		}
1463 #else /* HAVE_CPU_AFFINITY */
1464                 i_errno = IEUNIMP;
1465                 return -1;
1466 #endif /* HAVE_CPU_AFFINITY */
1467                 break;
1468             case 'T':
1469                 test->title = strdup(optarg);
1470 		client_flag = 1;
1471                 break;
1472 	    case 'C':
1473 #if defined(HAVE_TCP_CONGESTION)
1474 		test->congestion = strdup(optarg);
1475 		client_flag = 1;
1476 #else /* HAVE_TCP_CONGESTION */
1477 		i_errno = IEUNIMP;
1478 		return -1;
1479 #endif /* HAVE_TCP_CONGESTION */
1480 		break;
1481 	    case 'd':
1482 		test->debug = 1;
1483 		break;
1484 	    case 'I':
1485 		test->pidfile = strdup(optarg);
1486 	        break;
1487 	    case OPT_LOGFILE:
1488 		test->logfile = strdup(optarg);
1489 		break;
1490 	    case OPT_FORCEFLUSH:
1491 		test->forceflush = 1;
1492 		break;
1493 	    case OPT_GET_SERVER_OUTPUT:
1494 		test->get_server_output = 1;
1495 		client_flag = 1;
1496 		break;
1497 	    case OPT_UDP_COUNTERS_64BIT:
1498 		test->udp_counters_64bit = 1;
1499 		break;
1500 	    case OPT_NO_FQ_SOCKET_PACING:
1501 #if defined(HAVE_SO_MAX_PACING_RATE)
1502 		printf("Warning:  --no-fq-socket-pacing is deprecated\n");
1503 		test->settings->fqrate = 0;
1504 		client_flag = 1;
1505 #else /* HAVE_SO_MAX_PACING_RATE */
1506 		i_errno = IEUNIMP;
1507 		return -1;
1508 #endif
1509 		break;
1510 	    case OPT_FQ_RATE:
1511 #if defined(HAVE_SO_MAX_PACING_RATE)
1512 		test->settings->fqrate = unit_atof_rate(optarg);
1513 		client_flag = 1;
1514 #else /* HAVE_SO_MAX_PACING_RATE */
1515 		i_errno = IEUNIMP;
1516 		return -1;
1517 #endif
1518 		break;
1519 #if defined(HAVE_DONT_FRAGMENT)
1520         case OPT_DONT_FRAGMENT:
1521             test->settings->dont_fragment = 1;
1522             client_flag = 1;
1523             break;
1524 #endif /* HAVE_DONT_FRAGMENT */
1525 #if defined(HAVE_SSL)
1526         case OPT_CLIENT_USERNAME:
1527             client_username = strdup(optarg);
1528             break;
1529         case OPT_CLIENT_RSA_PUBLIC_KEY:
1530             client_rsa_public_key = strdup(optarg);
1531             break;
1532         case OPT_SERVER_RSA_PRIVATE_KEY:
1533             server_rsa_private_key = strdup(optarg);
1534             break;
1535         case OPT_SERVER_AUTHORIZED_USERS:
1536             test->server_authorized_users = strdup(optarg);
1537             break;
1538         case OPT_SERVER_SKEW_THRESHOLD:
1539             test->server_skew_threshold = atoi(optarg);
1540             if(test->server_skew_threshold <= 0){
1541                 i_errno = IESKEWTHRESHOLD;
1542                 return -1;
1543             }
1544             break;
1545 #endif /* HAVE_SSL */
1546 	    case OPT_PACING_TIMER:
1547 		test->settings->pacing_timer = unit_atoi(optarg);
1548 		client_flag = 1;
1549 		break;
1550 	    case OPT_CONNECT_TIMEOUT:
1551 		test->settings->connect_timeout = unit_atoi(optarg);
1552 		client_flag = 1;
1553 		break;
1554 	    case 'h':
1555 		usage_long(stdout);
1556 		exit(0);
1557             default:
1558                 usage_long(stderr);
1559                 exit(1);
1560         }
1561     }
1562 
1563     /* Check flag / role compatibility. */
1564     if (test->role == 'c' && server_flag) {
1565         i_errno = IESERVERONLY;
1566         return -1;
1567     }
1568     if (test->role == 's' && client_flag) {
1569         i_errno = IECLIENTONLY;
1570         return -1;
1571     }
1572 
1573 #if defined(HAVE_SSL)
1574 
1575     if (test->role == 's' && (client_username || client_rsa_public_key)){
1576         i_errno = IECLIENTONLY;
1577         return -1;
1578     } else if (test->role == 'c' && (client_username || client_rsa_public_key) &&
1579         !(client_username && client_rsa_public_key)) {
1580         i_errno = IESETCLIENTAUTH;
1581         return -1;
1582     } else if (test->role == 'c' && (client_username && client_rsa_public_key)){
1583 
1584         char *client_password = NULL;
1585         size_t s;
1586         /* Need to copy env var, so we can do a common free */
1587         if ((client_password = getenv("IPERF3_PASSWORD")) != NULL)
1588              client_password = strdup(client_password);
1589         else if (iperf_getpass(&client_password, &s, stdin) < 0){
1590             i_errno = IESETCLIENTAUTH;
1591             return -1;
1592         }
1593         if (test_load_pubkey_from_file(client_rsa_public_key) < 0){
1594             iperf_err(test, "%s\n", ERR_error_string(ERR_get_error(), NULL));
1595             i_errno = IESETCLIENTAUTH;
1596             return -1;
1597         }
1598 
1599         test->settings->client_username = client_username;
1600         test->settings->client_password = client_password;
1601         test->settings->client_rsa_pubkey = load_pubkey_from_file(client_rsa_public_key);
1602 	free(client_rsa_public_key);
1603 	client_rsa_public_key = NULL;
1604     }
1605 
1606     if (test->role == 'c' && (server_rsa_private_key || test->server_authorized_users)){
1607         i_errno = IESERVERONLY;
1608         return -1;
1609     } else if (test->role == 'c' && (test->server_skew_threshold != 0)){
1610         i_errno = IESERVERONLY;
1611         return -1;
1612     } else if (test->role == 'c' && rcv_timeout_flag && test->mode == SENDER){
1613         i_errno = IERVRSONLYRCVTIMEOUT;
1614         return -1;
1615     } else if (test->role == 's' && (server_rsa_private_key || test->server_authorized_users) &&
1616         !(server_rsa_private_key && test->server_authorized_users)) {
1617          i_errno = IESETSERVERAUTH;
1618         return -1;
1619     } else if (test->role == 's' && server_rsa_private_key) {
1620         test->server_rsa_private_key = load_privkey_from_file(server_rsa_private_key);
1621         if (test->server_rsa_private_key == NULL){
1622             iperf_err(test, "%s\n", ERR_error_string(ERR_get_error(), NULL));
1623             i_errno = IESETSERVERAUTH;
1624             return -1;
1625         }
1626 	    free(server_rsa_private_key);
1627 	    server_rsa_private_key = NULL;
1628 
1629         if(test->server_skew_threshold == 0){
1630             // Set default value for time skew threshold
1631             test->server_skew_threshold=10;
1632         }
1633     }
1634 
1635 #endif //HAVE_SSL
1636     if (blksize == 0) {
1637 	if (test->protocol->id == Pudp)
1638 	    blksize = 0;	/* try to dynamically determine from MSS */
1639 	else if (test->protocol->id == Psctp)
1640 	    blksize = DEFAULT_SCTP_BLKSIZE;
1641 	else
1642 	    blksize = DEFAULT_TCP_BLKSIZE;
1643     }
1644     if ((test->protocol->id != Pudp && blksize <= 0)
1645 	|| blksize > MAX_BLOCKSIZE) {
1646 	i_errno = IEBLOCKSIZE;
1647 	return -1;
1648     }
1649     if (test->protocol->id == Pudp &&
1650 	(blksize > 0 &&
1651 	    (blksize < MIN_UDP_BLOCKSIZE || blksize > MAX_UDP_BLOCKSIZE))) {
1652 	i_errno = IEUDPBLOCKSIZE;
1653 	return -1;
1654     }
1655     test->settings->blksize = blksize;
1656 
1657     if (!rate_flag)
1658 	test->settings->rate = test->protocol->id == Pudp ? UDP_RATE : 0;
1659 
1660     /* if no bytes or blocks specified, nor a duration_flag, and we have -F,
1661     ** get the file-size as the bytes count to be transferred
1662     */
1663     if (test->settings->bytes == 0 &&
1664         test->settings->blocks == 0 &&
1665         ! duration_flag &&
1666         test->diskfile_name != (char*) 0 &&
1667         test->role == 'c'
1668         ){
1669         struct stat st;
1670         if( stat(test->diskfile_name, &st) == 0 ){
1671             iperf_size_t file_bytes = st.st_size;
1672             test->settings->bytes = file_bytes;
1673             if (test->debug)
1674                 printf("End condition set to file-size: %"PRIu64" bytes\n", test->settings->bytes);
1675         }
1676         // if failing to read file stat, it should fallback to default duration mode
1677     }
1678 
1679     if ((test->settings->bytes != 0 || test->settings->blocks != 0) && ! duration_flag)
1680         test->duration = 0;
1681 
1682     /* Disallow specifying multiple test end conditions. The code actually
1683     ** works just fine without this prohibition. As soon as any one of the
1684     ** three possible end conditions is met, the test ends. So this check
1685     ** could be removed if desired.
1686     */
1687     if ((duration_flag && test->settings->bytes != 0) ||
1688         (duration_flag && test->settings->blocks != 0) ||
1689 	(test->settings->bytes != 0 && test->settings->blocks != 0)) {
1690         i_errno = IEENDCONDITIONS;
1691         return -1;
1692     }
1693 
1694     /* For subsequent calls to getopt */
1695 #ifdef __APPLE__
1696     optreset = 1;
1697 #endif
1698     optind = 0;
1699 
1700     if ((test->role != 'c') && (test->role != 's')) {
1701         i_errno = IENOROLE;
1702         return -1;
1703     }
1704 
1705     /* Set Total-rate average interval to multiplicity of State interval */
1706     if (test->settings->bitrate_limit_interval != 0) {
1707 	test->settings->bitrate_limit_stats_per_interval =
1708 	    (test->settings->bitrate_limit_interval <= test->stats_interval ?
1709 	    1 : round(test->settings->bitrate_limit_interval/test->stats_interval) );
1710     }
1711 
1712     /* Show warning if JSON output is used with explicit report format */
1713     if ((test->json_output) && (test->settings->unit_format != 'a')) {
1714         warning("Report format (-f) flag ignored with JSON output (-J)");
1715     }
1716 
1717     /* Show warning if JSON output is used with verbose or debug flags */
1718     if (test->json_output && test->verbose) {
1719         warning("Verbose output (-v) may interfere with JSON output (-J)");
1720     }
1721     if (test->json_output && test->debug) {
1722         warning("Debug output (-d) may interfere with JSON output (-J)");
1723     }
1724 
1725     return 0;
1726 }
1727 
1728 /*
1729  * Open the file specified by test->logfile and set test->outfile to its' FD.
1730  */
1731 int iperf_open_logfile(struct iperf_test *test)
1732 {
1733     test->outfile = fopen(test->logfile, "a+");
1734     if (test->outfile == NULL) {
1735         i_errno = IELOGFILE;
1736         return -1;
1737     }
1738 
1739     return 0;
1740 }
1741 
1742 int
1743 iperf_set_send_state(struct iperf_test *test, signed char state)
1744 {
1745     if (test->ctrl_sck >= 0) {
1746         test->state = state;
1747         if (Nwrite(test->ctrl_sck, (char*) &state, sizeof(state), Ptcp) < 0) {
1748 	    i_errno = IESENDMESSAGE;
1749 	    return -1;
1750         }
1751     }
1752     return 0;
1753 }
1754 
1755 void
1756 iperf_check_throttle(struct iperf_stream *sp, struct iperf_time *nowP)
1757 {
1758     struct iperf_time temp_time;
1759     double seconds;
1760     uint64_t bits_per_second;
1761 
1762     if (sp->test->done || sp->test->settings->rate == 0)
1763         return;
1764     iperf_time_diff(&sp->result->start_time_fixed, nowP, &temp_time);
1765     seconds = iperf_time_in_secs(&temp_time);
1766     bits_per_second = sp->result->bytes_sent * 8 / seconds;
1767     if (bits_per_second < sp->test->settings->rate) {
1768         sp->green_light = 1;
1769         FD_SET(sp->socket, &sp->test->write_set);
1770     } else {
1771         sp->green_light = 0;
1772         FD_CLR(sp->socket, &sp->test->write_set);
1773     }
1774 }
1775 
1776 /* Verify that average traffic is not greater than the specified limit */
1777 void
1778 iperf_check_total_rate(struct iperf_test *test, iperf_size_t last_interval_bytes_transferred)
1779 {
1780     double seconds;
1781     uint64_t bits_per_second;
1782     iperf_size_t total_bytes;
1783     int i;
1784 
1785     if (test->done || test->settings->bitrate_limit == 0)    // Continue only if check should be done
1786         return;
1787 
1788     /* Add last inetrval's transferred bytes to the array */
1789     if (++test->bitrate_limit_last_interval_index >= test->settings->bitrate_limit_stats_per_interval)
1790         test->bitrate_limit_last_interval_index = 0;
1791     test->bitrate_limit_intervals_traffic_bytes[test->bitrate_limit_last_interval_index] = last_interval_bytes_transferred;
1792 
1793     /* Ensure that enough stats periods passed to allow averaging throughput */
1794     test->bitrate_limit_stats_count += 1;
1795     if (test->bitrate_limit_stats_count < test->settings->bitrate_limit_stats_per_interval)
1796         return;
1797 
1798      /* Calculating total bytes traffic to be averaged */
1799     for (total_bytes = 0, i = 0; i < test->settings->bitrate_limit_stats_per_interval; i++) {
1800         total_bytes += test->bitrate_limit_intervals_traffic_bytes[i];
1801     }
1802 
1803     seconds = test->stats_interval * test->settings->bitrate_limit_stats_per_interval;
1804     bits_per_second = total_bytes * 8 / seconds;
1805     if (test->debug) {
1806         iperf_printf(test,"Interval %" PRIu64 " - throughput %" PRIu64 " bps (limit %" PRIu64 ")\n", test->bitrate_limit_stats_count, bits_per_second, test->settings->bitrate_limit);
1807     }
1808 
1809     if (bits_per_second  > test->settings->bitrate_limit) {
1810         if (iperf_get_verbose(test))
1811             iperf_err(test, "Total throughput of %" PRIu64 " bps exceeded %" PRIu64 " bps limit", bits_per_second, test->settings->bitrate_limit);
1812 	test->bitrate_limit_exceeded = 1;
1813     }
1814 }
1815 
1816 int
1817 iperf_send(struct iperf_test *test, fd_set *write_setP)
1818 {
1819     register int multisend, r, streams_active;
1820     register struct iperf_stream *sp;
1821     struct iperf_time now;
1822     int no_throttle_check;
1823 
1824     /* Can we do multisend mode? */
1825     if (test->settings->burst != 0)
1826         multisend = test->settings->burst;
1827     else if (test->settings->rate == 0)
1828         multisend = test->multisend;
1829     else
1830         multisend = 1;	/* nope */
1831 
1832     /* Should bitrate throttle be checked for every send */
1833     no_throttle_check = test->settings->rate != 0 && test->settings->burst == 0;
1834 
1835     for (; multisend > 0; --multisend) {
1836 	if (no_throttle_check)
1837 	    iperf_time_now(&now);
1838 	streams_active = 0;
1839 	SLIST_FOREACH(sp, &test->streams, streams) {
1840 	    if ((sp->green_light && sp->sender &&
1841 		 (write_setP == NULL || FD_ISSET(sp->socket, write_setP)))) {
1842         if (multisend > 1 && test->settings->bytes != 0 && test->bytes_sent >= test->settings->bytes)
1843             break;
1844         if (multisend > 1 && test->settings->blocks != 0 && test->blocks_sent >= test->settings->blocks)
1845             break;
1846 		if ((r = sp->snd(sp)) < 0) {
1847 		    if (r == NET_SOFTERROR)
1848 			break;
1849 		    i_errno = IESTREAMWRITE;
1850 		    return r;
1851 		}
1852 		streams_active = 1;
1853 		test->bytes_sent += r;
1854 		if (!sp->pending_size)
1855 		    ++test->blocks_sent;
1856                 if (no_throttle_check)
1857 		    iperf_check_throttle(sp, &now);
1858 	    }
1859 	}
1860 	if (!streams_active)
1861 	    break;
1862     }
1863     if (!no_throttle_check) {   /* Throttle check if was not checked for each send */
1864 	iperf_time_now(&now);
1865 	SLIST_FOREACH(sp, &test->streams, streams)
1866 	    if (sp->sender)
1867 	        iperf_check_throttle(sp, &now);
1868     }
1869     if (write_setP != NULL)
1870 	SLIST_FOREACH(sp, &test->streams, streams)
1871 	    if (FD_ISSET(sp->socket, write_setP))
1872 		FD_CLR(sp->socket, write_setP);
1873 
1874     return 0;
1875 }
1876 
1877 int
1878 iperf_recv(struct iperf_test *test, fd_set *read_setP)
1879 {
1880     int r;
1881     struct iperf_stream *sp;
1882 
1883     SLIST_FOREACH(sp, &test->streams, streams) {
1884 	if (FD_ISSET(sp->socket, read_setP) && !sp->sender) {
1885 	    if ((r = sp->rcv(sp)) < 0) {
1886 		i_errno = IESTREAMREAD;
1887 		return r;
1888 	    }
1889 	    test->bytes_received += r;
1890 	    ++test->blocks_received;
1891 	    FD_CLR(sp->socket, read_setP);
1892 	}
1893     }
1894 
1895     return 0;
1896 }
1897 
1898 int
1899 iperf_init_test(struct iperf_test *test)
1900 {
1901     struct iperf_time now;
1902     struct iperf_stream *sp;
1903 
1904     if (test->protocol->init) {
1905         if (test->protocol->init(test) < 0)
1906             return -1;
1907     }
1908 
1909     /* Init each stream. */
1910     if (iperf_time_now(&now) < 0) {
1911 	i_errno = IEINITTEST;
1912 	return -1;
1913     }
1914     SLIST_FOREACH(sp, &test->streams, streams) {
1915 	sp->result->start_time = sp->result->start_time_fixed = now;
1916     }
1917 
1918     if (test->on_test_start)
1919         test->on_test_start(test);
1920 
1921     return 0;
1922 }
1923 
1924 static void
1925 send_timer_proc(TimerClientData client_data, struct iperf_time *nowP)
1926 {
1927     struct iperf_stream *sp = client_data.p;
1928 
1929     /* All we do here is set or clear the flag saying that this stream may
1930     ** be sent to.  The actual sending gets done in the send proc, after
1931     ** checking the flag.
1932     */
1933     iperf_check_throttle(sp, nowP);
1934 }
1935 
1936 int
1937 iperf_create_send_timers(struct iperf_test * test)
1938 {
1939     struct iperf_time now;
1940     struct iperf_stream *sp;
1941     TimerClientData cd;
1942 
1943     if (iperf_time_now(&now) < 0) {
1944 	i_errno = IEINITTEST;
1945 	return -1;
1946     }
1947     SLIST_FOREACH(sp, &test->streams, streams) {
1948         sp->green_light = 1;
1949 	if (test->settings->rate != 0 && sp->sender) {
1950 	    cd.p = sp;
1951 	    sp->send_timer = tmr_create(NULL, send_timer_proc, cd, test->settings->pacing_timer, 1);
1952 	    if (sp->send_timer == NULL) {
1953 		i_errno = IEINITTEST;
1954 		return -1;
1955 	    }
1956 	}
1957     }
1958     return 0;
1959 }
1960 
1961 #if defined(HAVE_SSL)
1962 int test_is_authorized(struct iperf_test *test){
1963     if ( !(test->server_rsa_private_key && test->server_authorized_users)) {
1964         return 0;
1965     }
1966 
1967     if (test->settings->authtoken){
1968         char *username = NULL, *password = NULL;
1969         time_t ts;
1970         int rc = decode_auth_setting(test->debug, test->settings->authtoken, test->server_rsa_private_key, &username, &password, &ts);
1971 	if (rc) {
1972 	    return -1;
1973 	}
1974         int ret = check_authentication(username, password, ts, test->server_authorized_users, test->server_skew_threshold);
1975         if (ret == 0){
1976             if (test->debug) {
1977               iperf_printf(test, report_authentication_succeeded, username, ts);
1978             }
1979             free(username);
1980             free(password);
1981             return 0;
1982         } else {
1983             if (test->debug) {
1984                 iperf_printf(test, report_authentication_failed, username, ts);
1985             }
1986             free(username);
1987             free(password);
1988             return -1;
1989         }
1990     }
1991     return -1;
1992 }
1993 #endif //HAVE_SSL
1994 
1995 /**
1996  * iperf_exchange_parameters - handles the param_Exchange part for client
1997  *
1998  */
1999 
2000 int
2001 iperf_exchange_parameters(struct iperf_test *test)
2002 {
2003     int s;
2004     int32_t err;
2005 
2006     if (test->role == 'c') {
2007 
2008         if (send_parameters(test) < 0)
2009             return -1;
2010 
2011     } else {
2012 
2013         if (get_parameters(test) < 0)
2014             return -1;
2015 
2016 #if defined(HAVE_SSL)
2017         if (test_is_authorized(test) < 0){
2018             if (iperf_set_send_state(test, SERVER_ERROR) != 0)
2019                 return -1;
2020             i_errno = IEAUTHTEST;
2021             err = htonl(i_errno);
2022             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
2023                 i_errno = IECTRLWRITE;
2024                 return -1;
2025             }
2026             return -1;
2027         }
2028 #endif //HAVE_SSL
2029 
2030         if ((s = test->protocol->listen(test)) < 0) {
2031 	        if (iperf_set_send_state(test, SERVER_ERROR) != 0)
2032                 return -1;
2033             err = htonl(i_errno);
2034             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
2035                 i_errno = IECTRLWRITE;
2036                 return -1;
2037             }
2038             err = htonl(errno);
2039             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
2040                 i_errno = IECTRLWRITE;
2041                 return -1;
2042             }
2043             return -1;
2044         }
2045 
2046         FD_SET(s, &test->read_set);
2047         test->max_fd = (s > test->max_fd) ? s : test->max_fd;
2048         test->prot_listener = s;
2049 
2050         // Send the control message to create streams and start the test
2051 	if (iperf_set_send_state(test, CREATE_STREAMS) != 0)
2052             return -1;
2053 
2054     }
2055 
2056     return 0;
2057 }
2058 
2059 /*************************************************************/
2060 
2061 int
2062 iperf_exchange_results(struct iperf_test *test)
2063 {
2064     if (test->role == 'c') {
2065         /* Send results to server. */
2066 	if (send_results(test) < 0)
2067             return -1;
2068         /* Get server results. */
2069         if (get_results(test) < 0)
2070             return -1;
2071     } else {
2072         /* Get client results. */
2073         if (get_results(test) < 0)
2074             return -1;
2075         /* Send results to client. */
2076 	if (send_results(test) < 0)
2077             return -1;
2078     }
2079     return 0;
2080 }
2081 
2082 /*************************************************************/
2083 
2084 static int
2085 send_parameters(struct iperf_test *test)
2086 {
2087     int r = 0;
2088     cJSON *j;
2089 
2090     j = cJSON_CreateObject();
2091     if (j == NULL) {
2092 	i_errno = IESENDPARAMS;
2093 	r = -1;
2094     } else {
2095 	if (test->protocol->id == Ptcp)
2096 	    cJSON_AddTrueToObject(j, "tcp");
2097 	else if (test->protocol->id == Pudp)
2098 	    cJSON_AddTrueToObject(j, "udp");
2099         else if (test->protocol->id == Psctp)
2100             cJSON_AddTrueToObject(j, "sctp");
2101 	cJSON_AddNumberToObject(j, "omit", test->omit);
2102 	if (test->server_affinity != -1)
2103 	    cJSON_AddNumberToObject(j, "server_affinity", test->server_affinity);
2104 	cJSON_AddNumberToObject(j, "time", test->duration);
2105 	if (test->settings->bytes)
2106 	    cJSON_AddNumberToObject(j, "num", test->settings->bytes);
2107 	if (test->settings->blocks)
2108 	    cJSON_AddNumberToObject(j, "blockcount", test->settings->blocks);
2109 	if (test->settings->mss)
2110 	    cJSON_AddNumberToObject(j, "MSS", test->settings->mss);
2111 	if (test->no_delay)
2112 	    cJSON_AddTrueToObject(j, "nodelay");
2113 	cJSON_AddNumberToObject(j, "parallel", test->num_streams);
2114 	if (test->reverse)
2115 	    cJSON_AddTrueToObject(j, "reverse");
2116 	if (test->bidirectional)
2117 	            cJSON_AddTrueToObject(j, "bidirectional");
2118 	if (test->settings->socket_bufsize)
2119 	    cJSON_AddNumberToObject(j, "window", test->settings->socket_bufsize);
2120 	if (test->settings->blksize)
2121 	    cJSON_AddNumberToObject(j, "len", test->settings->blksize);
2122 	if (test->settings->rate)
2123 	    cJSON_AddNumberToObject(j, "bandwidth", test->settings->rate);
2124 	if (test->settings->fqrate)
2125 	    cJSON_AddNumberToObject(j, "fqrate", test->settings->fqrate);
2126 	if (test->settings->pacing_timer)
2127 	    cJSON_AddNumberToObject(j, "pacing_timer", test->settings->pacing_timer);
2128 	if (test->settings->burst)
2129 	    cJSON_AddNumberToObject(j, "burst", test->settings->burst);
2130 	if (test->settings->tos)
2131 	    cJSON_AddNumberToObject(j, "TOS", test->settings->tos);
2132 	if (test->settings->flowlabel)
2133 	    cJSON_AddNumberToObject(j, "flowlabel", test->settings->flowlabel);
2134 	if (test->title)
2135 	    cJSON_AddStringToObject(j, "title", test->title);
2136 	if (test->extra_data)
2137 	    cJSON_AddStringToObject(j, "extra_data", test->extra_data);
2138 	if (test->congestion)
2139 	    cJSON_AddStringToObject(j, "congestion", test->congestion);
2140 	if (test->congestion_used)
2141 	    cJSON_AddStringToObject(j, "congestion_used", test->congestion_used);
2142 	if (test->get_server_output)
2143 	    cJSON_AddNumberToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
2144 	if (test->udp_counters_64bit)
2145 	    cJSON_AddNumberToObject(j, "udp_counters_64bit", iperf_get_test_udp_counters_64bit(test));
2146 	if (test->repeating_payload)
2147 	    cJSON_AddNumberToObject(j, "repeating_payload", test->repeating_payload);
2148 	if (test->zerocopy)
2149 	    cJSON_AddNumberToObject(j, "zerocopy", test->zerocopy);
2150 #if defined(HAVE_DONT_FRAGMENT)
2151 	if (test->settings->dont_fragment)
2152 	    cJSON_AddNumberToObject(j, "dont_fragment", test->settings->dont_fragment);
2153 #endif /* HAVE_DONT_FRAGMENT */
2154 #if defined(HAVE_SSL)
2155 	/* Send authentication parameters */
2156 	if (test->settings->client_username && test->settings->client_password && test->settings->client_rsa_pubkey){
2157 	    int rc = encode_auth_setting(test->settings->client_username, test->settings->client_password, test->settings->client_rsa_pubkey, &test->settings->authtoken);
2158 
2159 	    if (rc) {
2160 		cJSON_Delete(j);
2161 		i_errno = IESENDPARAMS;
2162 		return -1;
2163 	    }
2164 
2165 	    cJSON_AddStringToObject(j, "authtoken", test->settings->authtoken);
2166 	}
2167 #endif // HAVE_SSL
2168 	cJSON_AddStringToObject(j, "client_version", IPERF_VERSION);
2169 
2170 	if (test->debug) {
2171 	    char *str = cJSON_Print(j);
2172 	    printf("send_parameters:\n%s\n", str);
2173 	    cJSON_free(str);
2174 	}
2175 
2176 	if (JSON_write(test->ctrl_sck, j) < 0) {
2177 	    i_errno = IESENDPARAMS;
2178 	    r = -1;
2179 	}
2180 	cJSON_Delete(j);
2181     }
2182     return r;
2183 }
2184 
2185 /*************************************************************/
2186 
2187 static int
2188 get_parameters(struct iperf_test *test)
2189 {
2190     int r = 0;
2191     cJSON *j;
2192     cJSON *j_p;
2193 
2194     j = JSON_read(test->ctrl_sck);
2195     if (j == NULL) {
2196 	i_errno = IERECVPARAMS;
2197         r = -1;
2198     } else {
2199 	if (test->debug) {
2200             char *str;
2201             str = cJSON_Print(j);
2202             printf("get_parameters:\n%s\n", str );
2203             cJSON_free(str);
2204 	}
2205 
2206 	if ((j_p = cJSON_GetObjectItem(j, "tcp")) != NULL)
2207 	    set_protocol(test, Ptcp);
2208 	if ((j_p = cJSON_GetObjectItem(j, "udp")) != NULL)
2209 	    set_protocol(test, Pudp);
2210         if ((j_p = cJSON_GetObjectItem(j, "sctp")) != NULL)
2211             set_protocol(test, Psctp);
2212 	if ((j_p = cJSON_GetObjectItem(j, "omit")) != NULL)
2213 	    test->omit = j_p->valueint;
2214 	if ((j_p = cJSON_GetObjectItem(j, "server_affinity")) != NULL)
2215 	    test->server_affinity = j_p->valueint;
2216 	if ((j_p = cJSON_GetObjectItem(j, "time")) != NULL)
2217 	    test->duration = j_p->valueint;
2218 	if ((j_p = cJSON_GetObjectItem(j, "num")) != NULL)
2219 	    test->settings->bytes = j_p->valueint;
2220 	if ((j_p = cJSON_GetObjectItem(j, "blockcount")) != NULL)
2221 	    test->settings->blocks = j_p->valueint;
2222 	if ((j_p = cJSON_GetObjectItem(j, "MSS")) != NULL)
2223 	    test->settings->mss = j_p->valueint;
2224 	if ((j_p = cJSON_GetObjectItem(j, "nodelay")) != NULL)
2225 	    test->no_delay = 1;
2226 	if ((j_p = cJSON_GetObjectItem(j, "parallel")) != NULL)
2227 	    test->num_streams = j_p->valueint;
2228 	if ((j_p = cJSON_GetObjectItem(j, "reverse")) != NULL)
2229 	    iperf_set_test_reverse(test, 1);
2230         if ((j_p = cJSON_GetObjectItem(j, "bidirectional")) != NULL)
2231             iperf_set_test_bidirectional(test, 1);
2232 	if ((j_p = cJSON_GetObjectItem(j, "window")) != NULL)
2233 	    test->settings->socket_bufsize = j_p->valueint;
2234 	if ((j_p = cJSON_GetObjectItem(j, "len")) != NULL)
2235 	    test->settings->blksize = j_p->valueint;
2236 	if ((j_p = cJSON_GetObjectItem(j, "bandwidth")) != NULL)
2237 	    test->settings->rate = j_p->valueint;
2238 	if ((j_p = cJSON_GetObjectItem(j, "fqrate")) != NULL)
2239 	    test->settings->fqrate = j_p->valueint;
2240 	if ((j_p = cJSON_GetObjectItem(j, "pacing_timer")) != NULL)
2241 	    test->settings->pacing_timer = j_p->valueint;
2242 	if ((j_p = cJSON_GetObjectItem(j, "burst")) != NULL)
2243 	    test->settings->burst = j_p->valueint;
2244 	if ((j_p = cJSON_GetObjectItem(j, "TOS")) != NULL)
2245 	    test->settings->tos = j_p->valueint;
2246 	if ((j_p = cJSON_GetObjectItem(j, "flowlabel")) != NULL)
2247 	    test->settings->flowlabel = j_p->valueint;
2248 	if ((j_p = cJSON_GetObjectItem(j, "title")) != NULL)
2249 	    test->title = strdup(j_p->valuestring);
2250 	if ((j_p = cJSON_GetObjectItem(j, "extra_data")) != NULL)
2251 	    test->extra_data = strdup(j_p->valuestring);
2252 	if ((j_p = cJSON_GetObjectItem(j, "congestion")) != NULL)
2253 	    test->congestion = strdup(j_p->valuestring);
2254 	if ((j_p = cJSON_GetObjectItem(j, "congestion_used")) != NULL)
2255 	    test->congestion_used = strdup(j_p->valuestring);
2256 	if ((j_p = cJSON_GetObjectItem(j, "get_server_output")) != NULL)
2257 	    iperf_set_test_get_server_output(test, 1);
2258 	if ((j_p = cJSON_GetObjectItem(j, "udp_counters_64bit")) != NULL)
2259 	    iperf_set_test_udp_counters_64bit(test, 1);
2260 	if ((j_p = cJSON_GetObjectItem(j, "repeating_payload")) != NULL)
2261 	    test->repeating_payload = 1;
2262 	if ((j_p = cJSON_GetObjectItem(j, "zerocopy")) != NULL)
2263 	    test->zerocopy = j_p->valueint;
2264 #if defined(HAVE_DONT_FRAGMENT)
2265 	if ((j_p = cJSON_GetObjectItem(j, "dont_fragment")) != NULL)
2266 	    test->settings->dont_fragment = j_p->valueint;
2267 #endif /* HAVE_DONT_FRAGMENT */
2268 #if defined(HAVE_SSL)
2269 	if ((j_p = cJSON_GetObjectItem(j, "authtoken")) != NULL)
2270         test->settings->authtoken = strdup(j_p->valuestring);
2271 #endif //HAVE_SSL
2272 	if (test->mode && test->protocol->id == Ptcp && has_tcpinfo_retransmits())
2273 	    test->sender_has_retransmits = 1;
2274 	if (test->settings->rate)
2275 	    cJSON_AddNumberToObject(test->json_start, "target_bitrate", test->settings->rate);
2276 	cJSON_Delete(j);
2277     }
2278     return r;
2279 }
2280 
2281 /*************************************************************/
2282 
2283 static int
2284 send_results(struct iperf_test *test)
2285 {
2286     int r = 0;
2287     cJSON *j;
2288     cJSON *j_streams;
2289     struct iperf_stream *sp;
2290     cJSON *j_stream;
2291     int sender_has_retransmits;
2292     iperf_size_t bytes_transferred;
2293     int retransmits;
2294     struct iperf_time temp_time;
2295     double start_time, end_time;
2296 
2297     j = cJSON_CreateObject();
2298     if (j == NULL) {
2299 	i_errno = IEPACKAGERESULTS;
2300 	r = -1;
2301     } else {
2302 	cJSON_AddNumberToObject(j, "cpu_util_total", test->cpu_util[0]);
2303 	cJSON_AddNumberToObject(j, "cpu_util_user", test->cpu_util[1]);
2304 	cJSON_AddNumberToObject(j, "cpu_util_system", test->cpu_util[2]);
2305 	if ( test->mode == RECEIVER )
2306 	    sender_has_retransmits = -1;
2307 	else
2308 	    sender_has_retransmits = test->sender_has_retransmits;
2309 	cJSON_AddNumberToObject(j, "sender_has_retransmits", sender_has_retransmits);
2310 	if ( test->congestion_used ) {
2311 	    cJSON_AddStringToObject(j, "congestion_used", test->congestion_used);
2312 	}
2313 
2314 	/* If on the server and sending server output, then do this */
2315 	if (test->role == 's' && test->get_server_output) {
2316 	    if (test->json_output) {
2317 		/* Add JSON output */
2318 		cJSON_AddItemReferenceToObject(j, "server_output_json", test->json_top);
2319 	    }
2320 	    else {
2321 		/* Add textual output */
2322 		size_t buflen = 0;
2323 
2324 		/* Figure out how much room we need to hold the complete output string */
2325 		struct iperf_textline *t;
2326 		TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
2327 		    buflen += strlen(t->line);
2328 		}
2329 
2330 		/* Allocate and build it up from the component lines */
2331 		char *output = calloc(buflen + 1, 1);
2332 		TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
2333 		    strncat(output, t->line, buflen);
2334 		    buflen -= strlen(t->line);
2335 		}
2336 
2337 		cJSON_AddStringToObject(j, "server_output_text", output);
2338         free(output);
2339 	    }
2340 	}
2341 
2342 	j_streams = cJSON_CreateArray();
2343 	if (j_streams == NULL) {
2344 	    i_errno = IEPACKAGERESULTS;
2345 	    r = -1;
2346 	} else {
2347 	    cJSON_AddItemToObject(j, "streams", j_streams);
2348 	    SLIST_FOREACH(sp, &test->streams, streams) {
2349 		j_stream = cJSON_CreateObject();
2350 		if (j_stream == NULL) {
2351 		    i_errno = IEPACKAGERESULTS;
2352 		    r = -1;
2353 		} else {
2354 		    cJSON_AddItemToArray(j_streams, j_stream);
2355 		    bytes_transferred = sp->sender ? (sp->result->bytes_sent - sp->result->bytes_sent_omit) : sp->result->bytes_received;
2356 		    retransmits = (sp->sender && test->sender_has_retransmits) ? sp->result->stream_retrans : -1;
2357 		    cJSON_AddNumberToObject(j_stream, "id", sp->id);
2358 		    cJSON_AddNumberToObject(j_stream, "bytes", bytes_transferred);
2359 		    cJSON_AddNumberToObject(j_stream, "retransmits", retransmits);
2360 		    cJSON_AddNumberToObject(j_stream, "jitter", sp->jitter);
2361 		    cJSON_AddNumberToObject(j_stream, "errors", sp->cnt_error);
2362 		    cJSON_AddNumberToObject(j_stream, "packets", sp->packet_count);
2363 
2364 		    iperf_time_diff(&sp->result->start_time, &sp->result->start_time, &temp_time);
2365 		    start_time = iperf_time_in_secs(&temp_time);
2366 		    iperf_time_diff(&sp->result->start_time, &sp->result->end_time, &temp_time);
2367 		    end_time = iperf_time_in_secs(&temp_time);
2368 		    cJSON_AddNumberToObject(j_stream, "start_time", start_time);
2369 		    cJSON_AddNumberToObject(j_stream, "end_time", end_time);
2370 
2371 		}
2372 	    }
2373 	    if (r == 0 && test->debug) {
2374                 char *str = cJSON_Print(j);
2375 		printf("send_results\n%s\n", str);
2376                 cJSON_free(str);
2377 	    }
2378 	    if (r == 0 && JSON_write(test->ctrl_sck, j) < 0) {
2379 		i_errno = IESENDRESULTS;
2380 		r = -1;
2381 	    }
2382 	}
2383 	cJSON_Delete(j);
2384     }
2385     return r;
2386 }
2387 
2388 /*************************************************************/
2389 
2390 static int
2391 get_results(struct iperf_test *test)
2392 {
2393     int r = 0;
2394     cJSON *j;
2395     cJSON *j_cpu_util_total;
2396     cJSON *j_cpu_util_user;
2397     cJSON *j_cpu_util_system;
2398     cJSON *j_remote_congestion_used;
2399     cJSON *j_sender_has_retransmits;
2400     int result_has_retransmits;
2401     cJSON *j_streams;
2402     int n, i;
2403     cJSON *j_stream;
2404     cJSON *j_id;
2405     cJSON *j_bytes;
2406     cJSON *j_retransmits;
2407     cJSON *j_jitter;
2408     cJSON *j_errors;
2409     cJSON *j_packets;
2410     cJSON *j_server_output;
2411     cJSON *j_start_time, *j_end_time;
2412     int sid, cerror, pcount;
2413     double jitter;
2414     iperf_size_t bytes_transferred;
2415     int retransmits;
2416     struct iperf_stream *sp;
2417 
2418     j = JSON_read(test->ctrl_sck);
2419     if (j == NULL) {
2420 	i_errno = IERECVRESULTS;
2421         r = -1;
2422     } else {
2423 	j_cpu_util_total = cJSON_GetObjectItem(j, "cpu_util_total");
2424 	j_cpu_util_user = cJSON_GetObjectItem(j, "cpu_util_user");
2425 	j_cpu_util_system = cJSON_GetObjectItem(j, "cpu_util_system");
2426 	j_sender_has_retransmits = cJSON_GetObjectItem(j, "sender_has_retransmits");
2427 	if (j_cpu_util_total == NULL || j_cpu_util_user == NULL || j_cpu_util_system == NULL || j_sender_has_retransmits == NULL) {
2428 	    i_errno = IERECVRESULTS;
2429 	    r = -1;
2430 	} else {
2431 	    if (test->debug) {
2432                 char *str = cJSON_Print(j);
2433                 printf("get_results\n%s\n", str);
2434                 cJSON_free(str);
2435 	    }
2436 
2437 	    test->remote_cpu_util[0] = j_cpu_util_total->valuedouble;
2438 	    test->remote_cpu_util[1] = j_cpu_util_user->valuedouble;
2439 	    test->remote_cpu_util[2] = j_cpu_util_system->valuedouble;
2440 	    result_has_retransmits = j_sender_has_retransmits->valueint;
2441 	    if ( test->mode == RECEIVER ) {
2442 	        test->sender_has_retransmits = result_has_retransmits;
2443 	        test->other_side_has_retransmits = 0;
2444 	    }
2445 	    else if ( test->mode == BIDIRECTIONAL )
2446 	        test->other_side_has_retransmits = result_has_retransmits;
2447 
2448 	    j_streams = cJSON_GetObjectItem(j, "streams");
2449 	    if (j_streams == NULL) {
2450 		i_errno = IERECVRESULTS;
2451 		r = -1;
2452 	    } else {
2453 	        n = cJSON_GetArraySize(j_streams);
2454 		for (i=0; i<n; ++i) {
2455 		    j_stream = cJSON_GetArrayItem(j_streams, i);
2456 		    if (j_stream == NULL) {
2457 			i_errno = IERECVRESULTS;
2458 			r = -1;
2459 		    } else {
2460 			j_id = cJSON_GetObjectItem(j_stream, "id");
2461 			j_bytes = cJSON_GetObjectItem(j_stream, "bytes");
2462 			j_retransmits = cJSON_GetObjectItem(j_stream, "retransmits");
2463 			j_jitter = cJSON_GetObjectItem(j_stream, "jitter");
2464 			j_errors = cJSON_GetObjectItem(j_stream, "errors");
2465 			j_packets = cJSON_GetObjectItem(j_stream, "packets");
2466 			j_start_time = cJSON_GetObjectItem(j_stream, "start_time");
2467 			j_end_time = cJSON_GetObjectItem(j_stream, "end_time");
2468 			if (j_id == NULL || j_bytes == NULL || j_retransmits == NULL || j_jitter == NULL || j_errors == NULL || j_packets == NULL) {
2469 			    i_errno = IERECVRESULTS;
2470 			    r = -1;
2471 			} else {
2472 			    sid = j_id->valueint;
2473 			    bytes_transferred = j_bytes->valueint;
2474 			    retransmits = j_retransmits->valueint;
2475 			    jitter = j_jitter->valuedouble;
2476 			    cerror = j_errors->valueint;
2477 			    pcount = j_packets->valueint;
2478 			    SLIST_FOREACH(sp, &test->streams, streams)
2479 				if (sp->id == sid) break;
2480 			    if (sp == NULL) {
2481 				i_errno = IESTREAMID;
2482 				r = -1;
2483 			    } else {
2484 				if (sp->sender) {
2485 				    sp->jitter = jitter;
2486 				    sp->cnt_error = cerror;
2487 				    sp->peer_packet_count = pcount;
2488 				    sp->result->bytes_received = bytes_transferred;
2489 				    /*
2490 				     * We have to handle the possibility that
2491 				     * start_time and end_time might not be
2492 				     * available; this is the case for older (pre-3.2)
2493 				     * servers.
2494 				     *
2495 				     * We need to have result structure members to hold
2496 				     * the both sides' start_time and end_time.
2497 				     */
2498 				    if (j_start_time && j_end_time) {
2499 					sp->result->receiver_time = j_end_time->valuedouble - j_start_time->valuedouble;
2500 				    }
2501 				    else {
2502 					sp->result->receiver_time = 0.0;
2503 				    }
2504 				} else {
2505 				    sp->peer_packet_count = pcount;
2506 				    sp->result->bytes_sent = bytes_transferred;
2507 				    sp->result->stream_retrans = retransmits;
2508 				    if (j_start_time && j_end_time) {
2509 					sp->result->sender_time = j_end_time->valuedouble - j_start_time->valuedouble;
2510 				    }
2511 				    else {
2512 					sp->result->sender_time = 0.0;
2513 				    }
2514 				}
2515 			    }
2516 			}
2517 		    }
2518 		}
2519 		/*
2520 		 * If we're the client and we're supposed to get remote results,
2521 		 * look them up and process accordingly.
2522 		 */
2523 		if (test->role == 'c' && iperf_get_test_get_server_output(test)) {
2524 		    /* Look for JSON.  If we find it, grab the object so it doesn't get deleted. */
2525 		    j_server_output = cJSON_DetachItemFromObject(j, "server_output_json");
2526 		    if (j_server_output != NULL) {
2527 			test->json_server_output = j_server_output;
2528 		    }
2529 		    else {
2530 			/* No JSON, look for textual output.  Make a copy of the text for later. */
2531 			j_server_output = cJSON_GetObjectItem(j, "server_output_text");
2532 			if (j_server_output != NULL) {
2533 			    test->server_output_text = strdup(j_server_output->valuestring);
2534 			}
2535 		    }
2536 		}
2537 	    }
2538 	}
2539 
2540 	j_remote_congestion_used = cJSON_GetObjectItem(j, "congestion_used");
2541 	if (j_remote_congestion_used != NULL) {
2542 	    test->remote_congestion_used = strdup(j_remote_congestion_used->valuestring);
2543 	}
2544 
2545 	cJSON_Delete(j);
2546     }
2547     return r;
2548 }
2549 
2550 /*************************************************************/
2551 
2552 static int
2553 JSON_write(int fd, cJSON *json)
2554 {
2555     uint32_t hsize, nsize;
2556     char *str;
2557     int r = 0;
2558 
2559     str = cJSON_PrintUnformatted(json);
2560     if (str == NULL)
2561 	r = -1;
2562     else {
2563 	hsize = strlen(str);
2564 	nsize = htonl(hsize);
2565 	if (Nwrite(fd, (char*) &nsize, sizeof(nsize), Ptcp) < 0)
2566 	    r = -1;
2567 	else {
2568 	    if (Nwrite(fd, str, hsize, Ptcp) < 0)
2569 		r = -1;
2570 	}
2571 	cJSON_free(str);
2572     }
2573     return r;
2574 }
2575 
2576 /*************************************************************/
2577 
2578 static cJSON *
2579 JSON_read(int fd)
2580 {
2581     uint32_t hsize, nsize;
2582     char *str;
2583     cJSON *json = NULL;
2584     int rc;
2585 
2586     /*
2587      * Read a four-byte integer, which is the length of the JSON to follow.
2588      * Then read the JSON into a buffer and parse it.  Return a parsed JSON
2589      * structure, NULL if there was an error.
2590      */
2591     if (Nread(fd, (char*) &nsize, sizeof(nsize), Ptcp) >= 0) {
2592 	hsize = ntohl(nsize);
2593 	/* Allocate a buffer to hold the JSON */
2594 	str = (char *) calloc(sizeof(char), hsize+1);	/* +1 for trailing null */
2595 	if (str != NULL) {
2596 	    rc = Nread(fd, str, hsize, Ptcp);
2597 	    if (rc >= 0) {
2598 		/*
2599 		 * We should be reading in the number of bytes corresponding to the
2600 		 * length in that 4-byte integer.  If we don't the socket might have
2601 		 * prematurely closed.  Only do the JSON parsing if we got the
2602 		 * correct number of bytes.
2603 		 */
2604 		if (rc == hsize) {
2605 		    json = cJSON_Parse(str);
2606 		}
2607 		else {
2608 		    printf("WARNING:  Size of data read does not correspond to offered length\n");
2609 		}
2610 	    }
2611 	}
2612 	free(str);
2613     }
2614     return json;
2615 }
2616 
2617 /*************************************************************/
2618 /**
2619  * add_to_interval_list -- adds new interval to the interval_list
2620  */
2621 
2622 void
2623 add_to_interval_list(struct iperf_stream_result * rp, struct iperf_interval_results * new)
2624 {
2625     struct iperf_interval_results *irp;
2626 
2627     irp = (struct iperf_interval_results *) malloc(sizeof(struct iperf_interval_results));
2628     memcpy(irp, new, sizeof(struct iperf_interval_results));
2629     TAILQ_INSERT_TAIL(&rp->interval_results, irp, irlistentries);
2630 }
2631 
2632 
2633 /************************************************************/
2634 
2635 /**
2636  * connect_msg -- displays connection message
2637  * denoting sender/receiver details
2638  *
2639  */
2640 
2641 void
2642 connect_msg(struct iperf_stream *sp)
2643 {
2644     char ipl[INET6_ADDRSTRLEN], ipr[INET6_ADDRSTRLEN];
2645     int lport, rport;
2646 
2647     if (getsockdomain(sp->socket) == AF_INET) {
2648         inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->local_addr)->sin_addr, ipl, sizeof(ipl));
2649 	mapped_v4_to_regular_v4(ipl);
2650         inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->remote_addr)->sin_addr, ipr, sizeof(ipr));
2651 	mapped_v4_to_regular_v4(ipr);
2652         lport = ntohs(((struct sockaddr_in *) &sp->local_addr)->sin_port);
2653         rport = ntohs(((struct sockaddr_in *) &sp->remote_addr)->sin_port);
2654     } else {
2655         inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->local_addr)->sin6_addr, ipl, sizeof(ipl));
2656 	mapped_v4_to_regular_v4(ipl);
2657         inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->remote_addr)->sin6_addr, ipr, sizeof(ipr));
2658 	mapped_v4_to_regular_v4(ipr);
2659         lport = ntohs(((struct sockaddr_in6 *) &sp->local_addr)->sin6_port);
2660         rport = ntohs(((struct sockaddr_in6 *) &sp->remote_addr)->sin6_port);
2661     }
2662 
2663     if (sp->test->json_output)
2664         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));
2665     else
2666 	iperf_printf(sp->test, report_connected, sp->socket, ipl, lport, ipr, rport);
2667 }
2668 
2669 
2670 /**************************************************************************/
2671 
2672 struct iperf_test *
2673 iperf_new_test()
2674 {
2675     struct iperf_test *test;
2676 
2677     test = (struct iperf_test *) malloc(sizeof(struct iperf_test));
2678     if (!test) {
2679         i_errno = IENEWTEST;
2680         return NULL;
2681     }
2682     /* initialize everything to zero */
2683     memset(test, 0, sizeof(struct iperf_test));
2684 
2685     test->settings = (struct iperf_settings *) malloc(sizeof(struct iperf_settings));
2686     if (!test->settings) {
2687         free(test);
2688 	i_errno = IENEWTEST;
2689 	return NULL;
2690     }
2691     memset(test->settings, 0, sizeof(struct iperf_settings));
2692 
2693     test->bitrate_limit_intervals_traffic_bytes = (iperf_size_t *) malloc(sizeof(iperf_size_t) * MAX_INTERVAL);
2694     if (!test->bitrate_limit_intervals_traffic_bytes) {
2695         free(test);
2696 	i_errno = IENEWTEST;
2697 	return NULL;
2698     }
2699     memset(test->bitrate_limit_intervals_traffic_bytes, 0, sizeof(sizeof(iperf_size_t) * MAX_INTERVAL));
2700 
2701     /* By default all output goes to stdout */
2702     test->outfile = stdout;
2703 
2704     return test;
2705 }
2706 
2707 /**************************************************************************/
2708 
2709 struct protocol *
2710 protocol_new(void)
2711 {
2712     struct protocol *proto;
2713 
2714     proto = malloc(sizeof(struct protocol));
2715     if(!proto) {
2716         return NULL;
2717     }
2718     memset(proto, 0, sizeof(struct protocol));
2719 
2720     return proto;
2721 }
2722 
2723 void
2724 protocol_free(struct protocol *proto)
2725 {
2726     free(proto);
2727 }
2728 
2729 /**************************************************************************/
2730 int
2731 iperf_defaults(struct iperf_test *testp)
2732 {
2733     struct protocol *tcp, *udp;
2734 #if defined(HAVE_SCTP_H)
2735     struct protocol *sctp;
2736 #endif /* HAVE_SCTP_H */
2737 
2738     testp->omit = OMIT;
2739     testp->duration = DURATION;
2740     testp->diskfile_name = (char*) 0;
2741     testp->affinity = -1;
2742     testp->server_affinity = -1;
2743     TAILQ_INIT(&testp->xbind_addrs);
2744 #if defined(HAVE_CPUSET_SETAFFINITY)
2745     CPU_ZERO(&testp->cpumask);
2746 #endif /* HAVE_CPUSET_SETAFFINITY */
2747     testp->title = NULL;
2748     testp->extra_data = NULL;
2749     testp->congestion = NULL;
2750     testp->congestion_used = NULL;
2751     testp->remote_congestion_used = NULL;
2752     testp->server_port = PORT;
2753     testp->ctrl_sck = -1;
2754     testp->prot_listener = -1;
2755     testp->other_side_has_retransmits = 0;
2756 
2757     testp->stats_callback = iperf_stats_callback;
2758     testp->reporter_callback = iperf_reporter_callback;
2759 
2760     testp->stats_interval = testp->reporter_interval = 1;
2761     testp->num_streams = 1;
2762 
2763     testp->settings->domain = AF_UNSPEC;
2764     testp->settings->unit_format = 'a';
2765     testp->settings->socket_bufsize = 0;    /* use autotuning */
2766     testp->settings->blksize = DEFAULT_TCP_BLKSIZE;
2767     testp->settings->rate = 0;
2768     testp->settings->bitrate_limit = 0;
2769     testp->settings->bitrate_limit_interval = 5;
2770     testp->settings->bitrate_limit_stats_per_interval = 0;
2771     testp->settings->fqrate = 0;
2772     testp->settings->pacing_timer = DEFAULT_PACING_TIMER;
2773     testp->settings->burst = 0;
2774     testp->settings->mss = 0;
2775     testp->settings->bytes = 0;
2776     testp->settings->blocks = 0;
2777     testp->settings->connect_timeout = -1;
2778     testp->settings->rcv_timeout.secs = DEFAULT_NO_MSG_RCVD_TIMEOUT / SEC_TO_mS;
2779     testp->settings->rcv_timeout.usecs = (DEFAULT_NO_MSG_RCVD_TIMEOUT % SEC_TO_mS) * mS_TO_US;
2780     testp->zerocopy = 0;
2781 
2782     memset(testp->cookie, 0, COOKIE_SIZE);
2783 
2784     testp->multisend = 10;	/* arbitrary */
2785 
2786     /* Set up protocol list */
2787     SLIST_INIT(&testp->streams);
2788     SLIST_INIT(&testp->protocols);
2789 
2790     tcp = protocol_new();
2791     if (!tcp)
2792         return -1;
2793 
2794     tcp->id = Ptcp;
2795     tcp->name = "TCP";
2796     tcp->accept = iperf_tcp_accept;
2797     tcp->listen = iperf_tcp_listen;
2798     tcp->connect = iperf_tcp_connect;
2799     tcp->send = iperf_tcp_send;
2800     tcp->recv = iperf_tcp_recv;
2801     tcp->init = NULL;
2802     SLIST_INSERT_HEAD(&testp->protocols, tcp, protocols);
2803 
2804     udp = protocol_new();
2805     if (!udp) {
2806         protocol_free(tcp);
2807         return -1;
2808     }
2809 
2810     udp->id = Pudp;
2811     udp->name = "UDP";
2812     udp->accept = iperf_udp_accept;
2813     udp->listen = iperf_udp_listen;
2814     udp->connect = iperf_udp_connect;
2815     udp->send = iperf_udp_send;
2816     udp->recv = iperf_udp_recv;
2817     udp->init = iperf_udp_init;
2818     SLIST_INSERT_AFTER(tcp, udp, protocols);
2819 
2820     set_protocol(testp, Ptcp);
2821 
2822 #if defined(HAVE_SCTP_H)
2823     sctp = protocol_new();
2824     if (!sctp) {
2825         protocol_free(tcp);
2826         protocol_free(udp);
2827         return -1;
2828     }
2829 
2830     sctp->id = Psctp;
2831     sctp->name = "SCTP";
2832     sctp->accept = iperf_sctp_accept;
2833     sctp->listen = iperf_sctp_listen;
2834     sctp->connect = iperf_sctp_connect;
2835     sctp->send = iperf_sctp_send;
2836     sctp->recv = iperf_sctp_recv;
2837     sctp->init = iperf_sctp_init;
2838 
2839     SLIST_INSERT_AFTER(udp, sctp, protocols);
2840 #endif /* HAVE_SCTP_H */
2841 
2842     testp->on_new_stream = iperf_on_new_stream;
2843     testp->on_test_start = iperf_on_test_start;
2844     testp->on_connect = iperf_on_connect;
2845     testp->on_test_finish = iperf_on_test_finish;
2846 
2847     TAILQ_INIT(&testp->server_output_list);
2848 
2849     return 0;
2850 }
2851 
2852 
2853 /**************************************************************************/
2854 void
2855 iperf_free_test(struct iperf_test *test)
2856 {
2857     struct protocol *prot;
2858     struct iperf_stream *sp;
2859 
2860     /* Free streams */
2861     while (!SLIST_EMPTY(&test->streams)) {
2862         sp = SLIST_FIRST(&test->streams);
2863         SLIST_REMOVE_HEAD(&test->streams, streams);
2864         iperf_free_stream(sp);
2865     }
2866     if (test->server_hostname)
2867 	free(test->server_hostname);
2868     if (test->tmp_template)
2869 	free(test->tmp_template);
2870     if (test->bind_address)
2871 	free(test->bind_address);
2872     if (test->bind_dev)
2873 	free(test->bind_dev);
2874     if (!TAILQ_EMPTY(&test->xbind_addrs)) {
2875         struct xbind_entry *xbe;
2876 
2877         while (!TAILQ_EMPTY(&test->xbind_addrs)) {
2878             xbe = TAILQ_FIRST(&test->xbind_addrs);
2879             TAILQ_REMOVE(&test->xbind_addrs, xbe, link);
2880             if (xbe->ai)
2881                 freeaddrinfo(xbe->ai);
2882             free(xbe->name);
2883             free(xbe);
2884         }
2885     }
2886 #if defined(HAVE_SSL)
2887 
2888     if (test->server_rsa_private_key)
2889       EVP_PKEY_free(test->server_rsa_private_key);
2890     test->server_rsa_private_key = NULL;
2891 
2892     free(test->settings->authtoken);
2893     test->settings->authtoken = NULL;
2894 
2895     free(test->settings->client_username);
2896     test->settings->client_username = NULL;
2897 
2898     free(test->settings->client_password);
2899     test->settings->client_password = NULL;
2900 
2901     if (test->settings->client_rsa_pubkey)
2902       EVP_PKEY_free(test->settings->client_rsa_pubkey);
2903     test->settings->client_rsa_pubkey = NULL;
2904 #endif /* HAVE_SSL */
2905 
2906     if (test->settings)
2907     free(test->settings);
2908     if (test->title)
2909 	free(test->title);
2910     if (test->extra_data)
2911 	free(test->extra_data);
2912     if (test->congestion)
2913 	free(test->congestion);
2914     if (test->congestion_used)
2915 	free(test->congestion_used);
2916     if (test->remote_congestion_used)
2917 	free(test->remote_congestion_used);
2918     if (test->timestamp_format)
2919 	free(test->timestamp_format);
2920     if (test->omit_timer != NULL)
2921 	tmr_cancel(test->omit_timer);
2922     if (test->timer != NULL)
2923 	tmr_cancel(test->timer);
2924     if (test->stats_timer != NULL)
2925 	tmr_cancel(test->stats_timer);
2926     if (test->reporter_timer != NULL)
2927 	tmr_cancel(test->reporter_timer);
2928 
2929     /* Free protocol list */
2930     while (!SLIST_EMPTY(&test->protocols)) {
2931         prot = SLIST_FIRST(&test->protocols);
2932         SLIST_REMOVE_HEAD(&test->protocols, protocols);
2933         free(prot);
2934     }
2935 
2936     if (test->logfile) {
2937 	free(test->logfile);
2938 	test->logfile = NULL;
2939 	if (test->outfile && test->outfile != stdout) {
2940 	    fclose(test->outfile);
2941 	    test->outfile = NULL;
2942 	}
2943     }
2944 
2945     if (test->server_output_text) {
2946 	free(test->server_output_text);
2947 	test->server_output_text = NULL;
2948     }
2949 
2950     if (test->json_output_string) {
2951 	free(test->json_output_string);
2952 	test->json_output_string = NULL;
2953     }
2954 
2955     /* Free output line buffers, if any (on the server only) */
2956     struct iperf_textline *t;
2957     while (!TAILQ_EMPTY(&test->server_output_list)) {
2958 	t = TAILQ_FIRST(&test->server_output_list);
2959 	TAILQ_REMOVE(&test->server_output_list, t, textlineentries);
2960 	free(t->line);
2961 	free(t);
2962     }
2963 
2964     /* sctp_bindx: do not free the arguments, only the resolver results */
2965     if (!TAILQ_EMPTY(&test->xbind_addrs)) {
2966         struct xbind_entry *xbe;
2967 
2968         TAILQ_FOREACH(xbe, &test->xbind_addrs, link) {
2969             if (xbe->ai) {
2970                 freeaddrinfo(xbe->ai);
2971                 xbe->ai = NULL;
2972             }
2973         }
2974     }
2975 
2976     /* Free interval's traffic array for average rate calculations */
2977     if (test->bitrate_limit_intervals_traffic_bytes != NULL)
2978         free(test->bitrate_limit_intervals_traffic_bytes);
2979 
2980     /* XXX: Why are we setting these values to NULL? */
2981     // test->streams = NULL;
2982     test->stats_callback = NULL;
2983     test->reporter_callback = NULL;
2984     free(test);
2985 }
2986 
2987 
2988 void
2989 iperf_reset_test(struct iperf_test *test)
2990 {
2991     struct iperf_stream *sp;
2992     int i;
2993 
2994     /* Free streams */
2995     while (!SLIST_EMPTY(&test->streams)) {
2996         sp = SLIST_FIRST(&test->streams);
2997         SLIST_REMOVE_HEAD(&test->streams, streams);
2998         iperf_free_stream(sp);
2999     }
3000     if (test->omit_timer != NULL) {
3001 	tmr_cancel(test->omit_timer);
3002 	test->omit_timer = NULL;
3003     }
3004     if (test->timer != NULL) {
3005 	tmr_cancel(test->timer);
3006 	test->timer = NULL;
3007     }
3008     if (test->stats_timer != NULL) {
3009 	tmr_cancel(test->stats_timer);
3010 	test->stats_timer = NULL;
3011     }
3012     if (test->reporter_timer != NULL) {
3013 	tmr_cancel(test->reporter_timer);
3014 	test->reporter_timer = NULL;
3015     }
3016     test->done = 0;
3017 
3018     SLIST_INIT(&test->streams);
3019 
3020     if (test->remote_congestion_used)
3021         free(test->remote_congestion_used);
3022     test->remote_congestion_used = NULL;
3023     test->role = 's';
3024     test->mode = RECEIVER;
3025     test->sender_has_retransmits = 0;
3026     set_protocol(test, Ptcp);
3027     test->omit = OMIT;
3028     test->duration = DURATION;
3029     test->server_affinity = -1;
3030 #if defined(HAVE_CPUSET_SETAFFINITY)
3031     CPU_ZERO(&test->cpumask);
3032 #endif /* HAVE_CPUSET_SETAFFINITY */
3033     test->state = 0;
3034 
3035     test->ctrl_sck = -1;
3036     test->prot_listener = -1;
3037 
3038     test->bytes_sent = 0;
3039     test->blocks_sent = 0;
3040 
3041     test->bytes_received = 0;
3042     test->blocks_received = 0;
3043 
3044     test->other_side_has_retransmits = 0;
3045 
3046     test->bitrate_limit_stats_count = 0;
3047     test->bitrate_limit_last_interval_index = 0;
3048     test->bitrate_limit_exceeded = 0;
3049 
3050     for (i = 0; i < MAX_INTERVAL; i++)
3051         test->bitrate_limit_intervals_traffic_bytes[i] = 0;
3052 
3053     test->reverse = 0;
3054     test->bidirectional = 0;
3055     test->no_delay = 0;
3056 
3057     FD_ZERO(&test->read_set);
3058     FD_ZERO(&test->write_set);
3059 
3060     test->num_streams = 1;
3061     test->settings->socket_bufsize = 0;
3062     test->settings->blksize = DEFAULT_TCP_BLKSIZE;
3063     test->settings->rate = 0;
3064     test->settings->burst = 0;
3065     test->settings->mss = 0;
3066     test->settings->tos = 0;
3067     test->settings->dont_fragment = 0;
3068     test->zerocopy = 0;
3069 
3070 #if defined(HAVE_SSL)
3071     if (test->settings->authtoken) {
3072         free(test->settings->authtoken);
3073         test->settings->authtoken = NULL;
3074     }
3075     if (test->settings->client_username) {
3076         free(test->settings->client_username);
3077         test->settings->client_username = NULL;
3078     }
3079     if (test->settings->client_password) {
3080         free(test->settings->client_password);
3081         test->settings->client_password = NULL;
3082     }
3083     if (test->settings->client_rsa_pubkey) {
3084         EVP_PKEY_free(test->settings->client_rsa_pubkey);
3085         test->settings->client_rsa_pubkey = NULL;
3086     }
3087 #endif /* HAVE_SSL */
3088 
3089     memset(test->cookie, 0, COOKIE_SIZE);
3090     test->multisend = 10;	/* arbitrary */
3091     test->udp_counters_64bit = 0;
3092     if (test->title) {
3093 	free(test->title);
3094 	test->title = NULL;
3095     }
3096     if (test->extra_data) {
3097 	free(test->extra_data);
3098 	test->extra_data = NULL;
3099     }
3100 
3101     /* Free output line buffers, if any (on the server only) */
3102     struct iperf_textline *t;
3103     while (!TAILQ_EMPTY(&test->server_output_list)) {
3104 	t = TAILQ_FIRST(&test->server_output_list);
3105 	TAILQ_REMOVE(&test->server_output_list, t, textlineentries);
3106 	free(t->line);
3107 	free(t);
3108     }
3109 }
3110 
3111 
3112 /* Reset all of a test's stats back to zero.  Called when the omitting
3113 ** period is over.
3114 */
3115 void
3116 iperf_reset_stats(struct iperf_test *test)
3117 {
3118     struct iperf_time now;
3119     struct iperf_stream *sp;
3120     struct iperf_stream_result *rp;
3121 
3122     test->bytes_sent = 0;
3123     test->blocks_sent = 0;
3124     iperf_time_now(&now);
3125     SLIST_FOREACH(sp, &test->streams, streams) {
3126 	sp->omitted_packet_count = sp->packet_count;
3127         sp->omitted_cnt_error = sp->cnt_error;
3128         sp->omitted_outoforder_packets = sp->outoforder_packets;
3129 	sp->jitter = 0;
3130 	rp = sp->result;
3131         rp->bytes_sent_omit = rp->bytes_sent;
3132         rp->bytes_received = 0;
3133         rp->bytes_sent_this_interval = rp->bytes_received_this_interval = 0;
3134 	if (test->sender_has_retransmits == 1) {
3135 	    struct iperf_interval_results ir; /* temporary results structure */
3136 	    save_tcpinfo(sp, &ir);
3137 	    rp->stream_prev_total_retrans = get_total_retransmits(&ir);
3138 	}
3139 	rp->stream_retrans = 0;
3140 	rp->start_time = now;
3141     }
3142 }
3143 
3144 
3145 /**************************************************************************/
3146 
3147 /**
3148  * Gather statistics during a test.
3149  * This function works for both the client and server side.
3150  */
3151 void
3152 iperf_stats_callback(struct iperf_test *test)
3153 {
3154     struct iperf_stream *sp;
3155     struct iperf_stream_result *rp = NULL;
3156     struct iperf_interval_results *irp, temp;
3157     struct iperf_time temp_time;
3158     iperf_size_t total_interval_bytes_transferred = 0;
3159 
3160     temp.omitted = test->omitting;
3161     SLIST_FOREACH(sp, &test->streams, streams) {
3162         rp = sp->result;
3163 	temp.bytes_transferred = sp->sender ? rp->bytes_sent_this_interval : rp->bytes_received_this_interval;
3164 
3165         // Total bytes transferred this interval
3166 	total_interval_bytes_transferred += rp->bytes_sent_this_interval + rp->bytes_received_this_interval;
3167 
3168 	irp = TAILQ_LAST(&rp->interval_results, irlisthead);
3169         /* result->end_time contains timestamp of previous interval */
3170         if ( irp != NULL ) /* not the 1st interval */
3171             memcpy(&temp.interval_start_time, &rp->end_time, sizeof(struct iperf_time));
3172         else /* or use timestamp from beginning */
3173             memcpy(&temp.interval_start_time, &rp->start_time, sizeof(struct iperf_time));
3174         /* now save time of end of this interval */
3175         iperf_time_now(&rp->end_time);
3176         memcpy(&temp.interval_end_time, &rp->end_time, sizeof(struct iperf_time));
3177         iperf_time_diff(&temp.interval_start_time, &temp.interval_end_time, &temp_time);
3178         temp.interval_duration = iperf_time_in_secs(&temp_time);
3179 	if (test->protocol->id == Ptcp) {
3180 	    if ( has_tcpinfo()) {
3181 		save_tcpinfo(sp, &temp);
3182 		if (test->sender_has_retransmits == 1) {
3183 		    long total_retrans = get_total_retransmits(&temp);
3184 		    temp.interval_retrans = total_retrans - rp->stream_prev_total_retrans;
3185 		    rp->stream_retrans += temp.interval_retrans;
3186 		    rp->stream_prev_total_retrans = total_retrans;
3187 
3188 		    temp.snd_cwnd = get_snd_cwnd(&temp);
3189 		    if (temp.snd_cwnd > rp->stream_max_snd_cwnd) {
3190 			rp->stream_max_snd_cwnd = temp.snd_cwnd;
3191 		    }
3192 
3193 		    temp.snd_wnd = get_snd_wnd(&temp);
3194 		    if (temp.snd_wnd > rp->stream_max_snd_wnd) {
3195 			rp->stream_max_snd_wnd = temp.snd_wnd;
3196 		    }
3197 
3198 		    temp.rtt = get_rtt(&temp);
3199 		    if (temp.rtt > rp->stream_max_rtt) {
3200 			rp->stream_max_rtt = temp.rtt;
3201 		    }
3202 		    if (rp->stream_min_rtt == 0 ||
3203 			temp.rtt < rp->stream_min_rtt) {
3204 			rp->stream_min_rtt = temp.rtt;
3205 		    }
3206 		    rp->stream_sum_rtt += temp.rtt;
3207 		    rp->stream_count_rtt++;
3208 
3209 		    temp.rttvar = get_rttvar(&temp);
3210 		    temp.pmtu = get_pmtu(&temp);
3211 		}
3212 	    }
3213 	} else {
3214 	    if (irp == NULL) {
3215 		temp.interval_packet_count = sp->packet_count;
3216 		temp.interval_outoforder_packets = sp->outoforder_packets;
3217 		temp.interval_cnt_error = sp->cnt_error;
3218 	    } else {
3219 		temp.interval_packet_count = sp->packet_count - irp->packet_count;
3220 		temp.interval_outoforder_packets = sp->outoforder_packets - irp->outoforder_packets;
3221 		temp.interval_cnt_error = sp->cnt_error - irp->cnt_error;
3222 	    }
3223 	    temp.packet_count = sp->packet_count;
3224 	    temp.jitter = sp->jitter;
3225 	    temp.outoforder_packets = sp->outoforder_packets;
3226 	    temp.cnt_error = sp->cnt_error;
3227 	}
3228         add_to_interval_list(rp, &temp);
3229         rp->bytes_sent_this_interval = rp->bytes_received_this_interval = 0;
3230     }
3231 
3232     /* Verify that total server's throughput is not above specified limit */
3233     if (test->role == 's') {
3234 	iperf_check_total_rate(test, total_interval_bytes_transferred);
3235     }
3236 }
3237 
3238 /**
3239  * Print intermediate results during a test (interval report).
3240  * Uses print_interval_results to print the results for each stream,
3241  * then prints an interval summary for all streams in this
3242  * interval.
3243  */
3244 static void
3245 iperf_print_intermediate(struct iperf_test *test)
3246 {
3247     struct iperf_stream *sp = NULL;
3248     struct iperf_interval_results *irp;
3249     struct iperf_time temp_time;
3250     cJSON *json_interval;
3251     cJSON *json_interval_streams;
3252 
3253     int lower_mode, upper_mode;
3254     int current_mode;
3255 
3256     /*
3257      * Due to timing oddities, there can be cases, especially on the
3258      * server side, where at the end of a test there is a fairly short
3259      * interval with no data transferred.  This could caused by
3260      * the control and data flows sharing the same path in the network,
3261      * and having the control messages for stopping the test being
3262      * queued behind the data packets.
3263      *
3264      * We'd like to try to omit that last interval when it happens, to
3265      * avoid cluttering data and output with useless stuff.
3266      * So we're going to try to ignore very short intervals (less than
3267      * 10% of the interval time) that have no data.
3268      */
3269     int interval_ok = 0;
3270     SLIST_FOREACH(sp, &test->streams, streams) {
3271 	irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);
3272 	if (irp) {
3273 	    iperf_time_diff(&irp->interval_start_time, &irp->interval_end_time, &temp_time);
3274 	    double interval_len = iperf_time_in_secs(&temp_time);
3275 	    if (test->debug) {
3276 		printf("interval_len %f bytes_transferred %" PRIu64 "\n", interval_len, irp->bytes_transferred);
3277 	    }
3278 
3279 	    /*
3280 	     * If the interval is at least 10% the normal interval
3281 	     * length, or if there were actual bytes transferred,
3282 	     * then we want to keep this interval.
3283 	     */
3284 	    if (interval_len >= test->stats_interval * 0.10 ||
3285 		irp->bytes_transferred > 0) {
3286 		interval_ok = 1;
3287 		if (test->debug) {
3288 		    printf("interval forces keep\n");
3289 		}
3290 	    }
3291 	}
3292     }
3293     if (!interval_ok) {
3294 	if (test->debug) {
3295 	    printf("ignoring short interval with no data\n");
3296 	}
3297 	return;
3298     }
3299 
3300     if (test->json_output) {
3301         json_interval = cJSON_CreateObject();
3302 	if (json_interval == NULL)
3303 	    return;
3304 	cJSON_AddItemToArray(test->json_intervals, json_interval);
3305         json_interval_streams = cJSON_CreateArray();
3306 	if (json_interval_streams == NULL)
3307 	    return;
3308 	cJSON_AddItemToObject(json_interval, "streams", json_interval_streams);
3309     } else {
3310         json_interval = NULL;
3311         json_interval_streams = NULL;
3312     }
3313 
3314     /*
3315      * We must to sum streams separately.
3316      * For bidirectional mode we must to display
3317      * information about sender and receiver streams.
3318      * For client side we must handle sender streams
3319      * firstly and receiver streams for server side.
3320      * The following design allows us to do this.
3321      */
3322 
3323     if (test->mode == BIDIRECTIONAL) {
3324         if (test->role == 'c') {
3325             lower_mode = -1;
3326             upper_mode = 0;
3327         } else {
3328             lower_mode = 0;
3329             upper_mode = 1;
3330         }
3331     } else {
3332         lower_mode = test->mode;
3333         upper_mode = lower_mode;
3334     }
3335 
3336 
3337     for (current_mode = lower_mode; current_mode <= upper_mode; ++current_mode) {
3338         char ubuf[UNIT_LEN];
3339         char nbuf[UNIT_LEN];
3340         char mbuf[UNIT_LEN];
3341         char zbuf[] = "          ";
3342 
3343         iperf_size_t bytes = 0;
3344         double bandwidth;
3345         int retransmits = 0;
3346         double start_time, end_time;
3347 
3348         int total_packets = 0, lost_packets = 0;
3349         double avg_jitter = 0.0, lost_percent;
3350         int stream_must_be_sender = current_mode * current_mode;
3351 
3352         char *sum_name;
3353 
3354         /*  Print stream role just for bidirectional mode. */
3355 
3356         if (test->mode == BIDIRECTIONAL) {
3357             sprintf(mbuf, "[%s-%s]", stream_must_be_sender?"TX":"RX", test->role == 'c'?"C":"S");
3358         } else {
3359             mbuf[0] = '\0';
3360             zbuf[0] = '\0';
3361         }
3362 
3363         SLIST_FOREACH(sp, &test->streams, streams) {
3364             if (sp->sender == stream_must_be_sender) {
3365                 print_interval_results(test, sp, json_interval_streams);
3366                 /* sum up all streams */
3367                 irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);
3368                 if (irp == NULL) {
3369                     iperf_err(test,
3370                             "iperf_print_intermediate error: interval_results is NULL");
3371                     return;
3372                 }
3373                 bytes += irp->bytes_transferred;
3374                 if (test->protocol->id == Ptcp) {
3375                     if (test->sender_has_retransmits == 1) {
3376                         retransmits += irp->interval_retrans;
3377                     }
3378                 } else {
3379                     total_packets += irp->interval_packet_count;
3380                     lost_packets += irp->interval_cnt_error;
3381                     avg_jitter += irp->jitter;
3382                 }
3383             }
3384         }
3385 
3386         /* next build string with sum of all streams */
3387         if (test->num_streams > 1 || test->json_output) {
3388             /*
3389              * With BIDIR give a different JSON object name to the one sent/receive sums.
3390              * The different name is given to the data sent from the server, which is
3391              * the "reverse" channel.  This makes sure that the name reported on the server
3392              * and client are compatible, and the names are the same as with non-bidir,
3393              * except for when reverse is used.
3394              */
3395             sum_name = "sum";
3396             if (test->mode == BIDIRECTIONAL) {
3397                 if ((test->role == 'c' && !stream_must_be_sender) ||
3398                     (test->role != 'c' && stream_must_be_sender))
3399                 {
3400                     sum_name = "sum_bidir_reverse";
3401                 }
3402             }
3403 
3404             sp = SLIST_FIRST(&test->streams); /* reset back to 1st stream */
3405             /* Only do this of course if there was a first stream */
3406             if (sp) {
3407 	    irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);    /* use 1st stream for timing info */
3408 
3409 	    unit_snprintf(ubuf, UNIT_LEN, (double) bytes, 'A');
3410 	    bandwidth = (double) bytes / (double) irp->interval_duration;
3411 	    unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3412 
3413 	    iperf_time_diff(&sp->result->start_time,&irp->interval_start_time, &temp_time);
3414 	    start_time = iperf_time_in_secs(&temp_time);
3415 	    iperf_time_diff(&sp->result->start_time,&irp->interval_end_time, &temp_time);
3416 	    end_time = iperf_time_in_secs(&temp_time);
3417                 if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3418                     if (test->sender_has_retransmits == 1 && stream_must_be_sender) {
3419                         /* Interval sum, TCP with retransmits. */
3420                         if (test->json_output)
3421                             cJSON_AddItemToObject(json_interval, sum_name, iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  retransmits: %d  omitted: %b sender: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, (int64_t) retransmits, irp->omitted, stream_must_be_sender)); /* XXX irp->omitted or test->omitting? */
3422                         else
3423                             iperf_printf(test, report_sum_bw_retrans_format, mbuf, start_time, end_time, ubuf, nbuf, retransmits, irp->omitted?report_omitted:""); /* XXX irp->omitted or test->omitting? */
3424                     } else {
3425                         /* Interval sum, TCP without retransmits. */
3426                         if (test->json_output)
3427                             cJSON_AddItemToObject(json_interval, sum_name, iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  omitted: %b sender: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, test->omitting, stream_must_be_sender));
3428                         else
3429                             iperf_printf(test, report_sum_bw_format, mbuf, start_time, end_time, ubuf, nbuf, test->omitting?report_omitted:"");
3430                     }
3431                 } else {
3432                     /* Interval sum, UDP. */
3433                     if (stream_must_be_sender) {
3434                         if (test->json_output)
3435                             cJSON_AddItemToObject(json_interval, sum_name, iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  packets: %d  omitted: %b sender: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, (int64_t) total_packets, test->omitting, stream_must_be_sender));
3436                         else
3437                             iperf_printf(test, report_sum_bw_udp_sender_format, mbuf, start_time, end_time, ubuf, nbuf, zbuf, total_packets, test->omitting?report_omitted:"");
3438                     } else {
3439                         avg_jitter /= test->num_streams;
3440                         if (total_packets > 0) {
3441                             lost_percent = 100.0 * lost_packets / total_packets;
3442                         }
3443                         else {
3444                             lost_percent = 0.0;
3445                         }
3446                         if (test->json_output)
3447                             cJSON_AddItemToObject(json_interval, sum_name, 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 sender: %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, stream_must_be_sender));
3448                         else
3449                             iperf_printf(test, report_sum_bw_udp_format, mbuf, start_time, end_time, ubuf, nbuf, avg_jitter * 1000.0, lost_packets, total_packets, lost_percent, test->omitting?report_omitted:"");
3450                     }
3451                 }
3452             }
3453         }
3454     }
3455 }
3456 
3457 /**
3458  * Print overall summary statistics at the end of a test.
3459  */
3460 static void
3461 iperf_print_results(struct iperf_test *test)
3462 {
3463 
3464     cJSON *json_summary_streams = NULL;
3465 
3466     int lower_mode, upper_mode;
3467     int current_mode;
3468 
3469     char *sum_sent_name, *sum_received_name, *sum_name;
3470 
3471     int tmp_sender_has_retransmits = test->sender_has_retransmits;
3472 
3473     /* print final summary for all intervals */
3474 
3475     if (test->json_output) {
3476         json_summary_streams = cJSON_CreateArray();
3477 	if (json_summary_streams == NULL)
3478 	    return;
3479 	cJSON_AddItemToObject(test->json_end, "streams", json_summary_streams);
3480     } else {
3481 	iperf_printf(test, "%s", report_bw_separator);
3482 	if (test->verbose)
3483 	    iperf_printf(test, "%s", report_summary);
3484 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3485 	    if (test->sender_has_retransmits || test->other_side_has_retransmits) {
3486 	        if (test->bidirectional)
3487 	            iperf_printf(test, "%s", report_bw_retrans_header_bidir);
3488 	        else
3489 	            iperf_printf(test, "%s", report_bw_retrans_header);
3490 	    }
3491 	    else {
3492 	        if (test->bidirectional)
3493 	            iperf_printf(test, "%s", report_bw_header_bidir);
3494 	        else
3495 	            iperf_printf(test, "%s", report_bw_header);
3496 	    }
3497 	} else {
3498 	    if (test->bidirectional)
3499 	        iperf_printf(test, "%s", report_bw_udp_header_bidir);
3500 	    else
3501 	        iperf_printf(test, "%s", report_bw_udp_header);
3502 	}
3503     }
3504 
3505     /*
3506      * We must to sum streams separately.
3507      * For bidirectional mode we must to display
3508      * information about sender and receiver streams.
3509      * For client side we must handle sender streams
3510      * firstly and receiver streams for server side.
3511      * The following design allows us to do this.
3512      */
3513 
3514     if (test->mode == BIDIRECTIONAL) {
3515         if (test->role == 'c') {
3516             lower_mode = -1;
3517             upper_mode = 0;
3518         } else {
3519             lower_mode = 0;
3520             upper_mode = 1;
3521         }
3522     } else {
3523         lower_mode = test->mode;
3524         upper_mode = lower_mode;
3525     }
3526 
3527 
3528     for (current_mode = lower_mode; current_mode <= upper_mode; ++current_mode) {
3529         cJSON *json_summary_stream = NULL;
3530         int total_retransmits = 0;
3531         int total_packets = 0, lost_packets = 0;
3532         int sender_packet_count = 0, receiver_packet_count = 0; /* for this stream, this interval */
3533         int sender_total_packets = 0, receiver_total_packets = 0; /* running total */
3534         char ubuf[UNIT_LEN];
3535         char nbuf[UNIT_LEN];
3536         struct stat sb;
3537         char sbuf[UNIT_LEN];
3538         struct iperf_stream *sp = NULL;
3539         iperf_size_t bytes_sent, total_sent = 0;
3540         iperf_size_t bytes_received, total_received = 0;
3541         double start_time, end_time = 0.0, avg_jitter = 0.0, lost_percent = 0.0;
3542         double sender_time = 0.0, receiver_time = 0.0;
3543     struct iperf_time temp_time;
3544         double bandwidth;
3545 
3546         char mbuf[UNIT_LEN];
3547         int stream_must_be_sender = current_mode * current_mode;
3548 
3549 
3550         /*  Print stream role just for bidirectional mode. */
3551 
3552         if (test->mode == BIDIRECTIONAL) {
3553             sprintf(mbuf, "[%s-%s]", stream_must_be_sender?"TX":"RX", test->role == 'c'?"C":"S");
3554         } else {
3555             mbuf[0] = '\0';
3556         }
3557 
3558         /* Get sender_has_retransmits for each sender side (client and server) */
3559         if (test->mode == BIDIRECTIONAL && stream_must_be_sender)
3560             test->sender_has_retransmits = tmp_sender_has_retransmits;
3561         else if (test->mode == BIDIRECTIONAL && !stream_must_be_sender)
3562             test->sender_has_retransmits = test->other_side_has_retransmits;
3563 
3564         start_time = 0.;
3565         sp = SLIST_FIRST(&test->streams);
3566 
3567         /*
3568          * If there is at least one stream, then figure out the length of time
3569          * we were running the tests and print out some statistics about
3570          * the streams.  It's possible to not have any streams at all
3571          * if the client got interrupted before it got to do anything.
3572          *
3573          * Also note that we try to keep separate values for the sender
3574          * and receiver ending times.  Earlier iperf (3.1 and earlier)
3575          * servers didn't send that to the clients, so in this case we fall
3576          * back to using the client's ending timestamp.  The fallback is
3577          * basically emulating what iperf 3.1 did.
3578          */
3579 
3580         if (sp) {
3581     iperf_time_diff(&sp->result->start_time, &sp->result->end_time, &temp_time);
3582     end_time = iperf_time_in_secs(&temp_time);
3583         if (sp->sender) {
3584             sp->result->sender_time = end_time;
3585             if (sp->result->receiver_time == 0.0) {
3586                 sp->result->receiver_time = sp->result->sender_time;
3587             }
3588         }
3589         else {
3590             sp->result->receiver_time = end_time;
3591             if (sp->result->sender_time == 0.0) {
3592                 sp->result->sender_time = sp->result->receiver_time;
3593             }
3594         }
3595         sender_time = sp->result->sender_time;
3596         receiver_time = sp->result->receiver_time;
3597         SLIST_FOREACH(sp, &test->streams, streams) {
3598             if (sp->sender == stream_must_be_sender) {
3599                 if (test->json_output) {
3600                     json_summary_stream = cJSON_CreateObject();
3601                     if (json_summary_stream == NULL)
3602                         return;
3603                     cJSON_AddItemToArray(json_summary_streams, json_summary_stream);
3604                 }
3605 
3606                 bytes_sent = sp->result->bytes_sent - sp->result->bytes_sent_omit;
3607                 bytes_received = sp->result->bytes_received;
3608                 total_sent += bytes_sent;
3609                 total_received += bytes_received;
3610 
3611                 if (sp->sender) {
3612                     sender_packet_count = sp->packet_count;
3613                     receiver_packet_count = sp->peer_packet_count;
3614                 }
3615                 else {
3616                     sender_packet_count = sp->peer_packet_count;
3617                     receiver_packet_count = sp->packet_count;
3618                 }
3619 
3620                 if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3621                     if (test->sender_has_retransmits) {
3622                         total_retransmits += sp->result->stream_retrans;
3623                     }
3624                 } else {
3625                     /*
3626                      * Running total of the total number of packets.  Use the sender packet count if we
3627                      * have it, otherwise use the receiver packet count.
3628                      */
3629                     int packet_count = sender_packet_count ? sender_packet_count : receiver_packet_count;
3630                     total_packets += (packet_count - sp->omitted_packet_count);
3631                     sender_total_packets += (sender_packet_count - sp->omitted_packet_count);
3632                     receiver_total_packets += (receiver_packet_count - sp->omitted_packet_count);
3633                     lost_packets += (sp->cnt_error - sp->omitted_cnt_error);
3634                     avg_jitter += sp->jitter;
3635                 }
3636 
3637                 unit_snprintf(ubuf, UNIT_LEN, (double) bytes_sent, 'A');
3638                 if (sender_time > 0.0) {
3639                     bandwidth = (double) bytes_sent / (double) sender_time;
3640                 }
3641                 else {
3642                     bandwidth = 0.0;
3643                 }
3644                 unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3645                 if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3646                     if (test->sender_has_retransmits) {
3647                         /* Sender summary, TCP and SCTP with retransmits. */
3648                         if (test->json_output)
3649                             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_snd_wnd:  %d  max_rtt:  %d  min_rtt:  %d  mean_rtt:  %d sender: %b", (int64_t) sp->socket, (double) start_time, (double) sender_time, (double) sender_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_snd_wnd, (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), stream_must_be_sender));
3650                         else
3651                             if (test->role == 's' && !sp->sender) {
3652                                 if (test->verbose)
3653                                     iperf_printf(test, report_sender_not_available_format, sp->socket);
3654                             }
3655                             else {
3656                                 iperf_printf(test, report_bw_retrans_format, sp->socket, mbuf, start_time, sender_time, ubuf, nbuf, sp->result->stream_retrans, report_sender);
3657                             }
3658                     } else {
3659                         /* Sender summary, TCP and SCTP without retransmits. */
3660                         if (test->json_output)
3661                             cJSON_AddItemToObject(json_summary_stream, "sender", iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f sender: %b", (int64_t) sp->socket, (double) start_time, (double) sender_time, (double) sender_time, (int64_t) bytes_sent, bandwidth * 8,  stream_must_be_sender));
3662                         else
3663                             if (test->role == 's' && !sp->sender) {
3664                                 if (test->verbose)
3665                                     iperf_printf(test, report_sender_not_available_format, sp->socket);
3666                             }
3667                             else {
3668                                 iperf_printf(test, report_bw_format, sp->socket, mbuf, start_time, sender_time, ubuf, nbuf, report_sender);
3669                             }
3670                     }
3671                 } else {
3672                     /* Sender summary, UDP. */
3673                     if (sender_packet_count - sp->omitted_packet_count > 0) {
3674                         lost_percent = 100.0 * (sp->cnt_error - sp->omitted_cnt_error) / (sender_packet_count - sp->omitted_packet_count);
3675                     }
3676                     else {
3677                         lost_percent = 0.0;
3678                     }
3679                     if (test->json_output) {
3680                         /*
3681                          * For hysterical raisins, we only emit one JSON
3682                          * object for the UDP summary, and it contains
3683                          * information for both the sender and receiver
3684                          * side.
3685                          *
3686                          * The JSON format as currently defined only includes one
3687                          * value for the number of packets.  We usually want that
3688                          * to be the sender's value (how many packets were sent
3689                          * by the sender).  However this value might not be
3690                          * available on the receiver in certain circumstances
3691                          * specifically on the server side for a normal test or
3692                          * the client side for a reverse-mode test.  If this
3693                          * is the case, then use the receiver's count of packets
3694                          * instead.
3695                          */
3696                         int packet_count = sender_packet_count ? sender_packet_count : receiver_packet_count;
3697                         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  out_of_order: %d sender: %b", (int64_t) sp->socket, (double) start_time, (double) sender_time, (double) sender_time, (int64_t) bytes_sent, bandwidth * 8, (double) sp->jitter * 1000.0, (int64_t) (sp->cnt_error - sp->omitted_cnt_error), (int64_t) (packet_count - sp->omitted_packet_count), (double) lost_percent, (int64_t) (sp->outoforder_packets - sp->omitted_outoforder_packets), stream_must_be_sender));
3698                     }
3699                     else {
3700                         /*
3701                          * Due to ordering of messages on the control channel,
3702                          * the server cannot report on client-side summary
3703                          * statistics.  If we're the server, omit one set of
3704                          * summary statistics to avoid giving meaningless
3705                          * results.
3706                          */
3707                         if (test->role == 's' && !sp->sender) {
3708                             if (test->verbose)
3709                                 iperf_printf(test, report_sender_not_available_format, sp->socket);
3710                         }
3711                         else {
3712                             iperf_printf(test, report_bw_udp_format, sp->socket, mbuf, start_time, sender_time, ubuf, nbuf, 0.0, 0, (sender_packet_count - sp->omitted_packet_count), (double) 0, report_sender);
3713                         }
3714                         if ((sp->outoforder_packets - sp->omitted_outoforder_packets) > 0)
3715                           iperf_printf(test, report_sum_outoforder, mbuf, start_time, sender_time, (sp->outoforder_packets - sp->omitted_outoforder_packets));
3716                     }
3717                 }
3718 
3719                 if (sp->diskfile_fd >= 0) {
3720                     if (fstat(sp->diskfile_fd, &sb) == 0) {
3721                         /* In the odd case that it's a zero-sized file, say it was all transferred. */
3722                         int percent_sent = 100, percent_received = 100;
3723                         if (sb.st_size > 0) {
3724                             percent_sent = (int) ( ( (double) bytes_sent / (double) sb.st_size ) * 100.0 );
3725                             percent_received = (int) ( ( (double) bytes_received / (double) sb.st_size ) * 100.0 );
3726                         }
3727                         unit_snprintf(sbuf, UNIT_LEN, (double) sb.st_size, 'A');
3728                         if (test->json_output)
3729                             cJSON_AddItemToObject(json_summary_stream, "diskfile", iperf_json_printf("sent: %d  received: %d  size: %d  percent_sent: %d  percent_received: %d  filename: %s", (int64_t) bytes_sent, (int64_t) bytes_received, (int64_t) sb.st_size, (int64_t) percent_sent, (int64_t) percent_received, test->diskfile_name));
3730                         else
3731                             if (stream_must_be_sender) {
3732                                 iperf_printf(test, report_diskfile, ubuf, sbuf, percent_sent, test->diskfile_name);
3733                             }
3734                             else {
3735                                 unit_snprintf(ubuf, UNIT_LEN, (double) bytes_received, 'A');
3736                                 iperf_printf(test, report_diskfile, ubuf, sbuf, percent_received, test->diskfile_name);
3737                             }
3738                     }
3739                 }
3740 
3741                 unit_snprintf(ubuf, UNIT_LEN, (double) bytes_received, 'A');
3742                 if (receiver_time > 0) {
3743                     bandwidth = (double) bytes_received / (double) receiver_time;
3744                 }
3745                 else {
3746                     bandwidth = 0.0;
3747                 }
3748                 unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3749                 if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3750                     /* Receiver summary, TCP and SCTP */
3751                     if (test->json_output)
3752                         cJSON_AddItemToObject(json_summary_stream, "receiver", iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f sender: %b", (int64_t) sp->socket, (double) start_time, (double) receiver_time, (double) end_time, (int64_t) bytes_received, bandwidth * 8, stream_must_be_sender));
3753                     else
3754                         if (test->role == 's' && sp->sender) {
3755                             if (test->verbose)
3756                                 iperf_printf(test, report_receiver_not_available_format, sp->socket);
3757                         }
3758                         else {
3759                             iperf_printf(test, report_bw_format, sp->socket, mbuf, start_time, receiver_time, ubuf, nbuf, report_receiver);
3760                         }
3761                 }
3762                 else {
3763                     /*
3764                      * Receiver summary, UDP.  Note that JSON was emitted with
3765                      * the sender summary, so we only deal with human-readable
3766                      * data here.
3767                      */
3768                     if (! test->json_output) {
3769                         if (receiver_packet_count - sp->omitted_packet_count > 0) {
3770                             lost_percent = 100.0 * (sp->cnt_error - sp->omitted_cnt_error) / (receiver_packet_count - sp->omitted_packet_count);
3771                         }
3772                         else {
3773                             lost_percent = 0.0;
3774                         }
3775 
3776                         if (test->role == 's' && sp->sender) {
3777                             if (test->verbose)
3778                                 iperf_printf(test, report_receiver_not_available_format, sp->socket);
3779                         }
3780                         else {
3781                             iperf_printf(test, report_bw_udp_format, sp->socket, mbuf, start_time, receiver_time, ubuf, nbuf, sp->jitter * 1000.0, (sp->cnt_error - sp->omitted_cnt_error), (receiver_packet_count - sp->omitted_packet_count), lost_percent, report_receiver);
3782                         }
3783                     }
3784                 }
3785             }
3786         }
3787         }
3788 
3789         if (test->num_streams > 1 || test->json_output) {
3790             /*
3791              * With BIDIR give a different JSON object name to the one sent/receive sums.
3792              * The different name is given to the data sent from the server, which is
3793              * the "reverse" channel.  This makes sure that the name reported on the server
3794              * and client are compatible, and the names are the same as with non-bidir,
3795              * except for when reverse is used.
3796              */
3797             sum_name = "sum";
3798             sum_sent_name = "sum_sent";
3799             sum_received_name = "sum_received";
3800             if (test->mode == BIDIRECTIONAL) {
3801                 if ((test->role == 'c' && !stream_must_be_sender) ||
3802                     (test->role != 'c' && stream_must_be_sender))
3803                 {
3804                     sum_name = "sum_bidir_reverse";
3805                     sum_sent_name = "sum_sent_bidir_reverse";
3806                     sum_received_name = "sum_received_bidir_reverse";
3807                 }
3808 
3809             }
3810 
3811             unit_snprintf(ubuf, UNIT_LEN, (double) total_sent, 'A');
3812             /* If no tests were run, arbitrarily set bandwidth to 0. */
3813             if (sender_time > 0.0) {
3814                 bandwidth = (double) total_sent / (double) sender_time;
3815             }
3816             else {
3817                 bandwidth = 0.0;
3818             }
3819             unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3820             if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3821                 if (test->sender_has_retransmits) {
3822                     /* Summary sum, TCP with retransmits. */
3823                     if (test->json_output)
3824                         cJSON_AddItemToObject(test->json_end, sum_sent_name, iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  retransmits: %d sender: %b", (double) start_time, (double) sender_time, (double) sender_time, (int64_t) total_sent, bandwidth * 8, (int64_t) total_retransmits, stream_must_be_sender));
3825                     else
3826                         if (test->role == 's' && !stream_must_be_sender) {
3827                             if (test->verbose)
3828                                 iperf_printf(test, report_sender_not_available_summary_format, "SUM");
3829                         }
3830                         else {
3831                           iperf_printf(test, report_sum_bw_retrans_format, mbuf, start_time, sender_time, ubuf, nbuf, total_retransmits, report_sender);
3832                         }
3833                 } else {
3834                     /* Summary sum, TCP without retransmits. */
3835                     if (test->json_output)
3836                         cJSON_AddItemToObject(test->json_end, sum_sent_name, iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f sender: %b", (double) start_time, (double) sender_time, (double) sender_time, (int64_t) total_sent, bandwidth * 8, stream_must_be_sender));
3837                     else
3838                         if (test->role == 's' && !stream_must_be_sender) {
3839                             if (test->verbose)
3840                                 iperf_printf(test, report_sender_not_available_summary_format, "SUM");
3841                         }
3842                         else {
3843                             iperf_printf(test, report_sum_bw_format, mbuf, start_time, sender_time, ubuf, nbuf, report_sender);
3844                         }
3845                 }
3846                 unit_snprintf(ubuf, UNIT_LEN, (double) total_received, 'A');
3847                 /* If no tests were run, set received bandwidth to 0 */
3848                 if (receiver_time > 0.0) {
3849                     bandwidth = (double) total_received / (double) receiver_time;
3850                 }
3851                 else {
3852                     bandwidth = 0.0;
3853                 }
3854                 unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3855                 if (test->json_output)
3856                     cJSON_AddItemToObject(test->json_end, sum_received_name, iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f sender: %b", (double) start_time, (double) receiver_time, (double) receiver_time, (int64_t) total_received, bandwidth * 8, stream_must_be_sender));
3857                 else
3858                     if (test->role == 's' && stream_must_be_sender) {
3859                         if (test->verbose)
3860                             iperf_printf(test, report_receiver_not_available_summary_format, "SUM");
3861                     }
3862                     else {
3863                         iperf_printf(test, report_sum_bw_format, mbuf, start_time, receiver_time, ubuf, nbuf, report_receiver);
3864                     }
3865             } else {
3866                 /* Summary sum, UDP. */
3867                 avg_jitter /= test->num_streams;
3868                 /* If no packets were sent, arbitrarily set loss percentage to 0. */
3869                 if (total_packets > 0) {
3870                     lost_percent = 100.0 * lost_packets / total_packets;
3871                 }
3872                 else {
3873                     lost_percent = 0.0;
3874                 }
3875                 if (test->json_output) {
3876                     /*
3877                      * Original, summary structure. Using this
3878                      * structure is not recommended due to
3879                      * ambiguities between the sender and receiver.
3880                      */
3881                     cJSON_AddItemToObject(test->json_end, sum_name, 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 sender: %b", (double) start_time, (double) receiver_time, (double) receiver_time, (int64_t) total_sent, bandwidth * 8, (double) avg_jitter * 1000.0, (int64_t) lost_packets, (int64_t) total_packets, (double) lost_percent, stream_must_be_sender));
3882                     /*
3883                      * Separate sum_sent and sum_received structures.
3884                      * Using these structures to get the most complete
3885                      * information about UDP transfer.
3886                      */
3887                     cJSON_AddItemToObject(test->json_end, sum_sent_name, 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  sender: %b", (double) start_time, (double) sender_time, (double) sender_time, (int64_t) total_sent, (double) total_sent * 8 / sender_time, (double) 0.0, (int64_t) 0, (int64_t) sender_total_packets, (double) 0.0, 1));
3888                     cJSON_AddItemToObject(test->json_end, sum_received_name, 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  sender: %b", (double) start_time, (double) receiver_time, (double) receiver_time, (int64_t) total_received, (double) total_received * 8 / receiver_time, (double) avg_jitter * 1000.0, (int64_t) lost_packets, (int64_t) receiver_total_packets, (double) lost_percent, 0));
3889                 } else {
3890                     /*
3891                      * On the client we have both sender and receiver overall summary
3892                      * stats.  On the server we have only the side that was on the
3893                      * server.  Output whatever we have.
3894                      */
3895                     if (! (test->role == 's' && !stream_must_be_sender) ) {
3896                         unit_snprintf(ubuf, UNIT_LEN, (double) total_sent, 'A');
3897                         iperf_printf(test, report_sum_bw_udp_format, mbuf, start_time, sender_time, ubuf, nbuf, 0.0, 0, sender_total_packets, 0.0, "sender");
3898                     }
3899                     if (! (test->role == 's' && stream_must_be_sender) ) {
3900 
3901                         unit_snprintf(ubuf, UNIT_LEN, (double) total_received, 'A');
3902                         /* Compute received bandwidth. */
3903                         if (end_time > 0.0) {
3904                             bandwidth = (double) total_received / (double) receiver_time;
3905                         }
3906                         else {
3907                             bandwidth = 0.0;
3908                         }
3909                         unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3910                         iperf_printf(test, report_sum_bw_udp_format, mbuf, start_time, receiver_time, ubuf, nbuf, avg_jitter * 1000.0, lost_packets, receiver_total_packets, lost_percent, "receiver");
3911                     }
3912                 }
3913             }
3914         }
3915 
3916         if (test->json_output && current_mode == upper_mode) {
3917             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]));
3918             if (test->protocol->id == Ptcp) {
3919                 char *snd_congestion = NULL, *rcv_congestion = NULL;
3920                 if (stream_must_be_sender) {
3921                     snd_congestion = test->congestion_used;
3922                     rcv_congestion = test->remote_congestion_used;
3923                 }
3924                 else {
3925                     snd_congestion = test->remote_congestion_used;
3926                     rcv_congestion = test->congestion_used;
3927                 }
3928                 if (snd_congestion) {
3929                     cJSON_AddStringToObject(test->json_end, "sender_tcp_congestion", snd_congestion);
3930                 }
3931                 if (rcv_congestion) {
3932                     cJSON_AddStringToObject(test->json_end, "receiver_tcp_congestion", rcv_congestion);
3933                 }
3934             }
3935         }
3936         else {
3937             if (test->verbose) {
3938                 if (stream_must_be_sender) {
3939                     if (test->bidirectional) {
3940                         iperf_printf(test, report_cpu, report_local, stream_must_be_sender?report_sender:report_receiver, test->cpu_util[0], test->cpu_util[1], test->cpu_util[2], report_remote, stream_must_be_sender?report_receiver:report_sender, test->remote_cpu_util[0], test->remote_cpu_util[1], test->remote_cpu_util[2]);
3941                         iperf_printf(test, report_cpu, report_local, !stream_must_be_sender?report_sender:report_receiver, test->cpu_util[0], test->cpu_util[1], test->cpu_util[2], report_remote, !stream_must_be_sender?report_receiver:report_sender, test->remote_cpu_util[0], test->remote_cpu_util[1], test->remote_cpu_util[2]);
3942                     } else
3943                         iperf_printf(test, report_cpu, report_local, stream_must_be_sender?report_sender:report_receiver, test->cpu_util[0], test->cpu_util[1], test->cpu_util[2], report_remote, stream_must_be_sender?report_receiver:report_sender, test->remote_cpu_util[0], test->remote_cpu_util[1], test->remote_cpu_util[2]);
3944                 }
3945                 if (test->protocol->id == Ptcp) {
3946                     char *snd_congestion = NULL, *rcv_congestion = NULL;
3947                     if (stream_must_be_sender) {
3948                         snd_congestion = test->congestion_used;
3949                         rcv_congestion = test->remote_congestion_used;
3950                     }
3951                     else {
3952                         snd_congestion = test->remote_congestion_used;
3953                         rcv_congestion = test->congestion_used;
3954                     }
3955                     if (snd_congestion) {
3956                         iperf_printf(test, "snd_tcp_congestion %s\n", snd_congestion);
3957                     }
3958                     if (rcv_congestion) {
3959                         iperf_printf(test, "rcv_tcp_congestion %s\n", rcv_congestion);
3960                     }
3961                 }
3962             }
3963 
3964             /* Print server output if we're on the client and it was requested/provided */
3965             if (test->role == 'c' && iperf_get_test_get_server_output(test) && !test->json_output) {
3966                 if (test->json_server_output) {
3967 		    char *str = cJSON_Print(test->json_server_output);
3968                     iperf_printf(test, "\nServer JSON output:\n%s\n", str);
3969 		    cJSON_free(str);
3970                     cJSON_Delete(test->json_server_output);
3971                     test->json_server_output = NULL;
3972                 }
3973                 if (test->server_output_text) {
3974                     iperf_printf(test, "\nServer output:\n%s\n", test->server_output_text);
3975                     test->server_output_text = NULL;
3976                 }
3977             }
3978         }
3979     }
3980 
3981     /* Set real sender_has_retransmits for current side */
3982     if (test->mode == BIDIRECTIONAL)
3983         test->sender_has_retransmits = tmp_sender_has_retransmits;
3984 }
3985 
3986 /**************************************************************************/
3987 
3988 /**
3989  * Main report-printing callback.
3990  * Prints results either during a test (interval report only) or
3991  * after the entire test has been run (last interval report plus
3992  * overall summary).
3993  */
3994 void
3995 iperf_reporter_callback(struct iperf_test *test)
3996 {
3997     switch (test->state) {
3998         case TEST_RUNNING:
3999         case STREAM_RUNNING:
4000             /* print interval results for each stream */
4001             iperf_print_intermediate(test);
4002             break;
4003         case TEST_END:
4004         case DISPLAY_RESULTS:
4005             iperf_print_intermediate(test);
4006             iperf_print_results(test);
4007             break;
4008     }
4009 
4010 }
4011 
4012 /**
4013  * Print the interval results for one stream.
4014  * This function needs to know about the overall test so it can determine the
4015  * context for printing headers, separators, etc.
4016  */
4017 static void
4018 print_interval_results(struct iperf_test *test, struct iperf_stream *sp, cJSON *json_interval_streams)
4019 {
4020     char ubuf[UNIT_LEN];
4021     char nbuf[UNIT_LEN];
4022     char cbuf[UNIT_LEN];
4023     char mbuf[UNIT_LEN];
4024     char zbuf[] = "          ";
4025     double st = 0., et = 0.;
4026     struct iperf_time temp_time;
4027     struct iperf_interval_results *irp = NULL;
4028     double bandwidth, lost_percent;
4029 
4030     if (test->mode == BIDIRECTIONAL) {
4031         sprintf(mbuf, "[%s-%s]", sp->sender?"TX":"RX", test->role == 'c'?"C":"S");
4032     } else {
4033         mbuf[0] = '\0';
4034         zbuf[0] = '\0';
4035     }
4036 
4037     irp = TAILQ_LAST(&sp->result->interval_results, irlisthead); /* get last entry in linked list */
4038     if (irp == NULL) {
4039 	iperf_err(test, "print_interval_results error: interval_results is NULL");
4040         return;
4041     }
4042     if (!test->json_output) {
4043 	/* First stream? */
4044 	if (sp == SLIST_FIRST(&test->streams)) {
4045 	    /* It it's the first interval, print the header;
4046 	    ** else if there's more than one stream, print the separator;
4047 	    ** else nothing.
4048 	    */
4049 	    if (iperf_time_compare(&sp->result->start_time, &irp->interval_start_time) == 0) {
4050 		if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
4051 		    if (test->sender_has_retransmits == 1) {
4052 		        if (test->bidirectional)
4053 		            iperf_printf(test, "%s", report_bw_retrans_cwnd_header_bidir);
4054 		        else
4055 		            iperf_printf(test, "%s", report_bw_retrans_cwnd_header);
4056 		    }
4057 		    else {
4058 	                if (test->bidirectional)
4059 	                    iperf_printf(test, "%s", report_bw_header_bidir);
4060 	                else
4061 	                    iperf_printf(test, "%s", report_bw_header);
4062 	            }
4063 		} else {
4064 		    if (test->mode == SENDER) {
4065 		        iperf_printf(test, "%s", report_bw_udp_sender_header);
4066 		    } else if (test->mode == RECEIVER){
4067 		        iperf_printf(test, "%s", report_bw_udp_header);
4068 		    } else {
4069 		        /* BIDIRECTIONAL */
4070 		        iperf_printf(test, "%s", report_bw_udp_header_bidir);
4071 		    }
4072 		}
4073 	    } else if (test->num_streams > 1)
4074 		iperf_printf(test, "%s", report_bw_separator);
4075 	}
4076     }
4077 
4078     unit_snprintf(ubuf, UNIT_LEN, (double) (irp->bytes_transferred), 'A');
4079     if (irp->interval_duration > 0.0) {
4080 	bandwidth = (double) irp->bytes_transferred / (double) irp->interval_duration;
4081     }
4082     else {
4083 	bandwidth = 0.0;
4084     }
4085     unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
4086 
4087     iperf_time_diff(&sp->result->start_time, &irp->interval_start_time, &temp_time);
4088     st = iperf_time_in_secs(&temp_time);
4089     iperf_time_diff(&sp->result->start_time, &irp->interval_end_time, &temp_time);
4090     et = iperf_time_in_secs(&temp_time);
4091 
4092     if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
4093 	if (test->sender_has_retransmits == 1 && sp->sender) {
4094 	    /* Interval, TCP with retransmits. */
4095 	    if (test->json_output)
4096 		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  snd_wnd:  %d  rtt:  %d  rttvar: %d  pmtu: %d  omitted: %b sender: %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->snd_wnd, (int64_t) irp->rtt, (int64_t) irp->rttvar, (int64_t) irp->pmtu, irp->omitted, sp->sender));
4097 	    else {
4098 		unit_snprintf(cbuf, UNIT_LEN, irp->snd_cwnd, 'A');
4099 		iperf_printf(test, report_bw_retrans_cwnd_format, sp->socket, mbuf, st, et, ubuf, nbuf, irp->interval_retrans, cbuf, irp->omitted?report_omitted:"");
4100 	    }
4101 	} else {
4102 	    /* Interval, TCP without retransmits. */
4103 	    if (test->json_output)
4104 		cJSON_AddItemToArray(json_interval_streams, iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  omitted: %b sender: %b", (int64_t) sp->socket, (double) st, (double) et, (double) irp->interval_duration, (int64_t) irp->bytes_transferred, bandwidth * 8, irp->omitted, sp->sender));
4105 	    else
4106 		iperf_printf(test, report_bw_format, sp->socket, mbuf, st, et, ubuf, nbuf, irp->omitted?report_omitted:"");
4107 	}
4108     } else {
4109 	/* Interval, UDP. */
4110 	if (sp->sender) {
4111 	    if (test->json_output)
4112 		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 sender: %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, sp->sender));
4113 	    else
4114 		iperf_printf(test, report_bw_udp_sender_format, sp->socket, mbuf, st, et, ubuf, nbuf, zbuf, irp->interval_packet_count, irp->omitted?report_omitted:"");
4115 	} else {
4116 	    if (irp->interval_packet_count > 0) {
4117 		lost_percent = 100.0 * irp->interval_cnt_error / irp->interval_packet_count;
4118 	    }
4119 	    else {
4120 		lost_percent = 0.0;
4121 	    }
4122 	    if (test->json_output)
4123 		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 sender: %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, sp->sender));
4124 	    else
4125 		iperf_printf(test, report_bw_udp_format, sp->socket, mbuf, st, et, ubuf, nbuf, irp->jitter * 1000.0, irp->interval_cnt_error, irp->interval_packet_count, lost_percent, irp->omitted?report_omitted:"");
4126 	}
4127     }
4128 
4129     if (test->logfile || test->forceflush)
4130         iflush(test);
4131 }
4132 
4133 /**************************************************************************/
4134 void
4135 iperf_free_stream(struct iperf_stream *sp)
4136 {
4137     struct iperf_interval_results *irp, *nirp;
4138 
4139     /* XXX: need to free interval list too! */
4140     munmap(sp->buffer, sp->test->settings->blksize);
4141     close(sp->buffer_fd);
4142     if (sp->diskfile_fd >= 0)
4143 	close(sp->diskfile_fd);
4144     for (irp = TAILQ_FIRST(&sp->result->interval_results); irp != NULL; irp = nirp) {
4145         nirp = TAILQ_NEXT(irp, irlistentries);
4146         free(irp);
4147     }
4148     free(sp->result);
4149     if (sp->send_timer != NULL)
4150 	tmr_cancel(sp->send_timer);
4151     free(sp);
4152 }
4153 
4154 /**************************************************************************/
4155 struct iperf_stream *
4156 iperf_new_stream(struct iperf_test *test, int s, int sender)
4157 {
4158     struct iperf_stream *sp;
4159     int ret = 0;
4160 
4161     char template[1024];
4162     if (test->tmp_template) {
4163         snprintf(template, sizeof(template) / sizeof(char), "%s", test->tmp_template);
4164     } else {
4165         //find the system temporary dir *unix, windows, cygwin support
4166         char* tempdir = getenv("TMPDIR");
4167         if (tempdir == 0){
4168             tempdir = getenv("TEMP");
4169         }
4170         if (tempdir == 0){
4171             tempdir = getenv("TMP");
4172         }
4173         if (tempdir == 0){
4174             tempdir = "/tmp";
4175         }
4176         snprintf(template, sizeof(template) / sizeof(char), "%s/iperf3.XXXXXX", tempdir);
4177     }
4178 
4179     sp = (struct iperf_stream *) malloc(sizeof(struct iperf_stream));
4180     if (!sp) {
4181         i_errno = IECREATESTREAM;
4182         return NULL;
4183     }
4184 
4185     memset(sp, 0, sizeof(struct iperf_stream));
4186 
4187     sp->sender = sender;
4188     sp->test = test;
4189     sp->settings = test->settings;
4190     sp->result = (struct iperf_stream_result *) malloc(sizeof(struct iperf_stream_result));
4191     if (!sp->result) {
4192         free(sp);
4193         i_errno = IECREATESTREAM;
4194         return NULL;
4195     }
4196 
4197     memset(sp->result, 0, sizeof(struct iperf_stream_result));
4198     TAILQ_INIT(&sp->result->interval_results);
4199 
4200     /* Create and randomize the buffer */
4201     sp->buffer_fd = mkstemp(template);
4202     if (sp->buffer_fd == -1) {
4203         i_errno = IECREATESTREAM;
4204         free(sp->result);
4205         free(sp);
4206         return NULL;
4207     }
4208     if (unlink(template) < 0) {
4209         i_errno = IECREATESTREAM;
4210         free(sp->result);
4211         free(sp);
4212         return NULL;
4213     }
4214     if (ftruncate(sp->buffer_fd, test->settings->blksize) < 0) {
4215         i_errno = IECREATESTREAM;
4216         free(sp->result);
4217         free(sp);
4218         return NULL;
4219     }
4220     sp->buffer = (char *) mmap(NULL, test->settings->blksize, PROT_READ|PROT_WRITE, MAP_PRIVATE, sp->buffer_fd, 0);
4221     if (sp->buffer == MAP_FAILED) {
4222         i_errno = IECREATESTREAM;
4223         free(sp->result);
4224         free(sp);
4225         return NULL;
4226     }
4227     sp->pending_size = 0;
4228 
4229     /* Set socket */
4230     sp->socket = s;
4231 
4232     sp->snd = test->protocol->send;
4233     sp->rcv = test->protocol->recv;
4234 
4235     if (test->diskfile_name != (char*) 0) {
4236 	sp->diskfile_fd = open(test->diskfile_name, sender ? O_RDONLY : (O_WRONLY|O_CREAT|O_TRUNC), S_IRUSR|S_IWUSR);
4237 	if (sp->diskfile_fd == -1) {
4238 	    i_errno = IEFILE;
4239             munmap(sp->buffer, sp->test->settings->blksize);
4240             free(sp->result);
4241             free(sp);
4242 	    return NULL;
4243 	}
4244         sp->snd2 = sp->snd;
4245 	sp->snd = diskfile_send;
4246 	sp->rcv2 = sp->rcv;
4247 	sp->rcv = diskfile_recv;
4248     } else
4249         sp->diskfile_fd = -1;
4250 
4251     /* Initialize stream */
4252     if (test->repeating_payload)
4253         fill_with_repeating_pattern(sp->buffer, test->settings->blksize);
4254     else
4255         ret = readentropy(sp->buffer, test->settings->blksize);
4256 
4257     if ((ret < 0) || (iperf_init_stream(sp, test) < 0)) {
4258         close(sp->buffer_fd);
4259         munmap(sp->buffer, sp->test->settings->blksize);
4260         free(sp->result);
4261         free(sp);
4262         return NULL;
4263     }
4264     iperf_add_stream(test, sp);
4265 
4266     return sp;
4267 }
4268 
4269 /**************************************************************************/
4270 int
4271 iperf_init_stream(struct iperf_stream *sp, struct iperf_test *test)
4272 {
4273     socklen_t len;
4274     int opt;
4275 
4276     len = sizeof(struct sockaddr_storage);
4277     if (getsockname(sp->socket, (struct sockaddr *) &sp->local_addr, &len) < 0) {
4278         i_errno = IEINITSTREAM;
4279         return -1;
4280     }
4281     len = sizeof(struct sockaddr_storage);
4282     if (getpeername(sp->socket, (struct sockaddr *) &sp->remote_addr, &len) < 0) {
4283         i_errno = IEINITSTREAM;
4284         return -1;
4285     }
4286 
4287     /* Set IP TOS */
4288     if ((opt = test->settings->tos)) {
4289         if (getsockdomain(sp->socket) == AF_INET6) {
4290 #ifdef IPV6_TCLASS
4291             if (setsockopt(sp->socket, IPPROTO_IPV6, IPV6_TCLASS, &opt, sizeof(opt)) < 0) {
4292                 i_errno = IESETCOS;
4293                 return -1;
4294             }
4295 #else
4296             i_errno = IESETCOS;
4297             return -1;
4298 #endif
4299         } else {
4300             if (setsockopt(sp->socket, IPPROTO_IP, IP_TOS, &opt, sizeof(opt)) < 0) {
4301                 i_errno = IESETTOS;
4302                 return -1;
4303             }
4304         }
4305     }
4306 
4307 #if defined(HAVE_DONT_FRAGMENT)
4308     /* Set Don't Fragment (DF). Only applicable to IPv4/UDP tests. */
4309     if (iperf_get_test_protocol_id(test) == Pudp &&
4310         getsockdomain(sp->socket) == AF_INET &&
4311         iperf_get_dont_fragment(test)) {
4312 
4313         /*
4314          * There are multiple implementations of this feature depending on the OS.
4315          * We need to handle separately Linux, UNIX, and Windows, as well as
4316          * the case that DF isn't supported at all (such as on macOS).
4317          */
4318 #if defined(IP_MTU_DISCOVER) /* Linux version of IP_DONTFRAG */
4319         opt = IP_PMTUDISC_DO;
4320         if (setsockopt(sp->socket, IPPROTO_IP, IP_MTU_DISCOVER, &opt, sizeof(opt)) < 0) {
4321             i_errno = IESETDONTFRAGMENT;
4322             return -1;
4323         }
4324 #else
4325 #if defined(IP_DONTFRAG) /* UNIX does IP_DONTFRAG */
4326         opt = 1;
4327         if (setsockopt(sp->socket, IPPROTO_IP, IP_DONTFRAG, &opt, sizeof(opt)) < 0) {
4328             i_errno = IESETDONTFRAGMENT;
4329             return -1;
4330         }
4331 #else
4332 #if defined(IP_DONTFRAGMENT) /* Windows does IP_DONTFRAGMENT */
4333         opt = 1;
4334         if (setsockopt(sp->socket, IPPROTO_IP, IP_DONTFRAGMENT, &opt, sizeof(opt)) < 0) {
4335             i_errno = IESETDONTFRAGMENT;
4336             return -1;
4337         }
4338 #else
4339 	i_errno = IESETDONTFRAGMENT;
4340 	return -1;
4341 #endif /* IP_DONTFRAGMENT */
4342 #endif /* IP_DONTFRAG */
4343 #endif /* IP_MTU_DISCOVER */
4344     }
4345 #endif /* HAVE_DONT_FRAGMENT */
4346     return 0;
4347 }
4348 
4349 /**************************************************************************/
4350 void
4351 iperf_add_stream(struct iperf_test *test, struct iperf_stream *sp)
4352 {
4353     int i;
4354     struct iperf_stream *n, *prev;
4355 
4356     if (SLIST_EMPTY(&test->streams)) {
4357         SLIST_INSERT_HEAD(&test->streams, sp, streams);
4358         sp->id = 1;
4359     } else {
4360         // for (n = test->streams, i = 2; n->next; n = n->next, ++i);
4361         // NOTE: this would ideally be set to 1, however this will not
4362         //       be changed since it is not causing a significant problem
4363         //       and changing it would break multi-stream tests between old
4364         //       and new iperf3 versions.
4365         i = 2;
4366         SLIST_FOREACH(n, &test->streams, streams) {
4367             prev = n;
4368             ++i;
4369         }
4370         SLIST_INSERT_AFTER(prev, sp, streams);
4371         sp->id = i;
4372     }
4373 }
4374 
4375 /* This pair of routines gets inserted into the snd/rcv function pointers
4376 ** when there's a -F flag. They handle the file stuff and call the real
4377 ** snd/rcv functions, which have been saved in snd2/rcv2.
4378 **
4379 ** The advantage of doing it this way is that in the much more common
4380 ** case of no -F flag, there is zero extra overhead.
4381 */
4382 
4383 static int
4384 diskfile_send(struct iperf_stream *sp)
4385 {
4386     int r;
4387     int buffer_left = sp->diskfile_left; // represents total data in buffer to be sent out
4388     static int rtot;
4389 
4390     /* if needed, read enough data from the disk to fill up the buffer */
4391     if (sp->diskfile_left < sp->test->settings->blksize && !sp->test->done) {
4392     	r = read(sp->diskfile_fd, sp->buffer, sp->test->settings->blksize -
4393     		 sp->diskfile_left);
4394         buffer_left += r;
4395     	rtot += r;
4396     	if (sp->test->debug) {
4397     	    printf("read %d bytes from file, %d total\n", r, rtot);
4398     	}
4399 
4400         // If the buffer doesn't contain a full buffer at this point,
4401         // adjust the size of the data to send.
4402         if (buffer_left != sp->test->settings->blksize) {
4403             if (sp->test->debug)
4404                 printf("possible eof\n");
4405             // setting data size to be sent,
4406             // which is less than full block/buffer size
4407             // (to be used by iperf_tcp_send, etc.)
4408             sp->pending_size = buffer_left;
4409         }
4410 
4411         // If there's no work left, we're done.
4412         if (buffer_left == 0) {
4413     	    sp->test->done = 1;
4414     	    if (sp->test->debug)
4415     		  printf("done\n");
4416     	}
4417     }
4418 
4419     // If there's no data left in the file or in the buffer, we're done.
4420     // No more data available to be sent.
4421     // Return without sending data to the network
4422     if( sp->test->done || buffer_left == 0 ){
4423         if (sp->test->debug)
4424               printf("already done\n");
4425         sp->test->done = 1;
4426         return 0;
4427     }
4428 
4429     r = sp->snd2(sp);
4430     if (r < 0) {
4431 	return r;
4432     }
4433     /*
4434      * Compute how much data is in the buffer but didn't get sent.
4435      * If there are bytes that got left behind, slide them to the
4436      * front of the buffer so they can hopefully go out on the next
4437      * pass.
4438      */
4439     sp->diskfile_left = buffer_left - r;
4440     if (sp->diskfile_left && sp->diskfile_left < sp->test->settings->blksize) {
4441 	memcpy(sp->buffer,
4442 	       sp->buffer + (sp->test->settings->blksize - sp->diskfile_left),
4443 	       sp->diskfile_left);
4444 	if (sp->test->debug)
4445 	    printf("Shifting %d bytes by %d\n", sp->diskfile_left, (sp->test->settings->blksize - sp->diskfile_left));
4446     }
4447     return r;
4448 }
4449 
4450 static int
4451 diskfile_recv(struct iperf_stream *sp)
4452 {
4453     int r;
4454 
4455     r = sp->rcv2(sp);
4456     if (r > 0) {
4457 	(void) (write(sp->diskfile_fd, sp->buffer, r) + 1);
4458     }
4459     return r;
4460 }
4461 
4462 
4463 void
4464 iperf_catch_sigend(void (*handler)(int))
4465 {
4466 #ifdef SIGINT
4467     signal(SIGINT, handler);
4468 #endif
4469 #ifdef SIGTERM
4470     signal(SIGTERM, handler);
4471 #endif
4472 #ifdef SIGHUP
4473     signal(SIGHUP, handler);
4474 #endif
4475 }
4476 
4477 /**
4478  * Called as a result of getting a signal.
4479  * Depending on the current state of the test (and the role of this
4480  * process) compute and report one more set of ending statistics
4481  * before cleaning up and exiting.
4482  */
4483 void
4484 iperf_got_sigend(struct iperf_test *test)
4485 {
4486     /*
4487      * If we're the client, or if we're a server and running a test,
4488      * then dump out the accumulated stats so far.
4489      */
4490     if (test->role == 'c' ||
4491       (test->role == 's' && test->state == TEST_RUNNING)) {
4492 
4493 	test->done = 1;
4494 	cpu_util(test->cpu_util);
4495 	test->stats_callback(test);
4496 	test->state = DISPLAY_RESULTS; /* change local state only */
4497 	if (test->on_test_finish)
4498 	    test->on_test_finish(test);
4499 	test->reporter_callback(test);
4500     }
4501 
4502     if (test->ctrl_sck >= 0) {
4503 	test->state = (test->role == 'c') ? CLIENT_TERMINATE : SERVER_TERMINATE;
4504 	(void) Nwrite(test->ctrl_sck, (char*) &test->state, sizeof(signed char), Ptcp);
4505     }
4506     i_errno = (test->role == 'c') ? IECLIENTTERM : IESERVERTERM;
4507     iperf_errexit(test, "interrupt - %s", iperf_strerror(i_errno));
4508 }
4509 
4510 /* Try to write a PID file if requested, return -1 on an error. */
4511 int
4512 iperf_create_pidfile(struct iperf_test *test)
4513 {
4514     if (test->pidfile) {
4515 	int fd;
4516 	char buf[8];
4517 
4518 	/* See if the file already exists and we can read it. */
4519 	fd = open(test->pidfile, O_RDONLY, 0);
4520 	if (fd >= 0) {
4521 	    if (read(fd, buf, sizeof(buf) - 1) >= 0) {
4522 
4523 		/* We read some bytes, see if they correspond to a valid PID */
4524 		pid_t pid;
4525 		pid = atoi(buf);
4526 		if (pid > 0) {
4527 
4528 		    /* See if the process exists. */
4529 		    if (kill(pid, 0) == 0) {
4530 			/*
4531 			 * Make sure not to try to delete existing PID file by
4532 			 * scribbling over the pathname we'd use to refer to it.
4533 			 * Then exit with an error.
4534 			 */
4535 			free(test->pidfile);
4536 			test->pidfile = NULL;
4537 			iperf_errexit(test, "Another instance of iperf3 appears to be running");
4538 		    }
4539 		}
4540 	    }
4541 	}
4542 
4543 	/*
4544 	 * File didn't exist, we couldn't read it, or it didn't correspond to
4545 	 * a running process.  Try to create it.
4546 	 */
4547 	fd = open(test->pidfile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR|S_IWUSR);
4548 	if (fd < 0) {
4549 	    return -1;
4550 	}
4551 	snprintf(buf, sizeof(buf), "%d", getpid()); /* no trailing newline */
4552 	if (write(fd, buf, strlen(buf)) < 0) {
4553 	    return -1;
4554 	}
4555 	if (close(fd) < 0) {
4556 	    return -1;
4557 	};
4558     }
4559     return 0;
4560 }
4561 
4562 /* Get rid of a PID file, return -1 on error. */
4563 int
4564 iperf_delete_pidfile(struct iperf_test *test)
4565 {
4566     if (test->pidfile) {
4567 	if (unlink(test->pidfile) < 0) {
4568 	    return -1;
4569 	}
4570     }
4571     return 0;
4572 }
4573 
4574 int
4575 iperf_json_start(struct iperf_test *test)
4576 {
4577     test->json_top = cJSON_CreateObject();
4578     if (test->json_top == NULL)
4579         return -1;
4580     test->json_start = cJSON_CreateObject();
4581     if (test->json_start == NULL)
4582         return -1;
4583     cJSON_AddItemToObject(test->json_top, "start", test->json_start);
4584     test->json_connected = cJSON_CreateArray();
4585     if (test->json_connected == NULL)
4586         return -1;
4587     cJSON_AddItemToObject(test->json_start, "connected", test->json_connected);
4588     test->json_intervals = cJSON_CreateArray();
4589     if (test->json_intervals == NULL)
4590         return -1;
4591     cJSON_AddItemToObject(test->json_top, "intervals", test->json_intervals);
4592     test->json_end = cJSON_CreateObject();
4593     if (test->json_end == NULL)
4594         return -1;
4595     cJSON_AddItemToObject(test->json_top, "end", test->json_end);
4596     return 0;
4597 }
4598 
4599 int
4600 iperf_json_finish(struct iperf_test *test)
4601 {
4602     if (test->title)
4603 	cJSON_AddStringToObject(test->json_top, "title", test->title);
4604     if (test->extra_data)
4605 	cJSON_AddStringToObject(test->json_top, "extra_data", test->extra_data);
4606     /* Include server output */
4607     if (test->json_server_output) {
4608 	cJSON_AddItemToObject(test->json_top, "server_output_json", test->json_server_output);
4609     }
4610     if (test->server_output_text) {
4611 	cJSON_AddStringToObject(test->json_top, "server_output_text", test->server_output_text);
4612     }
4613     // Get ASCII rendering of JSON structure.  Then make our
4614     // own copy of it and return the storage that cJSON allocated
4615     // on our behalf.  We keep our own copy around.
4616     char *str = cJSON_Print(test->json_top);
4617     if (str == NULL)
4618 	return -1;
4619     test->json_output_string = strdup(str);
4620     cJSON_free(str);
4621     if (test->json_output_string == NULL)
4622         return -1;
4623     fprintf(test->outfile, "%s\n", test->json_output_string);
4624     iflush(test);
4625     cJSON_Delete(test->json_top);
4626     test->json_top = test->json_start = test->json_connected = test->json_intervals = test->json_server_output = test->json_end = NULL;
4627     return 0;
4628 }
4629 
4630 
4631 /* CPU affinity stuff - Linux, FreeBSD, and Windows only. */
4632 
4633 int
4634 iperf_setaffinity(struct iperf_test *test, int affinity)
4635 {
4636 #if defined(HAVE_SCHED_SETAFFINITY)
4637     cpu_set_t cpu_set;
4638 
4639     CPU_ZERO(&cpu_set);
4640     CPU_SET(affinity, &cpu_set);
4641     if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0) {
4642 	i_errno = IEAFFINITY;
4643         return -1;
4644     }
4645     return 0;
4646 #elif defined(HAVE_CPUSET_SETAFFINITY)
4647     cpuset_t cpumask;
4648 
4649     if(cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1,
4650                           sizeof(cpuset_t), &test->cpumask) != 0) {
4651         i_errno = IEAFFINITY;
4652         return -1;
4653     }
4654 
4655     CPU_ZERO(&cpumask);
4656     CPU_SET(affinity, &cpumask);
4657 
4658     if(cpuset_setaffinity(CPU_LEVEL_WHICH,CPU_WHICH_PID, -1,
4659                           sizeof(cpuset_t), &cpumask) != 0) {
4660         i_errno = IEAFFINITY;
4661         return -1;
4662     }
4663     return 0;
4664 #elif defined(HAVE_SETPROCESSAFFINITYMASK)
4665 	HANDLE process = GetCurrentProcess();
4666 	DWORD_PTR processAffinityMask = 1 << affinity;
4667 
4668 	if (SetProcessAffinityMask(process, processAffinityMask) == 0) {
4669 		i_errno = IEAFFINITY;
4670 		return -1;
4671 	}
4672 	return 0;
4673 #else /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY nor HAVE_SETPROCESSAFFINITYMASK */
4674     i_errno = IEAFFINITY;
4675     return -1;
4676 #endif /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY nor HAVE_SETPROCESSAFFINITYMASK */
4677 }
4678 
4679 int
4680 iperf_clearaffinity(struct iperf_test *test)
4681 {
4682 #if defined(HAVE_SCHED_SETAFFINITY)
4683     cpu_set_t cpu_set;
4684     int i;
4685 
4686     CPU_ZERO(&cpu_set);
4687     for (i = 0; i < CPU_SETSIZE; ++i)
4688 	CPU_SET(i, &cpu_set);
4689     if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0) {
4690 	i_errno = IEAFFINITY;
4691         return -1;
4692     }
4693     return 0;
4694 #elif defined(HAVE_CPUSET_SETAFFINITY)
4695     if(cpuset_setaffinity(CPU_LEVEL_WHICH,CPU_WHICH_PID, -1,
4696                           sizeof(cpuset_t), &test->cpumask) != 0) {
4697         i_errno = IEAFFINITY;
4698         return -1;
4699     }
4700     return 0;
4701 #elif defined(HAVE_SETPROCESSAFFINITYMASK)
4702 	HANDLE process = GetCurrentProcess();
4703 	DWORD_PTR processAffinityMask;
4704 	DWORD_PTR lpSystemAffinityMask;
4705 
4706 	if (GetProcessAffinityMask(process, &processAffinityMask, &lpSystemAffinityMask) == 0
4707 			|| SetProcessAffinityMask(process, lpSystemAffinityMask) == 0) {
4708 		i_errno = IEAFFINITY;
4709 		return -1;
4710 	}
4711 	return 0;
4712 #else /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY nor HAVE_SETPROCESSAFFINITYMASK */
4713     i_errno = IEAFFINITY;
4714     return -1;
4715 #endif /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY nor HAVE_SETPROCESSAFFINITYMASK */
4716 }
4717 
4718 static char iperf_timestr[100];
4719 static char linebuffer[1024];
4720 
4721 int
4722 iperf_printf(struct iperf_test *test, const char* format, ...)
4723 {
4724     va_list argp;
4725     int r = 0, r0;
4726     time_t now;
4727     struct tm *ltm = NULL;
4728     char *ct = NULL;
4729 
4730     /* Timestamp if requested */
4731     if (iperf_get_test_timestamps(test)) {
4732 	time(&now);
4733 	ltm = localtime(&now);
4734 	strftime(iperf_timestr, sizeof(iperf_timestr), iperf_get_test_timestamp_format(test), ltm);
4735 	ct = iperf_timestr;
4736     }
4737 
4738     /*
4739      * There are roughly two use cases here.  If we're the client,
4740      * want to print stuff directly to the output stream.
4741      * If we're the sender we might need to buffer up output to send
4742      * to the client.
4743      *
4744      * This doesn't make a whole lot of difference except there are
4745      * some chunks of output on the client (on particular the whole
4746      * of the server output with --get-server-output) that could
4747      * easily exceed the size of the line buffer, but which don't need
4748      * to be buffered up anyway.
4749      */
4750     if (test->role == 'c') {
4751 	if (ct) {
4752             r0 = fprintf(test->outfile, "%s", ct);
4753             if (r0 < 0)
4754                 return r0;
4755             r += r0;
4756 	}
4757 	if (test->title) {
4758 	    r0 = fprintf(test->outfile, "%s:  ", test->title);
4759             if (r0 < 0)
4760                 return r0;
4761             r += r0;
4762         }
4763 	va_start(argp, format);
4764 	r0 = vfprintf(test->outfile, format, argp);
4765 	va_end(argp);
4766         if (r0 < 0)
4767             return r0;
4768         r += r0;
4769     }
4770     else if (test->role == 's') {
4771 	if (ct) {
4772 	    r0 = snprintf(linebuffer, sizeof(linebuffer), "%s", ct);
4773             if (r0 < 0)
4774                 return r0;
4775             r += r0;
4776 	}
4777         /* Should always be true as long as sizeof(ct) < sizeof(linebuffer) */
4778         if (r < sizeof(linebuffer)) {
4779             va_start(argp, format);
4780             r0 = vsnprintf(linebuffer + r, sizeof(linebuffer) - r, format, argp);
4781             va_end(argp);
4782             if (r0 < 0)
4783                 return r0;
4784             r += r0;
4785         }
4786 	fprintf(test->outfile, "%s", linebuffer);
4787 
4788 	if (test->role == 's' && iperf_get_test_get_server_output(test)) {
4789 	    struct iperf_textline *l = (struct iperf_textline *) malloc(sizeof(struct iperf_textline));
4790 	    l->line = strdup(linebuffer);
4791 	    TAILQ_INSERT_TAIL(&(test->server_output_list), l, textlineentries);
4792 	}
4793     }
4794     return r;
4795 }
4796 
4797 int
4798 iflush(struct iperf_test *test)
4799 {
4800     return fflush(test->outfile);
4801 }
4802