xref: /iperf/src/iperf_api.c (revision b97df9a9)
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         {"snd-timeout", required_argument, NULL, OPT_SND_TIMEOUT},
1081         {"debug", optional_argument, NULL, 'd'},
1082         {"help", no_argument, NULL, 'h'},
1083         {NULL, 0, NULL, 0}
1084     };
1085     int flag;
1086     int portno;
1087     int blksize;
1088     int server_flag, client_flag, rate_flag, duration_flag, rcv_timeout_flag, snd_timeout_flag;
1089     char *endptr;
1090 #if defined(HAVE_CPU_AFFINITY)
1091     char* comma;
1092 #endif /* HAVE_CPU_AFFINITY */
1093     char* slash;
1094     char *p, *p1;
1095     struct xbind_entry *xbe;
1096     double farg;
1097     int rcv_timeout_in = 0;
1098 
1099     blksize = 0;
1100     server_flag = client_flag = rate_flag = duration_flag = rcv_timeout_flag = snd_timeout_flag =0;
1101 #if defined(HAVE_SSL)
1102     char *client_username = NULL, *client_rsa_public_key = NULL, *server_rsa_private_key = NULL;
1103 #endif /* HAVE_SSL */
1104 
1105     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) {
1106         switch (flag) {
1107             case 'p':
1108 		portno = atoi(optarg);
1109 		if (portno < 1 || portno > 65535) {
1110 		    i_errno = IEBADPORT;
1111 		    return -1;
1112 		}
1113 		test->server_port = portno;
1114                 break;
1115             case 'f':
1116 		if (!optarg) {
1117 		    i_errno = IEBADFORMAT;
1118 		    return -1;
1119 		}
1120 		test->settings->unit_format = *optarg;
1121 		if (test->settings->unit_format == 'k' ||
1122 		    test->settings->unit_format == 'K' ||
1123 		    test->settings->unit_format == 'm' ||
1124 		    test->settings->unit_format == 'M' ||
1125 		    test->settings->unit_format == 'g' ||
1126 		    test->settings->unit_format == 'G' ||
1127 		    test->settings->unit_format == 't' ||
1128 		    test->settings->unit_format == 'T') {
1129 			break;
1130 		}
1131 		else {
1132 		    i_errno = IEBADFORMAT;
1133 		    return -1;
1134 		}
1135                 break;
1136             case 'i':
1137                 /* XXX: could potentially want separate stat collection and reporting intervals,
1138                    but just set them to be the same for now */
1139                 test->stats_interval = test->reporter_interval = atof(optarg);
1140                 if ((test->stats_interval < MIN_INTERVAL || test->stats_interval > MAX_INTERVAL) && test->stats_interval != 0) {
1141                     i_errno = IEINTERVAL;
1142                     return -1;
1143                 }
1144                 break;
1145             case 'D':
1146 		test->daemon = 1;
1147 		server_flag = 1;
1148 	        break;
1149             case '1':
1150 		test->one_off = 1;
1151 		server_flag = 1;
1152 	        break;
1153             case 'V':
1154                 test->verbose = 1;
1155                 break;
1156             case 'J':
1157                 test->json_output = 1;
1158                 break;
1159             case 'v':
1160                 printf("%s (cJSON %s)\n%s\n%s\n", version, cJSON_Version(), get_system_info(),
1161 		       get_optional_features());
1162                 exit(0);
1163             case 's':
1164                 if (test->role == 'c') {
1165                     i_errno = IESERVCLIENT;
1166                     return -1;
1167                 }
1168 		iperf_set_test_role(test, 's');
1169                 break;
1170             case 'c':
1171                 if (test->role == 's') {
1172                     i_errno = IESERVCLIENT;
1173                     return -1;
1174                 }
1175 		iperf_set_test_role(test, 'c');
1176 		iperf_set_test_server_hostname(test, optarg);
1177 
1178                 if (iperf_parse_hostname(test, optarg, &p, &p1)) {
1179 #if defined(HAVE_SO_BINDTODEVICE)
1180                     /* Get rid of the hostname we saved earlier. */
1181                     free(iperf_get_test_server_hostname(test));
1182                     iperf_set_test_server_hostname(test, p);
1183                     iperf_set_test_bind_dev(test, p1);
1184 #else /* HAVE_SO_BINDTODEVICE */
1185                     i_errno = IEBINDDEVNOSUPPORT;
1186                     return -1;
1187 #endif /* HAVE_SO_BINDTODEVICE */
1188                 }
1189                 break;
1190             case 'u':
1191                 set_protocol(test, Pudp);
1192 		client_flag = 1;
1193                 break;
1194             case OPT_SCTP:
1195 #if defined(HAVE_SCTP_H)
1196                 set_protocol(test, Psctp);
1197                 client_flag = 1;
1198                 break;
1199 #else /* HAVE_SCTP_H */
1200                 i_errno = IEUNIMP;
1201                 return -1;
1202 #endif /* HAVE_SCTP_H */
1203 
1204             case OPT_NUMSTREAMS:
1205 #if defined(linux) || defined(__FreeBSD__)
1206                 test->settings->num_ostreams = unit_atoi(optarg);
1207                 client_flag = 1;
1208 #else /* linux */
1209                 i_errno = IEUNIMP;
1210                 return -1;
1211 #endif /* linux */
1212             case 'b':
1213 		slash = strchr(optarg, '/');
1214 		if (slash) {
1215 		    *slash = '\0';
1216 		    ++slash;
1217 		    test->settings->burst = atoi(slash);
1218 		    if (test->settings->burst <= 0 ||
1219 		        test->settings->burst > MAX_BURST) {
1220 			i_errno = IEBURST;
1221 			return -1;
1222 		    }
1223 		}
1224                 test->settings->rate = unit_atof_rate(optarg);
1225 		rate_flag = 1;
1226 		client_flag = 1;
1227                 break;
1228             case OPT_SERVER_BITRATE_LIMIT:
1229 		slash = strchr(optarg, '/');
1230 		if (slash) {
1231 		    *slash = '\0';
1232 		    ++slash;
1233 		    test->settings->bitrate_limit_interval = atof(slash);
1234 		    if (test->settings->bitrate_limit_interval != 0 &&	/* Using same Max/Min limits as for Stats Interval */
1235 		        (test->settings->bitrate_limit_interval < MIN_INTERVAL || test->settings->bitrate_limit_interval > MAX_INTERVAL) ) {
1236 			i_errno = IETOTALINTERVAL;
1237 			return -1;
1238 		    }
1239 		}
1240 		test->settings->bitrate_limit = unit_atof_rate(optarg);
1241 		server_flag = 1;
1242 	        break;
1243             case 't':
1244                 test->duration = atoi(optarg);
1245                 if (test->duration > MAX_TIME) {
1246                     i_errno = IEDURATION;
1247                     return -1;
1248                 }
1249 		duration_flag = 1;
1250 		client_flag = 1;
1251                 break;
1252             case 'n':
1253                 test->settings->bytes = unit_atoi(optarg);
1254 		client_flag = 1;
1255                 break;
1256             case 'k':
1257                 test->settings->blocks = unit_atoi(optarg);
1258 		client_flag = 1;
1259                 break;
1260             case 'l':
1261                 blksize = unit_atoi(optarg);
1262 		client_flag = 1;
1263                 break;
1264             case 'P':
1265                 test->num_streams = atoi(optarg);
1266                 if (test->num_streams > MAX_STREAMS) {
1267                     i_errno = IENUMSTREAMS;
1268                     return -1;
1269                 }
1270 		client_flag = 1;
1271                 break;
1272             case 'R':
1273                 if (test->bidirectional) {
1274                     i_errno = IEREVERSEBIDIR;
1275                     return -1;
1276                 }
1277 		iperf_set_test_reverse(test, 1);
1278 		client_flag = 1;
1279                 break;
1280             case OPT_BIDIRECTIONAL:
1281                 if (test->reverse) {
1282                     i_errno = IEREVERSEBIDIR;
1283                     return -1;
1284                 }
1285                 iperf_set_test_bidirectional(test, 1);
1286                 client_flag = 1;
1287                 break;
1288             case 'w':
1289                 // XXX: This is a socket buffer, not specific to TCP
1290 		// Do sanity checks as double-precision floating point
1291 		// to avoid possible integer overflows.
1292                 farg = unit_atof(optarg);
1293                 if (farg > (double) MAX_TCP_BUFFER) {
1294                     i_errno = IEBUFSIZE;
1295                     return -1;
1296                 }
1297                 test->settings->socket_bufsize = (int) farg;
1298 		client_flag = 1;
1299                 break;
1300 
1301             case 'B':
1302                 iperf_set_test_bind_address(test, optarg);
1303 
1304                 if (iperf_parse_hostname(test, optarg, &p, &p1)) {
1305 #if defined(HAVE_SO_BINDTODEVICE)
1306                     /* Get rid of the hostname we saved earlier. */
1307                     free(iperf_get_test_server_hostname(test));
1308                     iperf_set_test_server_hostname(test, p);
1309                     iperf_set_test_bind_dev(test, p1);
1310 #else /* HAVE_SO_BINDTODEVICE */
1311                     i_errno = IEBINDDEVNOSUPPORT;
1312                     return -1;
1313 #endif /* HAVE_SO_BINDTODEVICE */
1314                 }
1315                 break;
1316 #if defined (HAVE_SO_BINDTODEVICE)
1317             case OPT_BIND_DEV:
1318                 iperf_set_test_bind_dev(test, optarg);
1319                 break;
1320 #endif /* HAVE_SO_BINDTODEVICE */
1321             case OPT_CLIENT_PORT:
1322 		portno = atoi(optarg);
1323 		if (portno < 1 || portno > 65535) {
1324 		    i_errno = IEBADPORT;
1325 		    return -1;
1326 		}
1327                 test->bind_port = portno;
1328                 break;
1329             case 'M':
1330                 test->settings->mss = atoi(optarg);
1331                 if (test->settings->mss > MAX_MSS) {
1332                     i_errno = IEMSS;
1333                     return -1;
1334                 }
1335 		client_flag = 1;
1336                 break;
1337             case 'N':
1338                 test->no_delay = 1;
1339 		client_flag = 1;
1340                 break;
1341             case '4':
1342                 test->settings->domain = AF_INET;
1343                 break;
1344             case '6':
1345                 test->settings->domain = AF_INET6;
1346                 break;
1347             case 'S':
1348                 test->settings->tos = strtol(optarg, &endptr, 0);
1349 		if (endptr == optarg ||
1350 		    test->settings->tos < 0 ||
1351 		    test->settings->tos > 255) {
1352 		    i_errno = IEBADTOS;
1353 		    return -1;
1354 		}
1355 		client_flag = 1;
1356                 break;
1357 	    case OPT_DSCP:
1358                 test->settings->tos = parse_qos(optarg);
1359 		if(test->settings->tos < 0) {
1360 			i_errno = IEBADTOS;
1361 			return -1;
1362 		}
1363 		client_flag = 1;
1364                 break;
1365 	    case OPT_EXTRA_DATA:
1366 		test->extra_data = strdup(optarg);
1367 		client_flag = 1;
1368 	        break;
1369             case 'L':
1370 #if defined(HAVE_FLOWLABEL)
1371                 test->settings->flowlabel = strtol(optarg, &endptr, 0);
1372 		if (endptr == optarg ||
1373 		    test->settings->flowlabel < 1 || test->settings->flowlabel > 0xfffff) {
1374                     i_errno = IESETFLOW;
1375                     return -1;
1376 		}
1377 		client_flag = 1;
1378 #else /* HAVE_FLOWLABEL */
1379                 i_errno = IEUNIMP;
1380                 return -1;
1381 #endif /* HAVE_FLOWLABEL */
1382                 break;
1383             case 'X':
1384 		xbe = (struct xbind_entry *)malloc(sizeof(struct xbind_entry));
1385                 if (!xbe) {
1386 		    i_errno = IESETSCTPBINDX;
1387                     return -1;
1388                 }
1389 	        memset(xbe, 0, sizeof(*xbe));
1390                 xbe->name = strdup(optarg);
1391                 if (!xbe->name) {
1392 		    i_errno = IESETSCTPBINDX;
1393                     return -1;
1394                 }
1395 		TAILQ_INSERT_TAIL(&test->xbind_addrs, xbe, link);
1396                 break;
1397             case 'Z':
1398                 if (!has_sendfile()) {
1399                     i_errno = IENOSENDFILE;
1400                     return -1;
1401                 }
1402                 test->zerocopy = 1;
1403 		client_flag = 1;
1404                 break;
1405             case OPT_REPEATING_PAYLOAD:
1406                 test->repeating_payload = 1;
1407                 client_flag = 1;
1408                 break;
1409             case OPT_TIMESTAMPS:
1410                 iperf_set_test_timestamps(test, 1);
1411 		if (optarg) {
1412 		    iperf_set_test_timestamp_format(test, optarg);
1413 		}
1414 		else {
1415 		    iperf_set_test_timestamp_format(test, TIMESTAMP_FORMAT);
1416 		}
1417                 break;
1418             case 'O':
1419                 test->omit = atoi(optarg);
1420                 if (test->omit < 0 || test->omit > 60) {
1421                     i_errno = IEOMIT;
1422                     return -1;
1423                 }
1424 		client_flag = 1;
1425                 break;
1426             case 'F':
1427                 test->diskfile_name = optarg;
1428                 break;
1429             case OPT_IDLE_TIMEOUT:
1430                 test->settings->idle_timeout = atoi(optarg);
1431                 if (test->settings->idle_timeout < 1 || test->settings->idle_timeout > MAX_TIME) {
1432                     i_errno = IEIDLETIMEOUT;
1433                     return -1;
1434                 }
1435 		server_flag = 1;
1436 	        break;
1437             case OPT_RCV_TIMEOUT:
1438                 rcv_timeout_in = atoi(optarg);
1439                 if (rcv_timeout_in < MIN_NO_MSG_RCVD_TIMEOUT || rcv_timeout_in > MAX_TIME * SEC_TO_mS) {
1440                     i_errno = IERCVTIMEOUT;
1441                     return -1;
1442                 }
1443                 test->settings->rcv_timeout.secs = rcv_timeout_in / SEC_TO_mS;
1444                 test->settings->rcv_timeout.usecs = (rcv_timeout_in % SEC_TO_mS) * mS_TO_US;
1445                 rcv_timeout_flag = 1;
1446 	        break;
1447 #if defined(HAVE_TCP_USER_TIMEOUT)
1448             case OPT_SND_TIMEOUT:
1449                 test->settings->snd_timeout = atoi(optarg);
1450                 if (test->settings->snd_timeout < 0 || test->settings->snd_timeout > MAX_TIME * SEC_TO_mS) {
1451                     i_errno = IESNDTIMEOUT;
1452                     return -1;
1453                 }
1454                 snd_timeout_flag = 1;
1455 	        break;
1456 #endif /* HAVE_TCP_USER_TIMEOUT */
1457             case 'A':
1458 #if defined(HAVE_CPU_AFFINITY)
1459                 test->affinity = strtol(optarg, &endptr, 0);
1460                 if (endptr == optarg ||
1461 		    test->affinity < 0 || test->affinity > 1024) {
1462                     i_errno = IEAFFINITY;
1463                     return -1;
1464                 }
1465 		comma = strchr(optarg, ',');
1466 		if (comma != NULL) {
1467 		    test->server_affinity = atoi(comma+1);
1468 		    if (test->server_affinity < 0 || test->server_affinity > 1024) {
1469 			i_errno = IEAFFINITY;
1470 			return -1;
1471 		    }
1472 		    client_flag = 1;
1473 		}
1474 #else /* HAVE_CPU_AFFINITY */
1475                 i_errno = IEUNIMP;
1476                 return -1;
1477 #endif /* HAVE_CPU_AFFINITY */
1478                 break;
1479             case 'T':
1480                 test->title = strdup(optarg);
1481 		client_flag = 1;
1482                 break;
1483 	    case 'C':
1484 #if defined(HAVE_TCP_CONGESTION)
1485 		test->congestion = strdup(optarg);
1486 		client_flag = 1;
1487 #else /* HAVE_TCP_CONGESTION */
1488 		i_errno = IEUNIMP;
1489 		return -1;
1490 #endif /* HAVE_TCP_CONGESTION */
1491 		break;
1492 	    case 'd':
1493 		test->debug = 1;
1494                 test->debug_level = DEBUG_LEVEL_MAX;
1495                 if (optarg) {
1496                     test->debug_level = atoi(optarg);
1497                     if (test->debug_level < 0)
1498                         test->debug_level = DEBUG_LEVEL_MAX;
1499                 }
1500 		break;
1501 	    case 'I':
1502 		test->pidfile = strdup(optarg);
1503 	        break;
1504 	    case OPT_LOGFILE:
1505 		test->logfile = strdup(optarg);
1506 		break;
1507 	    case OPT_FORCEFLUSH:
1508 		test->forceflush = 1;
1509 		break;
1510 	    case OPT_GET_SERVER_OUTPUT:
1511 		test->get_server_output = 1;
1512 		client_flag = 1;
1513 		break;
1514 	    case OPT_UDP_COUNTERS_64BIT:
1515 		test->udp_counters_64bit = 1;
1516 		break;
1517 	    case OPT_NO_FQ_SOCKET_PACING:
1518 #if defined(HAVE_SO_MAX_PACING_RATE)
1519 		printf("Warning:  --no-fq-socket-pacing is deprecated\n");
1520 		test->settings->fqrate = 0;
1521 		client_flag = 1;
1522 #else /* HAVE_SO_MAX_PACING_RATE */
1523 		i_errno = IEUNIMP;
1524 		return -1;
1525 #endif
1526 		break;
1527 	    case OPT_FQ_RATE:
1528 #if defined(HAVE_SO_MAX_PACING_RATE)
1529 		test->settings->fqrate = unit_atof_rate(optarg);
1530 		client_flag = 1;
1531 #else /* HAVE_SO_MAX_PACING_RATE */
1532 		i_errno = IEUNIMP;
1533 		return -1;
1534 #endif
1535 		break;
1536 #if defined(HAVE_DONT_FRAGMENT)
1537         case OPT_DONT_FRAGMENT:
1538             test->settings->dont_fragment = 1;
1539             client_flag = 1;
1540             break;
1541 #endif /* HAVE_DONT_FRAGMENT */
1542 #if defined(HAVE_SSL)
1543         case OPT_CLIENT_USERNAME:
1544             client_username = strdup(optarg);
1545             break;
1546         case OPT_CLIENT_RSA_PUBLIC_KEY:
1547             client_rsa_public_key = strdup(optarg);
1548             break;
1549         case OPT_SERVER_RSA_PRIVATE_KEY:
1550             server_rsa_private_key = strdup(optarg);
1551             break;
1552         case OPT_SERVER_AUTHORIZED_USERS:
1553             test->server_authorized_users = strdup(optarg);
1554             break;
1555         case OPT_SERVER_SKEW_THRESHOLD:
1556             test->server_skew_threshold = atoi(optarg);
1557             if(test->server_skew_threshold <= 0){
1558                 i_errno = IESKEWTHRESHOLD;
1559                 return -1;
1560             }
1561             break;
1562 #endif /* HAVE_SSL */
1563 	    case OPT_PACING_TIMER:
1564 		test->settings->pacing_timer = unit_atoi(optarg);
1565 		client_flag = 1;
1566 		break;
1567 	    case OPT_CONNECT_TIMEOUT:
1568 		test->settings->connect_timeout = unit_atoi(optarg);
1569 		client_flag = 1;
1570 		break;
1571 	    case 'h':
1572 		usage_long(stdout);
1573 		exit(0);
1574             default:
1575                 usage_long(stderr);
1576                 exit(1);
1577         }
1578     }
1579 
1580     /* Check flag / role compatibility. */
1581     if (test->role == 'c' && server_flag) {
1582         i_errno = IESERVERONLY;
1583         return -1;
1584     }
1585     if (test->role == 's' && client_flag) {
1586         i_errno = IECLIENTONLY;
1587         return -1;
1588     }
1589 
1590 #if defined(HAVE_SSL)
1591 
1592     if (test->role == 's' && (client_username || client_rsa_public_key)){
1593         i_errno = IECLIENTONLY;
1594         return -1;
1595     } else if (test->role == 'c' && (client_username || client_rsa_public_key) &&
1596         !(client_username && client_rsa_public_key)) {
1597         i_errno = IESETCLIENTAUTH;
1598         return -1;
1599     } else if (test->role == 'c' && (client_username && client_rsa_public_key)){
1600 
1601         char *client_password = NULL;
1602         size_t s;
1603         /* Need to copy env var, so we can do a common free */
1604         if ((client_password = getenv("IPERF3_PASSWORD")) != NULL)
1605              client_password = strdup(client_password);
1606         else if (iperf_getpass(&client_password, &s, stdin) < 0){
1607             i_errno = IESETCLIENTAUTH;
1608             return -1;
1609         }
1610         if (test_load_pubkey_from_file(client_rsa_public_key) < 0){
1611             iperf_err(test, "%s\n", ERR_error_string(ERR_get_error(), NULL));
1612             i_errno = IESETCLIENTAUTH;
1613             return -1;
1614         }
1615 
1616         test->settings->client_username = client_username;
1617         test->settings->client_password = client_password;
1618         test->settings->client_rsa_pubkey = load_pubkey_from_file(client_rsa_public_key);
1619 	free(client_rsa_public_key);
1620 	client_rsa_public_key = NULL;
1621     }
1622 
1623     if (test->role == 'c' && (server_rsa_private_key || test->server_authorized_users)){
1624         i_errno = IESERVERONLY;
1625         return -1;
1626     } else if (test->role == 'c' && (test->server_skew_threshold != 0)){
1627         i_errno = IESERVERONLY;
1628         return -1;
1629     } else if (test->role == 'c' && rcv_timeout_flag && test->mode == SENDER){
1630         i_errno = IERVRSONLYRCVTIMEOUT;
1631         return -1;
1632     } else if (test->role == 's' && (server_rsa_private_key || test->server_authorized_users) &&
1633         !(server_rsa_private_key && test->server_authorized_users)) {
1634          i_errno = IESETSERVERAUTH;
1635         return -1;
1636     } else if (test->role == 's' && server_rsa_private_key) {
1637         test->server_rsa_private_key = load_privkey_from_file(server_rsa_private_key);
1638         if (test->server_rsa_private_key == NULL){
1639             iperf_err(test, "%s\n", ERR_error_string(ERR_get_error(), NULL));
1640             i_errno = IESETSERVERAUTH;
1641             return -1;
1642         }
1643 	    free(server_rsa_private_key);
1644 	    server_rsa_private_key = NULL;
1645 
1646         if(test->server_skew_threshold == 0){
1647             // Set default value for time skew threshold
1648             test->server_skew_threshold=10;
1649         }
1650     }
1651 
1652 #endif //HAVE_SSL
1653     if (blksize == 0) {
1654 	if (test->protocol->id == Pudp)
1655 	    blksize = 0;	/* try to dynamically determine from MSS */
1656 	else if (test->protocol->id == Psctp)
1657 	    blksize = DEFAULT_SCTP_BLKSIZE;
1658 	else
1659 	    blksize = DEFAULT_TCP_BLKSIZE;
1660     }
1661     if ((test->protocol->id != Pudp && blksize <= 0)
1662 	|| blksize > MAX_BLOCKSIZE) {
1663 	i_errno = IEBLOCKSIZE;
1664 	return -1;
1665     }
1666     if (test->protocol->id == Pudp &&
1667 	(blksize > 0 &&
1668 	    (blksize < MIN_UDP_BLOCKSIZE || blksize > MAX_UDP_BLOCKSIZE))) {
1669 	i_errno = IEUDPBLOCKSIZE;
1670 	return -1;
1671     }
1672     test->settings->blksize = blksize;
1673 
1674     if (!rate_flag)
1675 	test->settings->rate = test->protocol->id == Pudp ? UDP_RATE : 0;
1676 
1677     /* if no bytes or blocks specified, nor a duration_flag, and we have -F,
1678     ** get the file-size as the bytes count to be transferred
1679     */
1680     if (test->settings->bytes == 0 &&
1681         test->settings->blocks == 0 &&
1682         ! duration_flag &&
1683         test->diskfile_name != (char*) 0 &&
1684         test->role == 'c'
1685         ){
1686         struct stat st;
1687         if( stat(test->diskfile_name, &st) == 0 ){
1688             iperf_size_t file_bytes = st.st_size;
1689             test->settings->bytes = file_bytes;
1690             if (test->debug)
1691                 printf("End condition set to file-size: %"PRIu64" bytes\n", test->settings->bytes);
1692         }
1693         // if failing to read file stat, it should fallback to default duration mode
1694     }
1695 
1696     if ((test->settings->bytes != 0 || test->settings->blocks != 0) && ! duration_flag)
1697         test->duration = 0;
1698 
1699     /* Disallow specifying multiple test end conditions. The code actually
1700     ** works just fine without this prohibition. As soon as any one of the
1701     ** three possible end conditions is met, the test ends. So this check
1702     ** could be removed if desired.
1703     */
1704     if ((duration_flag && test->settings->bytes != 0) ||
1705         (duration_flag && test->settings->blocks != 0) ||
1706 	(test->settings->bytes != 0 && test->settings->blocks != 0)) {
1707         i_errno = IEENDCONDITIONS;
1708         return -1;
1709     }
1710 
1711     /* For subsequent calls to getopt */
1712 #ifdef __APPLE__
1713     optreset = 1;
1714 #endif
1715     optind = 0;
1716 
1717     if ((test->role != 'c') && (test->role != 's')) {
1718         i_errno = IENOROLE;
1719         return -1;
1720     }
1721 
1722     /* Set Total-rate average interval to multiplicity of State interval */
1723     if (test->settings->bitrate_limit_interval != 0) {
1724 	test->settings->bitrate_limit_stats_per_interval =
1725 	    (test->settings->bitrate_limit_interval <= test->stats_interval ?
1726 	    1 : round(test->settings->bitrate_limit_interval/test->stats_interval) );
1727     }
1728 
1729     /* Show warning if JSON output is used with explicit report format */
1730     if ((test->json_output) && (test->settings->unit_format != 'a')) {
1731         warning("Report format (-f) flag ignored with JSON output (-J)");
1732     }
1733 
1734     /* Show warning if JSON output is used with verbose or debug flags */
1735     if (test->json_output && test->verbose) {
1736         warning("Verbose output (-v) may interfere with JSON output (-J)");
1737     }
1738     if (test->json_output && test->debug) {
1739         warning("Debug output (-d) may interfere with JSON output (-J)");
1740     }
1741 
1742     return 0;
1743 }
1744 
1745 /*
1746  * Open the file specified by test->logfile and set test->outfile to its' FD.
1747  */
1748 int iperf_open_logfile(struct iperf_test *test)
1749 {
1750     test->outfile = fopen(test->logfile, "a+");
1751     if (test->outfile == NULL) {
1752         i_errno = IELOGFILE;
1753         return -1;
1754     }
1755 
1756     return 0;
1757 }
1758 
1759 int
1760 iperf_set_send_state(struct iperf_test *test, signed char state)
1761 {
1762     if (test->ctrl_sck >= 0) {
1763         test->state = state;
1764         if (Nwrite(test->ctrl_sck, (char*) &state, sizeof(state), Ptcp) < 0) {
1765 	    i_errno = IESENDMESSAGE;
1766 	    return -1;
1767         }
1768     }
1769     return 0;
1770 }
1771 
1772 void
1773 iperf_check_throttle(struct iperf_stream *sp, struct iperf_time *nowP)
1774 {
1775     struct iperf_time temp_time;
1776     double seconds;
1777     uint64_t bits_per_second;
1778 
1779     if (sp->test->done || sp->test->settings->rate == 0)
1780         return;
1781     iperf_time_diff(&sp->result->start_time_fixed, nowP, &temp_time);
1782     seconds = iperf_time_in_secs(&temp_time);
1783     bits_per_second = sp->result->bytes_sent * 8 / seconds;
1784     if (bits_per_second < sp->test->settings->rate) {
1785         sp->green_light = 1;
1786         FD_SET(sp->socket, &sp->test->write_set);
1787     } else {
1788         sp->green_light = 0;
1789         FD_CLR(sp->socket, &sp->test->write_set);
1790     }
1791 }
1792 
1793 /* Verify that average traffic is not greater than the specified limit */
1794 void
1795 iperf_check_total_rate(struct iperf_test *test, iperf_size_t last_interval_bytes_transferred)
1796 {
1797     double seconds;
1798     uint64_t bits_per_second;
1799     iperf_size_t total_bytes;
1800     int i;
1801 
1802     if (test->done || test->settings->bitrate_limit == 0)    // Continue only if check should be done
1803         return;
1804 
1805     /* Add last inetrval's transferred bytes to the array */
1806     if (++test->bitrate_limit_last_interval_index >= test->settings->bitrate_limit_stats_per_interval)
1807         test->bitrate_limit_last_interval_index = 0;
1808     test->bitrate_limit_intervals_traffic_bytes[test->bitrate_limit_last_interval_index] = last_interval_bytes_transferred;
1809 
1810     /* Ensure that enough stats periods passed to allow averaging throughput */
1811     test->bitrate_limit_stats_count += 1;
1812     if (test->bitrate_limit_stats_count < test->settings->bitrate_limit_stats_per_interval)
1813         return;
1814 
1815      /* Calculating total bytes traffic to be averaged */
1816     for (total_bytes = 0, i = 0; i < test->settings->bitrate_limit_stats_per_interval; i++) {
1817         total_bytes += test->bitrate_limit_intervals_traffic_bytes[i];
1818     }
1819 
1820     seconds = test->stats_interval * test->settings->bitrate_limit_stats_per_interval;
1821     bits_per_second = total_bytes * 8 / seconds;
1822     if (test->debug) {
1823         iperf_printf(test,"Interval %" PRIu64 " - throughput %" PRIu64 " bps (limit %" PRIu64 ")\n", test->bitrate_limit_stats_count, bits_per_second, test->settings->bitrate_limit);
1824     }
1825 
1826     if (bits_per_second  > test->settings->bitrate_limit) {
1827         if (iperf_get_verbose(test))
1828             iperf_err(test, "Total throughput of %" PRIu64 " bps exceeded %" PRIu64 " bps limit", bits_per_second, test->settings->bitrate_limit);
1829 	test->bitrate_limit_exceeded = 1;
1830     }
1831 }
1832 
1833 int
1834 iperf_send(struct iperf_test *test, fd_set *write_setP)
1835 {
1836     register int multisend, r, streams_active;
1837     register struct iperf_stream *sp;
1838     struct iperf_time now;
1839     int no_throttle_check;
1840 
1841     /* Can we do multisend mode? */
1842     if (test->settings->burst != 0)
1843         multisend = test->settings->burst;
1844     else if (test->settings->rate == 0)
1845         multisend = test->multisend;
1846     else
1847         multisend = 1;	/* nope */
1848 
1849     /* Should bitrate throttle be checked for every send */
1850     no_throttle_check = test->settings->rate != 0 && test->settings->burst == 0;
1851 
1852     for (; multisend > 0; --multisend) {
1853 	if (no_throttle_check)
1854 	    iperf_time_now(&now);
1855 	streams_active = 0;
1856 	SLIST_FOREACH(sp, &test->streams, streams) {
1857 	    if ((sp->green_light && sp->sender &&
1858 		 (write_setP == NULL || FD_ISSET(sp->socket, write_setP)))) {
1859         if (multisend > 1 && test->settings->bytes != 0 && test->bytes_sent >= test->settings->bytes)
1860             break;
1861         if (multisend > 1 && test->settings->blocks != 0 && test->blocks_sent >= test->settings->blocks)
1862             break;
1863 		if ((r = sp->snd(sp)) < 0) {
1864 		    if (r == NET_SOFTERROR)
1865 			break;
1866 		    i_errno = IESTREAMWRITE;
1867 		    return r;
1868 		}
1869 		streams_active = 1;
1870 		test->bytes_sent += r;
1871 		if (!sp->pending_size)
1872 		    ++test->blocks_sent;
1873                 if (no_throttle_check)
1874 		    iperf_check_throttle(sp, &now);
1875 	    }
1876 	}
1877 	if (!streams_active)
1878 	    break;
1879     }
1880     if (!no_throttle_check) {   /* Throttle check if was not checked for each send */
1881 	iperf_time_now(&now);
1882 	SLIST_FOREACH(sp, &test->streams, streams)
1883 	    if (sp->sender)
1884 	        iperf_check_throttle(sp, &now);
1885     }
1886     if (write_setP != NULL)
1887 	SLIST_FOREACH(sp, &test->streams, streams)
1888 	    if (FD_ISSET(sp->socket, write_setP))
1889 		FD_CLR(sp->socket, write_setP);
1890 
1891     return 0;
1892 }
1893 
1894 int
1895 iperf_recv(struct iperf_test *test, fd_set *read_setP)
1896 {
1897     int r;
1898     struct iperf_stream *sp;
1899 
1900     SLIST_FOREACH(sp, &test->streams, streams) {
1901 	if (FD_ISSET(sp->socket, read_setP) && !sp->sender) {
1902 	    if ((r = sp->rcv(sp)) < 0) {
1903 		i_errno = IESTREAMREAD;
1904 		return r;
1905 	    }
1906 	    test->bytes_received += r;
1907 	    ++test->blocks_received;
1908 	    FD_CLR(sp->socket, read_setP);
1909 	}
1910     }
1911 
1912     return 0;
1913 }
1914 
1915 int
1916 iperf_init_test(struct iperf_test *test)
1917 {
1918     struct iperf_time now;
1919     struct iperf_stream *sp;
1920 
1921     if (test->protocol->init) {
1922         if (test->protocol->init(test) < 0)
1923             return -1;
1924     }
1925 
1926     /* Init each stream. */
1927     if (iperf_time_now(&now) < 0) {
1928 	i_errno = IEINITTEST;
1929 	return -1;
1930     }
1931     SLIST_FOREACH(sp, &test->streams, streams) {
1932 	sp->result->start_time = sp->result->start_time_fixed = now;
1933     }
1934 
1935     if (test->on_test_start)
1936         test->on_test_start(test);
1937 
1938     return 0;
1939 }
1940 
1941 static void
1942 send_timer_proc(TimerClientData client_data, struct iperf_time *nowP)
1943 {
1944     struct iperf_stream *sp = client_data.p;
1945 
1946     /* All we do here is set or clear the flag saying that this stream may
1947     ** be sent to.  The actual sending gets done in the send proc, after
1948     ** checking the flag.
1949     */
1950     iperf_check_throttle(sp, nowP);
1951 }
1952 
1953 int
1954 iperf_create_send_timers(struct iperf_test * test)
1955 {
1956     struct iperf_time now;
1957     struct iperf_stream *sp;
1958     TimerClientData cd;
1959 
1960     if (iperf_time_now(&now) < 0) {
1961 	i_errno = IEINITTEST;
1962 	return -1;
1963     }
1964     SLIST_FOREACH(sp, &test->streams, streams) {
1965         sp->green_light = 1;
1966 	if (test->settings->rate != 0 && sp->sender) {
1967 	    cd.p = sp;
1968 	    sp->send_timer = tmr_create(NULL, send_timer_proc, cd, test->settings->pacing_timer, 1);
1969 	    if (sp->send_timer == NULL) {
1970 		i_errno = IEINITTEST;
1971 		return -1;
1972 	    }
1973 	}
1974     }
1975     return 0;
1976 }
1977 
1978 #if defined(HAVE_SSL)
1979 int test_is_authorized(struct iperf_test *test){
1980     if ( !(test->server_rsa_private_key && test->server_authorized_users)) {
1981         return 0;
1982     }
1983 
1984     if (test->settings->authtoken){
1985         char *username = NULL, *password = NULL;
1986         time_t ts;
1987         int rc = decode_auth_setting(test->debug, test->settings->authtoken, test->server_rsa_private_key, &username, &password, &ts);
1988 	if (rc) {
1989 	    return -1;
1990 	}
1991         int ret = check_authentication(username, password, ts, test->server_authorized_users, test->server_skew_threshold);
1992         if (ret == 0){
1993             if (test->debug) {
1994               iperf_printf(test, report_authentication_succeeded, username, ts);
1995             }
1996             free(username);
1997             free(password);
1998             return 0;
1999         } else {
2000             if (test->debug) {
2001                 iperf_printf(test, report_authentication_failed, username, ts);
2002             }
2003             free(username);
2004             free(password);
2005             return -1;
2006         }
2007     }
2008     return -1;
2009 }
2010 #endif //HAVE_SSL
2011 
2012 /**
2013  * iperf_exchange_parameters - handles the param_Exchange part for client
2014  *
2015  */
2016 
2017 int
2018 iperf_exchange_parameters(struct iperf_test *test)
2019 {
2020     int s;
2021     int32_t err;
2022 
2023     if (test->role == 'c') {
2024 
2025         if (send_parameters(test) < 0)
2026             return -1;
2027 
2028     } else {
2029 
2030         if (get_parameters(test) < 0)
2031             return -1;
2032 
2033 #if defined(HAVE_SSL)
2034         if (test_is_authorized(test) < 0){
2035             if (iperf_set_send_state(test, SERVER_ERROR) != 0)
2036                 return -1;
2037             i_errno = IEAUTHTEST;
2038             err = htonl(i_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 #endif //HAVE_SSL
2046 
2047         if ((s = test->protocol->listen(test)) < 0) {
2048 	        if (iperf_set_send_state(test, SERVER_ERROR) != 0)
2049                 return -1;
2050             err = htonl(i_errno);
2051             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
2052                 i_errno = IECTRLWRITE;
2053                 return -1;
2054             }
2055             err = htonl(errno);
2056             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
2057                 i_errno = IECTRLWRITE;
2058                 return -1;
2059             }
2060             return -1;
2061         }
2062 
2063         FD_SET(s, &test->read_set);
2064         test->max_fd = (s > test->max_fd) ? s : test->max_fd;
2065         test->prot_listener = s;
2066 
2067         // Send the control message to create streams and start the test
2068 	if (iperf_set_send_state(test, CREATE_STREAMS) != 0)
2069             return -1;
2070 
2071     }
2072 
2073     return 0;
2074 }
2075 
2076 /*************************************************************/
2077 
2078 int
2079 iperf_exchange_results(struct iperf_test *test)
2080 {
2081     if (test->role == 'c') {
2082         /* Send results to server. */
2083 	if (send_results(test) < 0)
2084             return -1;
2085         /* Get server results. */
2086         if (get_results(test) < 0)
2087             return -1;
2088     } else {
2089         /* Get client results. */
2090         if (get_results(test) < 0)
2091             return -1;
2092         /* Send results to client. */
2093 	if (send_results(test) < 0)
2094             return -1;
2095     }
2096     return 0;
2097 }
2098 
2099 /*************************************************************/
2100 
2101 static int
2102 send_parameters(struct iperf_test *test)
2103 {
2104     int r = 0;
2105     cJSON *j;
2106 
2107     j = cJSON_CreateObject();
2108     if (j == NULL) {
2109 	i_errno = IESENDPARAMS;
2110 	r = -1;
2111     } else {
2112 	if (test->protocol->id == Ptcp)
2113 	    cJSON_AddTrueToObject(j, "tcp");
2114 	else if (test->protocol->id == Pudp)
2115 	    cJSON_AddTrueToObject(j, "udp");
2116         else if (test->protocol->id == Psctp)
2117             cJSON_AddTrueToObject(j, "sctp");
2118 	cJSON_AddNumberToObject(j, "omit", test->omit);
2119 	if (test->server_affinity != -1)
2120 	    cJSON_AddNumberToObject(j, "server_affinity", test->server_affinity);
2121 	cJSON_AddNumberToObject(j, "time", test->duration);
2122 	if (test->settings->bytes)
2123 	    cJSON_AddNumberToObject(j, "num", test->settings->bytes);
2124 	if (test->settings->blocks)
2125 	    cJSON_AddNumberToObject(j, "blockcount", test->settings->blocks);
2126 	if (test->settings->mss)
2127 	    cJSON_AddNumberToObject(j, "MSS", test->settings->mss);
2128 	if (test->no_delay)
2129 	    cJSON_AddTrueToObject(j, "nodelay");
2130 	cJSON_AddNumberToObject(j, "parallel", test->num_streams);
2131 	if (test->reverse)
2132 	    cJSON_AddTrueToObject(j, "reverse");
2133 	if (test->bidirectional)
2134 	            cJSON_AddTrueToObject(j, "bidirectional");
2135 	if (test->settings->socket_bufsize)
2136 	    cJSON_AddNumberToObject(j, "window", test->settings->socket_bufsize);
2137 	if (test->settings->blksize)
2138 	    cJSON_AddNumberToObject(j, "len", test->settings->blksize);
2139 	if (test->settings->rate)
2140 	    cJSON_AddNumberToObject(j, "bandwidth", test->settings->rate);
2141 	if (test->settings->fqrate)
2142 	    cJSON_AddNumberToObject(j, "fqrate", test->settings->fqrate);
2143 	if (test->settings->pacing_timer)
2144 	    cJSON_AddNumberToObject(j, "pacing_timer", test->settings->pacing_timer);
2145 	if (test->settings->burst)
2146 	    cJSON_AddNumberToObject(j, "burst", test->settings->burst);
2147 	if (test->settings->tos)
2148 	    cJSON_AddNumberToObject(j, "TOS", test->settings->tos);
2149 	if (test->settings->flowlabel)
2150 	    cJSON_AddNumberToObject(j, "flowlabel", test->settings->flowlabel);
2151 	if (test->title)
2152 	    cJSON_AddStringToObject(j, "title", test->title);
2153 	if (test->extra_data)
2154 	    cJSON_AddStringToObject(j, "extra_data", test->extra_data);
2155 	if (test->congestion)
2156 	    cJSON_AddStringToObject(j, "congestion", test->congestion);
2157 	if (test->congestion_used)
2158 	    cJSON_AddStringToObject(j, "congestion_used", test->congestion_used);
2159 	if (test->get_server_output)
2160 	    cJSON_AddNumberToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
2161 	if (test->udp_counters_64bit)
2162 	    cJSON_AddNumberToObject(j, "udp_counters_64bit", iperf_get_test_udp_counters_64bit(test));
2163 	if (test->repeating_payload)
2164 	    cJSON_AddNumberToObject(j, "repeating_payload", test->repeating_payload);
2165 	if (test->zerocopy)
2166 	    cJSON_AddNumberToObject(j, "zerocopy", test->zerocopy);
2167 #if defined(HAVE_DONT_FRAGMENT)
2168 	if (test->settings->dont_fragment)
2169 	    cJSON_AddNumberToObject(j, "dont_fragment", test->settings->dont_fragment);
2170 #endif /* HAVE_DONT_FRAGMENT */
2171 #if defined(HAVE_SSL)
2172 	/* Send authentication parameters */
2173 	if (test->settings->client_username && test->settings->client_password && test->settings->client_rsa_pubkey){
2174 	    int rc = encode_auth_setting(test->settings->client_username, test->settings->client_password, test->settings->client_rsa_pubkey, &test->settings->authtoken);
2175 
2176 	    if (rc) {
2177 		cJSON_Delete(j);
2178 		i_errno = IESENDPARAMS;
2179 		return -1;
2180 	    }
2181 
2182 	    cJSON_AddStringToObject(j, "authtoken", test->settings->authtoken);
2183 	}
2184 #endif // HAVE_SSL
2185 	cJSON_AddStringToObject(j, "client_version", IPERF_VERSION);
2186 
2187 	if (test->debug) {
2188 	    char *str = cJSON_Print(j);
2189 	    printf("send_parameters:\n%s\n", str);
2190 	    cJSON_free(str);
2191 	}
2192 
2193 	if (JSON_write(test->ctrl_sck, j) < 0) {
2194 	    i_errno = IESENDPARAMS;
2195 	    r = -1;
2196 	}
2197 	cJSON_Delete(j);
2198     }
2199     return r;
2200 }
2201 
2202 /*************************************************************/
2203 
2204 static int
2205 get_parameters(struct iperf_test *test)
2206 {
2207     int r = 0;
2208     cJSON *j;
2209     cJSON *j_p;
2210 
2211     j = JSON_read(test->ctrl_sck);
2212     if (j == NULL) {
2213 	i_errno = IERECVPARAMS;
2214         r = -1;
2215     } else {
2216 	if (test->debug) {
2217             char *str;
2218             str = cJSON_Print(j);
2219             printf("get_parameters:\n%s\n", str );
2220             cJSON_free(str);
2221 	}
2222 
2223 	if ((j_p = cJSON_GetObjectItem(j, "tcp")) != NULL)
2224 	    set_protocol(test, Ptcp);
2225 	if ((j_p = cJSON_GetObjectItem(j, "udp")) != NULL)
2226 	    set_protocol(test, Pudp);
2227         if ((j_p = cJSON_GetObjectItem(j, "sctp")) != NULL)
2228             set_protocol(test, Psctp);
2229 	if ((j_p = cJSON_GetObjectItem(j, "omit")) != NULL)
2230 	    test->omit = j_p->valueint;
2231 	if ((j_p = cJSON_GetObjectItem(j, "server_affinity")) != NULL)
2232 	    test->server_affinity = j_p->valueint;
2233 	if ((j_p = cJSON_GetObjectItem(j, "time")) != NULL)
2234 	    test->duration = j_p->valueint;
2235 	if ((j_p = cJSON_GetObjectItem(j, "num")) != NULL)
2236 	    test->settings->bytes = j_p->valueint;
2237 	if ((j_p = cJSON_GetObjectItem(j, "blockcount")) != NULL)
2238 	    test->settings->blocks = j_p->valueint;
2239 	if ((j_p = cJSON_GetObjectItem(j, "MSS")) != NULL)
2240 	    test->settings->mss = j_p->valueint;
2241 	if ((j_p = cJSON_GetObjectItem(j, "nodelay")) != NULL)
2242 	    test->no_delay = 1;
2243 	if ((j_p = cJSON_GetObjectItem(j, "parallel")) != NULL)
2244 	    test->num_streams = j_p->valueint;
2245 	if ((j_p = cJSON_GetObjectItem(j, "reverse")) != NULL)
2246 	    iperf_set_test_reverse(test, 1);
2247         if ((j_p = cJSON_GetObjectItem(j, "bidirectional")) != NULL)
2248             iperf_set_test_bidirectional(test, 1);
2249 	if ((j_p = cJSON_GetObjectItem(j, "window")) != NULL)
2250 	    test->settings->socket_bufsize = j_p->valueint;
2251 	if ((j_p = cJSON_GetObjectItem(j, "len")) != NULL)
2252 	    test->settings->blksize = j_p->valueint;
2253 	if ((j_p = cJSON_GetObjectItem(j, "bandwidth")) != NULL)
2254 	    test->settings->rate = j_p->valueint;
2255 	if ((j_p = cJSON_GetObjectItem(j, "fqrate")) != NULL)
2256 	    test->settings->fqrate = j_p->valueint;
2257 	if ((j_p = cJSON_GetObjectItem(j, "pacing_timer")) != NULL)
2258 	    test->settings->pacing_timer = j_p->valueint;
2259 	if ((j_p = cJSON_GetObjectItem(j, "burst")) != NULL)
2260 	    test->settings->burst = j_p->valueint;
2261 	if ((j_p = cJSON_GetObjectItem(j, "TOS")) != NULL)
2262 	    test->settings->tos = j_p->valueint;
2263 	if ((j_p = cJSON_GetObjectItem(j, "flowlabel")) != NULL)
2264 	    test->settings->flowlabel = j_p->valueint;
2265 	if ((j_p = cJSON_GetObjectItem(j, "title")) != NULL)
2266 	    test->title = strdup(j_p->valuestring);
2267 	if ((j_p = cJSON_GetObjectItem(j, "extra_data")) != NULL)
2268 	    test->extra_data = strdup(j_p->valuestring);
2269 	if ((j_p = cJSON_GetObjectItem(j, "congestion")) != NULL)
2270 	    test->congestion = strdup(j_p->valuestring);
2271 	if ((j_p = cJSON_GetObjectItem(j, "congestion_used")) != NULL)
2272 	    test->congestion_used = strdup(j_p->valuestring);
2273 	if ((j_p = cJSON_GetObjectItem(j, "get_server_output")) != NULL)
2274 	    iperf_set_test_get_server_output(test, 1);
2275 	if ((j_p = cJSON_GetObjectItem(j, "udp_counters_64bit")) != NULL)
2276 	    iperf_set_test_udp_counters_64bit(test, 1);
2277 	if ((j_p = cJSON_GetObjectItem(j, "repeating_payload")) != NULL)
2278 	    test->repeating_payload = 1;
2279 	if ((j_p = cJSON_GetObjectItem(j, "zerocopy")) != NULL)
2280 	    test->zerocopy = j_p->valueint;
2281 #if defined(HAVE_DONT_FRAGMENT)
2282 	if ((j_p = cJSON_GetObjectItem(j, "dont_fragment")) != NULL)
2283 	    test->settings->dont_fragment = j_p->valueint;
2284 #endif /* HAVE_DONT_FRAGMENT */
2285 #if defined(HAVE_SSL)
2286 	if ((j_p = cJSON_GetObjectItem(j, "authtoken")) != NULL)
2287         test->settings->authtoken = strdup(j_p->valuestring);
2288 #endif //HAVE_SSL
2289 	if (test->mode && test->protocol->id == Ptcp && has_tcpinfo_retransmits())
2290 	    test->sender_has_retransmits = 1;
2291 	if (test->settings->rate)
2292 	    cJSON_AddNumberToObject(test->json_start, "target_bitrate", test->settings->rate);
2293 	cJSON_Delete(j);
2294     }
2295     return r;
2296 }
2297 
2298 /*************************************************************/
2299 
2300 static int
2301 send_results(struct iperf_test *test)
2302 {
2303     int r = 0;
2304     cJSON *j;
2305     cJSON *j_streams;
2306     struct iperf_stream *sp;
2307     cJSON *j_stream;
2308     int sender_has_retransmits;
2309     iperf_size_t bytes_transferred;
2310     int retransmits;
2311     struct iperf_time temp_time;
2312     double start_time, end_time;
2313 
2314     j = cJSON_CreateObject();
2315     if (j == NULL) {
2316 	i_errno = IEPACKAGERESULTS;
2317 	r = -1;
2318     } else {
2319 	cJSON_AddNumberToObject(j, "cpu_util_total", test->cpu_util[0]);
2320 	cJSON_AddNumberToObject(j, "cpu_util_user", test->cpu_util[1]);
2321 	cJSON_AddNumberToObject(j, "cpu_util_system", test->cpu_util[2]);
2322 	if ( test->mode == RECEIVER )
2323 	    sender_has_retransmits = -1;
2324 	else
2325 	    sender_has_retransmits = test->sender_has_retransmits;
2326 	cJSON_AddNumberToObject(j, "sender_has_retransmits", sender_has_retransmits);
2327 	if ( test->congestion_used ) {
2328 	    cJSON_AddStringToObject(j, "congestion_used", test->congestion_used);
2329 	}
2330 
2331 	/* If on the server and sending server output, then do this */
2332 	if (test->role == 's' && test->get_server_output) {
2333 	    if (test->json_output) {
2334 		/* Add JSON output */
2335 		cJSON_AddItemReferenceToObject(j, "server_output_json", test->json_top);
2336 	    }
2337 	    else {
2338 		/* Add textual output */
2339 		size_t buflen = 0;
2340 
2341 		/* Figure out how much room we need to hold the complete output string */
2342 		struct iperf_textline *t;
2343 		TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
2344 		    buflen += strlen(t->line);
2345 		}
2346 
2347 		/* Allocate and build it up from the component lines */
2348 		char *output = calloc(buflen + 1, 1);
2349 		TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
2350 		    strncat(output, t->line, buflen);
2351 		    buflen -= strlen(t->line);
2352 		}
2353 
2354 		cJSON_AddStringToObject(j, "server_output_text", output);
2355         free(output);
2356 	    }
2357 	}
2358 
2359 	j_streams = cJSON_CreateArray();
2360 	if (j_streams == NULL) {
2361 	    i_errno = IEPACKAGERESULTS;
2362 	    r = -1;
2363 	} else {
2364 	    cJSON_AddItemToObject(j, "streams", j_streams);
2365 	    SLIST_FOREACH(sp, &test->streams, streams) {
2366 		j_stream = cJSON_CreateObject();
2367 		if (j_stream == NULL) {
2368 		    i_errno = IEPACKAGERESULTS;
2369 		    r = -1;
2370 		} else {
2371 		    cJSON_AddItemToArray(j_streams, j_stream);
2372 		    bytes_transferred = sp->sender ? (sp->result->bytes_sent - sp->result->bytes_sent_omit) : sp->result->bytes_received;
2373 		    retransmits = (sp->sender && test->sender_has_retransmits) ? sp->result->stream_retrans : -1;
2374 		    cJSON_AddNumberToObject(j_stream, "id", sp->id);
2375 		    cJSON_AddNumberToObject(j_stream, "bytes", bytes_transferred);
2376 		    cJSON_AddNumberToObject(j_stream, "retransmits", retransmits);
2377 		    cJSON_AddNumberToObject(j_stream, "jitter", sp->jitter);
2378 		    cJSON_AddNumberToObject(j_stream, "errors", sp->cnt_error);
2379 		    cJSON_AddNumberToObject(j_stream, "packets", sp->packet_count);
2380 
2381 		    iperf_time_diff(&sp->result->start_time, &sp->result->start_time, &temp_time);
2382 		    start_time = iperf_time_in_secs(&temp_time);
2383 		    iperf_time_diff(&sp->result->start_time, &sp->result->end_time, &temp_time);
2384 		    end_time = iperf_time_in_secs(&temp_time);
2385 		    cJSON_AddNumberToObject(j_stream, "start_time", start_time);
2386 		    cJSON_AddNumberToObject(j_stream, "end_time", end_time);
2387 
2388 		}
2389 	    }
2390 	    if (r == 0 && test->debug) {
2391                 char *str = cJSON_Print(j);
2392 		printf("send_results\n%s\n", str);
2393                 cJSON_free(str);
2394 	    }
2395 	    if (r == 0 && JSON_write(test->ctrl_sck, j) < 0) {
2396 		i_errno = IESENDRESULTS;
2397 		r = -1;
2398 	    }
2399 	}
2400 	cJSON_Delete(j);
2401     }
2402     return r;
2403 }
2404 
2405 /*************************************************************/
2406 
2407 static int
2408 get_results(struct iperf_test *test)
2409 {
2410     int r = 0;
2411     cJSON *j;
2412     cJSON *j_cpu_util_total;
2413     cJSON *j_cpu_util_user;
2414     cJSON *j_cpu_util_system;
2415     cJSON *j_remote_congestion_used;
2416     cJSON *j_sender_has_retransmits;
2417     int result_has_retransmits;
2418     cJSON *j_streams;
2419     int n, i;
2420     cJSON *j_stream;
2421     cJSON *j_id;
2422     cJSON *j_bytes;
2423     cJSON *j_retransmits;
2424     cJSON *j_jitter;
2425     cJSON *j_errors;
2426     cJSON *j_packets;
2427     cJSON *j_server_output;
2428     cJSON *j_start_time, *j_end_time;
2429     int sid, cerror, pcount;
2430     double jitter;
2431     iperf_size_t bytes_transferred;
2432     int retransmits;
2433     struct iperf_stream *sp;
2434 
2435     j = JSON_read(test->ctrl_sck);
2436     if (j == NULL) {
2437 	i_errno = IERECVRESULTS;
2438         r = -1;
2439     } else {
2440 	j_cpu_util_total = cJSON_GetObjectItem(j, "cpu_util_total");
2441 	j_cpu_util_user = cJSON_GetObjectItem(j, "cpu_util_user");
2442 	j_cpu_util_system = cJSON_GetObjectItem(j, "cpu_util_system");
2443 	j_sender_has_retransmits = cJSON_GetObjectItem(j, "sender_has_retransmits");
2444 	if (j_cpu_util_total == NULL || j_cpu_util_user == NULL || j_cpu_util_system == NULL || j_sender_has_retransmits == NULL) {
2445 	    i_errno = IERECVRESULTS;
2446 	    r = -1;
2447 	} else {
2448 	    if (test->debug) {
2449                 char *str = cJSON_Print(j);
2450                 printf("get_results\n%s\n", str);
2451                 cJSON_free(str);
2452 	    }
2453 
2454 	    test->remote_cpu_util[0] = j_cpu_util_total->valuedouble;
2455 	    test->remote_cpu_util[1] = j_cpu_util_user->valuedouble;
2456 	    test->remote_cpu_util[2] = j_cpu_util_system->valuedouble;
2457 	    result_has_retransmits = j_sender_has_retransmits->valueint;
2458 	    if ( test->mode == RECEIVER ) {
2459 	        test->sender_has_retransmits = result_has_retransmits;
2460 	        test->other_side_has_retransmits = 0;
2461 	    }
2462 	    else if ( test->mode == BIDIRECTIONAL )
2463 	        test->other_side_has_retransmits = result_has_retransmits;
2464 
2465 	    j_streams = cJSON_GetObjectItem(j, "streams");
2466 	    if (j_streams == NULL) {
2467 		i_errno = IERECVRESULTS;
2468 		r = -1;
2469 	    } else {
2470 	        n = cJSON_GetArraySize(j_streams);
2471 		for (i=0; i<n; ++i) {
2472 		    j_stream = cJSON_GetArrayItem(j_streams, i);
2473 		    if (j_stream == NULL) {
2474 			i_errno = IERECVRESULTS;
2475 			r = -1;
2476 		    } else {
2477 			j_id = cJSON_GetObjectItem(j_stream, "id");
2478 			j_bytes = cJSON_GetObjectItem(j_stream, "bytes");
2479 			j_retransmits = cJSON_GetObjectItem(j_stream, "retransmits");
2480 			j_jitter = cJSON_GetObjectItem(j_stream, "jitter");
2481 			j_errors = cJSON_GetObjectItem(j_stream, "errors");
2482 			j_packets = cJSON_GetObjectItem(j_stream, "packets");
2483 			j_start_time = cJSON_GetObjectItem(j_stream, "start_time");
2484 			j_end_time = cJSON_GetObjectItem(j_stream, "end_time");
2485 			if (j_id == NULL || j_bytes == NULL || j_retransmits == NULL || j_jitter == NULL || j_errors == NULL || j_packets == NULL) {
2486 			    i_errno = IERECVRESULTS;
2487 			    r = -1;
2488 			} else {
2489 			    sid = j_id->valueint;
2490 			    bytes_transferred = j_bytes->valueint;
2491 			    retransmits = j_retransmits->valueint;
2492 			    jitter = j_jitter->valuedouble;
2493 			    cerror = j_errors->valueint;
2494 			    pcount = j_packets->valueint;
2495 			    SLIST_FOREACH(sp, &test->streams, streams)
2496 				if (sp->id == sid) break;
2497 			    if (sp == NULL) {
2498 				i_errno = IESTREAMID;
2499 				r = -1;
2500 			    } else {
2501 				if (sp->sender) {
2502 				    sp->jitter = jitter;
2503 				    sp->cnt_error = cerror;
2504 				    sp->peer_packet_count = pcount;
2505 				    sp->result->bytes_received = bytes_transferred;
2506 				    /*
2507 				     * We have to handle the possibility that
2508 				     * start_time and end_time might not be
2509 				     * available; this is the case for older (pre-3.2)
2510 				     * servers.
2511 				     *
2512 				     * We need to have result structure members to hold
2513 				     * the both sides' start_time and end_time.
2514 				     */
2515 				    if (j_start_time && j_end_time) {
2516 					sp->result->receiver_time = j_end_time->valuedouble - j_start_time->valuedouble;
2517 				    }
2518 				    else {
2519 					sp->result->receiver_time = 0.0;
2520 				    }
2521 				} else {
2522 				    sp->peer_packet_count = pcount;
2523 				    sp->result->bytes_sent = bytes_transferred;
2524 				    sp->result->stream_retrans = retransmits;
2525 				    if (j_start_time && j_end_time) {
2526 					sp->result->sender_time = j_end_time->valuedouble - j_start_time->valuedouble;
2527 				    }
2528 				    else {
2529 					sp->result->sender_time = 0.0;
2530 				    }
2531 				}
2532 			    }
2533 			}
2534 		    }
2535 		}
2536 		/*
2537 		 * If we're the client and we're supposed to get remote results,
2538 		 * look them up and process accordingly.
2539 		 */
2540 		if (test->role == 'c' && iperf_get_test_get_server_output(test)) {
2541 		    /* Look for JSON.  If we find it, grab the object so it doesn't get deleted. */
2542 		    j_server_output = cJSON_DetachItemFromObject(j, "server_output_json");
2543 		    if (j_server_output != NULL) {
2544 			test->json_server_output = j_server_output;
2545 		    }
2546 		    else {
2547 			/* No JSON, look for textual output.  Make a copy of the text for later. */
2548 			j_server_output = cJSON_GetObjectItem(j, "server_output_text");
2549 			if (j_server_output != NULL) {
2550 			    test->server_output_text = strdup(j_server_output->valuestring);
2551 			}
2552 		    }
2553 		}
2554 	    }
2555 	}
2556 
2557 	j_remote_congestion_used = cJSON_GetObjectItem(j, "congestion_used");
2558 	if (j_remote_congestion_used != NULL) {
2559 	    test->remote_congestion_used = strdup(j_remote_congestion_used->valuestring);
2560 	}
2561 
2562 	cJSON_Delete(j);
2563     }
2564     return r;
2565 }
2566 
2567 /*************************************************************/
2568 
2569 static int
2570 JSON_write(int fd, cJSON *json)
2571 {
2572     uint32_t hsize, nsize;
2573     char *str;
2574     int r = 0;
2575 
2576     str = cJSON_PrintUnformatted(json);
2577     if (str == NULL)
2578 	r = -1;
2579     else {
2580 	hsize = strlen(str);
2581 	nsize = htonl(hsize);
2582 	if (Nwrite(fd, (char*) &nsize, sizeof(nsize), Ptcp) < 0)
2583 	    r = -1;
2584 	else {
2585 	    if (Nwrite(fd, str, hsize, Ptcp) < 0)
2586 		r = -1;
2587 	}
2588 	cJSON_free(str);
2589     }
2590     return r;
2591 }
2592 
2593 /*************************************************************/
2594 
2595 static cJSON *
2596 JSON_read(int fd)
2597 {
2598     uint32_t hsize, nsize;
2599     char *str;
2600     cJSON *json = NULL;
2601     int rc;
2602 
2603     /*
2604      * Read a four-byte integer, which is the length of the JSON to follow.
2605      * Then read the JSON into a buffer and parse it.  Return a parsed JSON
2606      * structure, NULL if there was an error.
2607      */
2608     if (Nread(fd, (char*) &nsize, sizeof(nsize), Ptcp) >= 0) {
2609 	hsize = ntohl(nsize);
2610 	/* Allocate a buffer to hold the JSON */
2611 	str = (char *) calloc(sizeof(char), hsize+1);	/* +1 for trailing null */
2612 	if (str != NULL) {
2613 	    rc = Nread(fd, str, hsize, Ptcp);
2614 	    if (rc >= 0) {
2615 		/*
2616 		 * We should be reading in the number of bytes corresponding to the
2617 		 * length in that 4-byte integer.  If we don't the socket might have
2618 		 * prematurely closed.  Only do the JSON parsing if we got the
2619 		 * correct number of bytes.
2620 		 */
2621 		if (rc == hsize) {
2622 		    json = cJSON_Parse(str);
2623 		}
2624 		else {
2625 		    printf("WARNING:  Size of data read does not correspond to offered length\n");
2626 		}
2627 	    }
2628 	}
2629 	free(str);
2630     }
2631     return json;
2632 }
2633 
2634 /*************************************************************/
2635 /**
2636  * add_to_interval_list -- adds new interval to the interval_list
2637  */
2638 
2639 void
2640 add_to_interval_list(struct iperf_stream_result * rp, struct iperf_interval_results * new)
2641 {
2642     struct iperf_interval_results *irp;
2643 
2644     irp = (struct iperf_interval_results *) malloc(sizeof(struct iperf_interval_results));
2645     memcpy(irp, new, sizeof(struct iperf_interval_results));
2646     TAILQ_INSERT_TAIL(&rp->interval_results, irp, irlistentries);
2647 }
2648 
2649 
2650 /************************************************************/
2651 
2652 /**
2653  * connect_msg -- displays connection message
2654  * denoting sender/receiver details
2655  *
2656  */
2657 
2658 void
2659 connect_msg(struct iperf_stream *sp)
2660 {
2661     char ipl[INET6_ADDRSTRLEN], ipr[INET6_ADDRSTRLEN];
2662     int lport, rport;
2663 
2664     if (getsockdomain(sp->socket) == AF_INET) {
2665         inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->local_addr)->sin_addr, ipl, sizeof(ipl));
2666 	mapped_v4_to_regular_v4(ipl);
2667         inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->remote_addr)->sin_addr, ipr, sizeof(ipr));
2668 	mapped_v4_to_regular_v4(ipr);
2669         lport = ntohs(((struct sockaddr_in *) &sp->local_addr)->sin_port);
2670         rport = ntohs(((struct sockaddr_in *) &sp->remote_addr)->sin_port);
2671     } else {
2672         inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->local_addr)->sin6_addr, ipl, sizeof(ipl));
2673 	mapped_v4_to_regular_v4(ipl);
2674         inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->remote_addr)->sin6_addr, ipr, sizeof(ipr));
2675 	mapped_v4_to_regular_v4(ipr);
2676         lport = ntohs(((struct sockaddr_in6 *) &sp->local_addr)->sin6_port);
2677         rport = ntohs(((struct sockaddr_in6 *) &sp->remote_addr)->sin6_port);
2678     }
2679 
2680     if (sp->test->json_output)
2681         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));
2682     else
2683 	iperf_printf(sp->test, report_connected, sp->socket, ipl, lport, ipr, rport);
2684 }
2685 
2686 
2687 /**************************************************************************/
2688 
2689 struct iperf_test *
2690 iperf_new_test()
2691 {
2692     struct iperf_test *test;
2693 
2694     test = (struct iperf_test *) malloc(sizeof(struct iperf_test));
2695     if (!test) {
2696         i_errno = IENEWTEST;
2697         return NULL;
2698     }
2699     /* initialize everything to zero */
2700     memset(test, 0, sizeof(struct iperf_test));
2701 
2702     test->settings = (struct iperf_settings *) malloc(sizeof(struct iperf_settings));
2703     if (!test->settings) {
2704         free(test);
2705 	i_errno = IENEWTEST;
2706 	return NULL;
2707     }
2708     memset(test->settings, 0, sizeof(struct iperf_settings));
2709 
2710     test->bitrate_limit_intervals_traffic_bytes = (iperf_size_t *) malloc(sizeof(iperf_size_t) * MAX_INTERVAL);
2711     if (!test->bitrate_limit_intervals_traffic_bytes) {
2712         free(test);
2713 	i_errno = IENEWTEST;
2714 	return NULL;
2715     }
2716     memset(test->bitrate_limit_intervals_traffic_bytes, 0, sizeof(sizeof(iperf_size_t) * MAX_INTERVAL));
2717 
2718     /* By default all output goes to stdout */
2719     test->outfile = stdout;
2720 
2721     return test;
2722 }
2723 
2724 /**************************************************************************/
2725 
2726 struct protocol *
2727 protocol_new(void)
2728 {
2729     struct protocol *proto;
2730 
2731     proto = malloc(sizeof(struct protocol));
2732     if(!proto) {
2733         return NULL;
2734     }
2735     memset(proto, 0, sizeof(struct protocol));
2736 
2737     return proto;
2738 }
2739 
2740 void
2741 protocol_free(struct protocol *proto)
2742 {
2743     free(proto);
2744 }
2745 
2746 /**************************************************************************/
2747 int
2748 iperf_defaults(struct iperf_test *testp)
2749 {
2750     struct protocol *tcp, *udp;
2751 #if defined(HAVE_SCTP_H)
2752     struct protocol *sctp;
2753 #endif /* HAVE_SCTP_H */
2754 
2755     testp->omit = OMIT;
2756     testp->duration = DURATION;
2757     testp->diskfile_name = (char*) 0;
2758     testp->affinity = -1;
2759     testp->server_affinity = -1;
2760     TAILQ_INIT(&testp->xbind_addrs);
2761 #if defined(HAVE_CPUSET_SETAFFINITY)
2762     CPU_ZERO(&testp->cpumask);
2763 #endif /* HAVE_CPUSET_SETAFFINITY */
2764     testp->title = NULL;
2765     testp->extra_data = NULL;
2766     testp->congestion = NULL;
2767     testp->congestion_used = NULL;
2768     testp->remote_congestion_used = NULL;
2769     testp->server_port = PORT;
2770     testp->ctrl_sck = -1;
2771     testp->prot_listener = -1;
2772     testp->other_side_has_retransmits = 0;
2773 
2774     testp->stats_callback = iperf_stats_callback;
2775     testp->reporter_callback = iperf_reporter_callback;
2776 
2777     testp->stats_interval = testp->reporter_interval = 1;
2778     testp->num_streams = 1;
2779 
2780     testp->settings->domain = AF_UNSPEC;
2781     testp->settings->unit_format = 'a';
2782     testp->settings->socket_bufsize = 0;    /* use autotuning */
2783     testp->settings->blksize = DEFAULT_TCP_BLKSIZE;
2784     testp->settings->rate = 0;
2785     testp->settings->bitrate_limit = 0;
2786     testp->settings->bitrate_limit_interval = 5;
2787     testp->settings->bitrate_limit_stats_per_interval = 0;
2788     testp->settings->fqrate = 0;
2789     testp->settings->pacing_timer = DEFAULT_PACING_TIMER;
2790     testp->settings->burst = 0;
2791     testp->settings->mss = 0;
2792     testp->settings->bytes = 0;
2793     testp->settings->blocks = 0;
2794     testp->settings->connect_timeout = -1;
2795     testp->settings->rcv_timeout.secs = DEFAULT_NO_MSG_RCVD_TIMEOUT / SEC_TO_mS;
2796     testp->settings->rcv_timeout.usecs = (DEFAULT_NO_MSG_RCVD_TIMEOUT % SEC_TO_mS) * mS_TO_US;
2797     testp->zerocopy = 0;
2798 
2799     memset(testp->cookie, 0, COOKIE_SIZE);
2800 
2801     testp->multisend = 10;	/* arbitrary */
2802 
2803     /* Set up protocol list */
2804     SLIST_INIT(&testp->streams);
2805     SLIST_INIT(&testp->protocols);
2806 
2807     tcp = protocol_new();
2808     if (!tcp)
2809         return -1;
2810 
2811     tcp->id = Ptcp;
2812     tcp->name = "TCP";
2813     tcp->accept = iperf_tcp_accept;
2814     tcp->listen = iperf_tcp_listen;
2815     tcp->connect = iperf_tcp_connect;
2816     tcp->send = iperf_tcp_send;
2817     tcp->recv = iperf_tcp_recv;
2818     tcp->init = NULL;
2819     SLIST_INSERT_HEAD(&testp->protocols, tcp, protocols);
2820 
2821     udp = protocol_new();
2822     if (!udp) {
2823         protocol_free(tcp);
2824         return -1;
2825     }
2826 
2827     udp->id = Pudp;
2828     udp->name = "UDP";
2829     udp->accept = iperf_udp_accept;
2830     udp->listen = iperf_udp_listen;
2831     udp->connect = iperf_udp_connect;
2832     udp->send = iperf_udp_send;
2833     udp->recv = iperf_udp_recv;
2834     udp->init = iperf_udp_init;
2835     SLIST_INSERT_AFTER(tcp, udp, protocols);
2836 
2837     set_protocol(testp, Ptcp);
2838 
2839 #if defined(HAVE_SCTP_H)
2840     sctp = protocol_new();
2841     if (!sctp) {
2842         protocol_free(tcp);
2843         protocol_free(udp);
2844         return -1;
2845     }
2846 
2847     sctp->id = Psctp;
2848     sctp->name = "SCTP";
2849     sctp->accept = iperf_sctp_accept;
2850     sctp->listen = iperf_sctp_listen;
2851     sctp->connect = iperf_sctp_connect;
2852     sctp->send = iperf_sctp_send;
2853     sctp->recv = iperf_sctp_recv;
2854     sctp->init = iperf_sctp_init;
2855 
2856     SLIST_INSERT_AFTER(udp, sctp, protocols);
2857 #endif /* HAVE_SCTP_H */
2858 
2859     testp->on_new_stream = iperf_on_new_stream;
2860     testp->on_test_start = iperf_on_test_start;
2861     testp->on_connect = iperf_on_connect;
2862     testp->on_test_finish = iperf_on_test_finish;
2863 
2864     TAILQ_INIT(&testp->server_output_list);
2865 
2866     return 0;
2867 }
2868 
2869 
2870 /**************************************************************************/
2871 void
2872 iperf_free_test(struct iperf_test *test)
2873 {
2874     struct protocol *prot;
2875     struct iperf_stream *sp;
2876 
2877     /* Free streams */
2878     while (!SLIST_EMPTY(&test->streams)) {
2879         sp = SLIST_FIRST(&test->streams);
2880         SLIST_REMOVE_HEAD(&test->streams, streams);
2881         iperf_free_stream(sp);
2882     }
2883     if (test->server_hostname)
2884 	free(test->server_hostname);
2885     if (test->tmp_template)
2886 	free(test->tmp_template);
2887     if (test->bind_address)
2888 	free(test->bind_address);
2889     if (test->bind_dev)
2890 	free(test->bind_dev);
2891     if (!TAILQ_EMPTY(&test->xbind_addrs)) {
2892         struct xbind_entry *xbe;
2893 
2894         while (!TAILQ_EMPTY(&test->xbind_addrs)) {
2895             xbe = TAILQ_FIRST(&test->xbind_addrs);
2896             TAILQ_REMOVE(&test->xbind_addrs, xbe, link);
2897             if (xbe->ai)
2898                 freeaddrinfo(xbe->ai);
2899             free(xbe->name);
2900             free(xbe);
2901         }
2902     }
2903 #if defined(HAVE_SSL)
2904 
2905     if (test->server_rsa_private_key)
2906       EVP_PKEY_free(test->server_rsa_private_key);
2907     test->server_rsa_private_key = NULL;
2908 
2909     free(test->settings->authtoken);
2910     test->settings->authtoken = NULL;
2911 
2912     free(test->settings->client_username);
2913     test->settings->client_username = NULL;
2914 
2915     free(test->settings->client_password);
2916     test->settings->client_password = NULL;
2917 
2918     if (test->settings->client_rsa_pubkey)
2919       EVP_PKEY_free(test->settings->client_rsa_pubkey);
2920     test->settings->client_rsa_pubkey = NULL;
2921 #endif /* HAVE_SSL */
2922 
2923     if (test->settings)
2924     free(test->settings);
2925     if (test->title)
2926 	free(test->title);
2927     if (test->extra_data)
2928 	free(test->extra_data);
2929     if (test->congestion)
2930 	free(test->congestion);
2931     if (test->congestion_used)
2932 	free(test->congestion_used);
2933     if (test->remote_congestion_used)
2934 	free(test->remote_congestion_used);
2935     if (test->timestamp_format)
2936 	free(test->timestamp_format);
2937     if (test->omit_timer != NULL)
2938 	tmr_cancel(test->omit_timer);
2939     if (test->timer != NULL)
2940 	tmr_cancel(test->timer);
2941     if (test->stats_timer != NULL)
2942 	tmr_cancel(test->stats_timer);
2943     if (test->reporter_timer != NULL)
2944 	tmr_cancel(test->reporter_timer);
2945 
2946     /* Free protocol list */
2947     while (!SLIST_EMPTY(&test->protocols)) {
2948         prot = SLIST_FIRST(&test->protocols);
2949         SLIST_REMOVE_HEAD(&test->protocols, protocols);
2950         free(prot);
2951     }
2952 
2953     if (test->logfile) {
2954 	free(test->logfile);
2955 	test->logfile = NULL;
2956 	if (test->outfile && test->outfile != stdout) {
2957 	    fclose(test->outfile);
2958 	    test->outfile = NULL;
2959 	}
2960     }
2961 
2962     if (test->server_output_text) {
2963 	free(test->server_output_text);
2964 	test->server_output_text = NULL;
2965     }
2966 
2967     if (test->json_output_string) {
2968 	free(test->json_output_string);
2969 	test->json_output_string = NULL;
2970     }
2971 
2972     /* Free output line buffers, if any (on the server only) */
2973     struct iperf_textline *t;
2974     while (!TAILQ_EMPTY(&test->server_output_list)) {
2975 	t = TAILQ_FIRST(&test->server_output_list);
2976 	TAILQ_REMOVE(&test->server_output_list, t, textlineentries);
2977 	free(t->line);
2978 	free(t);
2979     }
2980 
2981     /* sctp_bindx: do not free the arguments, only the resolver results */
2982     if (!TAILQ_EMPTY(&test->xbind_addrs)) {
2983         struct xbind_entry *xbe;
2984 
2985         TAILQ_FOREACH(xbe, &test->xbind_addrs, link) {
2986             if (xbe->ai) {
2987                 freeaddrinfo(xbe->ai);
2988                 xbe->ai = NULL;
2989             }
2990         }
2991     }
2992 
2993     /* Free interval's traffic array for average rate calculations */
2994     if (test->bitrate_limit_intervals_traffic_bytes != NULL)
2995         free(test->bitrate_limit_intervals_traffic_bytes);
2996 
2997     /* XXX: Why are we setting these values to NULL? */
2998     // test->streams = NULL;
2999     test->stats_callback = NULL;
3000     test->reporter_callback = NULL;
3001     free(test);
3002 }
3003 
3004 
3005 void
3006 iperf_reset_test(struct iperf_test *test)
3007 {
3008     struct iperf_stream *sp;
3009     int i;
3010 
3011     /* Free streams */
3012     while (!SLIST_EMPTY(&test->streams)) {
3013         sp = SLIST_FIRST(&test->streams);
3014         SLIST_REMOVE_HEAD(&test->streams, streams);
3015         iperf_free_stream(sp);
3016     }
3017     if (test->omit_timer != NULL) {
3018 	tmr_cancel(test->omit_timer);
3019 	test->omit_timer = NULL;
3020     }
3021     if (test->timer != NULL) {
3022 	tmr_cancel(test->timer);
3023 	test->timer = NULL;
3024     }
3025     if (test->stats_timer != NULL) {
3026 	tmr_cancel(test->stats_timer);
3027 	test->stats_timer = NULL;
3028     }
3029     if (test->reporter_timer != NULL) {
3030 	tmr_cancel(test->reporter_timer);
3031 	test->reporter_timer = NULL;
3032     }
3033     test->done = 0;
3034 
3035     SLIST_INIT(&test->streams);
3036 
3037     if (test->remote_congestion_used)
3038         free(test->remote_congestion_used);
3039     test->remote_congestion_used = NULL;
3040     test->role = 's';
3041     test->mode = RECEIVER;
3042     test->sender_has_retransmits = 0;
3043     set_protocol(test, Ptcp);
3044     test->omit = OMIT;
3045     test->duration = DURATION;
3046     test->server_affinity = -1;
3047 #if defined(HAVE_CPUSET_SETAFFINITY)
3048     CPU_ZERO(&test->cpumask);
3049 #endif /* HAVE_CPUSET_SETAFFINITY */
3050     test->state = 0;
3051 
3052     test->ctrl_sck = -1;
3053     test->prot_listener = -1;
3054 
3055     test->bytes_sent = 0;
3056     test->blocks_sent = 0;
3057 
3058     test->bytes_received = 0;
3059     test->blocks_received = 0;
3060 
3061     test->other_side_has_retransmits = 0;
3062 
3063     test->bitrate_limit_stats_count = 0;
3064     test->bitrate_limit_last_interval_index = 0;
3065     test->bitrate_limit_exceeded = 0;
3066 
3067     for (i = 0; i < MAX_INTERVAL; i++)
3068         test->bitrate_limit_intervals_traffic_bytes[i] = 0;
3069 
3070     test->reverse = 0;
3071     test->bidirectional = 0;
3072     test->no_delay = 0;
3073 
3074     FD_ZERO(&test->read_set);
3075     FD_ZERO(&test->write_set);
3076 
3077     test->num_streams = 1;
3078     test->settings->socket_bufsize = 0;
3079     test->settings->blksize = DEFAULT_TCP_BLKSIZE;
3080     test->settings->rate = 0;
3081     test->settings->burst = 0;
3082     test->settings->mss = 0;
3083     test->settings->tos = 0;
3084     test->settings->dont_fragment = 0;
3085     test->zerocopy = 0;
3086 
3087 #if defined(HAVE_SSL)
3088     if (test->settings->authtoken) {
3089         free(test->settings->authtoken);
3090         test->settings->authtoken = NULL;
3091     }
3092     if (test->settings->client_username) {
3093         free(test->settings->client_username);
3094         test->settings->client_username = NULL;
3095     }
3096     if (test->settings->client_password) {
3097         free(test->settings->client_password);
3098         test->settings->client_password = NULL;
3099     }
3100     if (test->settings->client_rsa_pubkey) {
3101         EVP_PKEY_free(test->settings->client_rsa_pubkey);
3102         test->settings->client_rsa_pubkey = NULL;
3103     }
3104 #endif /* HAVE_SSL */
3105 
3106     memset(test->cookie, 0, COOKIE_SIZE);
3107     test->multisend = 10;	/* arbitrary */
3108     test->udp_counters_64bit = 0;
3109     if (test->title) {
3110 	free(test->title);
3111 	test->title = NULL;
3112     }
3113     if (test->extra_data) {
3114 	free(test->extra_data);
3115 	test->extra_data = NULL;
3116     }
3117 
3118     /* Free output line buffers, if any (on the server only) */
3119     struct iperf_textline *t;
3120     while (!TAILQ_EMPTY(&test->server_output_list)) {
3121 	t = TAILQ_FIRST(&test->server_output_list);
3122 	TAILQ_REMOVE(&test->server_output_list, t, textlineentries);
3123 	free(t->line);
3124 	free(t);
3125     }
3126 }
3127 
3128 
3129 /* Reset all of a test's stats back to zero.  Called when the omitting
3130 ** period is over.
3131 */
3132 void
3133 iperf_reset_stats(struct iperf_test *test)
3134 {
3135     struct iperf_time now;
3136     struct iperf_stream *sp;
3137     struct iperf_stream_result *rp;
3138 
3139     test->bytes_sent = 0;
3140     test->blocks_sent = 0;
3141     iperf_time_now(&now);
3142     SLIST_FOREACH(sp, &test->streams, streams) {
3143 	sp->omitted_packet_count = sp->packet_count;
3144         sp->omitted_cnt_error = sp->cnt_error;
3145         sp->omitted_outoforder_packets = sp->outoforder_packets;
3146 	sp->jitter = 0;
3147 	rp = sp->result;
3148         rp->bytes_sent_omit = rp->bytes_sent;
3149         rp->bytes_received = 0;
3150         rp->bytes_sent_this_interval = rp->bytes_received_this_interval = 0;
3151 	if (test->sender_has_retransmits == 1) {
3152 	    struct iperf_interval_results ir; /* temporary results structure */
3153 	    save_tcpinfo(sp, &ir);
3154 	    rp->stream_prev_total_retrans = get_total_retransmits(&ir);
3155 	}
3156 	rp->stream_retrans = 0;
3157 	rp->start_time = now;
3158     }
3159 }
3160 
3161 
3162 /**************************************************************************/
3163 
3164 /**
3165  * Gather statistics during a test.
3166  * This function works for both the client and server side.
3167  */
3168 void
3169 iperf_stats_callback(struct iperf_test *test)
3170 {
3171     struct iperf_stream *sp;
3172     struct iperf_stream_result *rp = NULL;
3173     struct iperf_interval_results *irp, temp;
3174     struct iperf_time temp_time;
3175     iperf_size_t total_interval_bytes_transferred = 0;
3176 
3177     temp.omitted = test->omitting;
3178     SLIST_FOREACH(sp, &test->streams, streams) {
3179         rp = sp->result;
3180 	temp.bytes_transferred = sp->sender ? rp->bytes_sent_this_interval : rp->bytes_received_this_interval;
3181 
3182         // Total bytes transferred this interval
3183 	total_interval_bytes_transferred += rp->bytes_sent_this_interval + rp->bytes_received_this_interval;
3184 
3185 	irp = TAILQ_LAST(&rp->interval_results, irlisthead);
3186         /* result->end_time contains timestamp of previous interval */
3187         if ( irp != NULL ) /* not the 1st interval */
3188             memcpy(&temp.interval_start_time, &rp->end_time, sizeof(struct iperf_time));
3189         else /* or use timestamp from beginning */
3190             memcpy(&temp.interval_start_time, &rp->start_time, sizeof(struct iperf_time));
3191         /* now save time of end of this interval */
3192         iperf_time_now(&rp->end_time);
3193         memcpy(&temp.interval_end_time, &rp->end_time, sizeof(struct iperf_time));
3194         iperf_time_diff(&temp.interval_start_time, &temp.interval_end_time, &temp_time);
3195         temp.interval_duration = iperf_time_in_secs(&temp_time);
3196 	if (test->protocol->id == Ptcp) {
3197 	    if ( has_tcpinfo()) {
3198 		save_tcpinfo(sp, &temp);
3199 		if (test->sender_has_retransmits == 1) {
3200 		    long total_retrans = get_total_retransmits(&temp);
3201 		    temp.interval_retrans = total_retrans - rp->stream_prev_total_retrans;
3202 		    rp->stream_retrans += temp.interval_retrans;
3203 		    rp->stream_prev_total_retrans = total_retrans;
3204 
3205 		    temp.snd_cwnd = get_snd_cwnd(&temp);
3206 		    if (temp.snd_cwnd > rp->stream_max_snd_cwnd) {
3207 			rp->stream_max_snd_cwnd = temp.snd_cwnd;
3208 		    }
3209 
3210 		    temp.snd_wnd = get_snd_wnd(&temp);
3211 		    if (temp.snd_wnd > rp->stream_max_snd_wnd) {
3212 			rp->stream_max_snd_wnd = temp.snd_wnd;
3213 		    }
3214 
3215 		    temp.rtt = get_rtt(&temp);
3216 		    if (temp.rtt > rp->stream_max_rtt) {
3217 			rp->stream_max_rtt = temp.rtt;
3218 		    }
3219 		    if (rp->stream_min_rtt == 0 ||
3220 			temp.rtt < rp->stream_min_rtt) {
3221 			rp->stream_min_rtt = temp.rtt;
3222 		    }
3223 		    rp->stream_sum_rtt += temp.rtt;
3224 		    rp->stream_count_rtt++;
3225 
3226 		    temp.rttvar = get_rttvar(&temp);
3227 		    temp.pmtu = get_pmtu(&temp);
3228 		}
3229 	    }
3230 	} else {
3231 	    if (irp == NULL) {
3232 		temp.interval_packet_count = sp->packet_count;
3233 		temp.interval_outoforder_packets = sp->outoforder_packets;
3234 		temp.interval_cnt_error = sp->cnt_error;
3235 	    } else {
3236 		temp.interval_packet_count = sp->packet_count - irp->packet_count;
3237 		temp.interval_outoforder_packets = sp->outoforder_packets - irp->outoforder_packets;
3238 		temp.interval_cnt_error = sp->cnt_error - irp->cnt_error;
3239 	    }
3240 	    temp.packet_count = sp->packet_count;
3241 	    temp.jitter = sp->jitter;
3242 	    temp.outoforder_packets = sp->outoforder_packets;
3243 	    temp.cnt_error = sp->cnt_error;
3244 	}
3245         add_to_interval_list(rp, &temp);
3246         rp->bytes_sent_this_interval = rp->bytes_received_this_interval = 0;
3247     }
3248 
3249     /* Verify that total server's throughput is not above specified limit */
3250     if (test->role == 's') {
3251 	iperf_check_total_rate(test, total_interval_bytes_transferred);
3252     }
3253 }
3254 
3255 /**
3256  * Print intermediate results during a test (interval report).
3257  * Uses print_interval_results to print the results for each stream,
3258  * then prints an interval summary for all streams in this
3259  * interval.
3260  */
3261 static void
3262 iperf_print_intermediate(struct iperf_test *test)
3263 {
3264     struct iperf_stream *sp = NULL;
3265     struct iperf_interval_results *irp;
3266     struct iperf_time temp_time;
3267     cJSON *json_interval;
3268     cJSON *json_interval_streams;
3269 
3270     int lower_mode, upper_mode;
3271     int current_mode;
3272 
3273     /*
3274      * Due to timing oddities, there can be cases, especially on the
3275      * server side, where at the end of a test there is a fairly short
3276      * interval with no data transferred.  This could caused by
3277      * the control and data flows sharing the same path in the network,
3278      * and having the control messages for stopping the test being
3279      * queued behind the data packets.
3280      *
3281      * We'd like to try to omit that last interval when it happens, to
3282      * avoid cluttering data and output with useless stuff.
3283      * So we're going to try to ignore very short intervals (less than
3284      * 10% of the interval time) that have no data.
3285      */
3286     int interval_ok = 0;
3287     SLIST_FOREACH(sp, &test->streams, streams) {
3288 	irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);
3289 	if (irp) {
3290 	    iperf_time_diff(&irp->interval_start_time, &irp->interval_end_time, &temp_time);
3291 	    double interval_len = iperf_time_in_secs(&temp_time);
3292 	    if (test->debug) {
3293 		printf("interval_len %f bytes_transferred %" PRIu64 "\n", interval_len, irp->bytes_transferred);
3294 	    }
3295 
3296 	    /*
3297 	     * If the interval is at least 10% the normal interval
3298 	     * length, or if there were actual bytes transferred,
3299 	     * then we want to keep this interval.
3300 	     */
3301 	    if (interval_len >= test->stats_interval * 0.10 ||
3302 		irp->bytes_transferred > 0) {
3303 		interval_ok = 1;
3304 		if (test->debug) {
3305 		    printf("interval forces keep\n");
3306 		}
3307 	    }
3308 	}
3309     }
3310     if (!interval_ok) {
3311 	if (test->debug) {
3312 	    printf("ignoring short interval with no data\n");
3313 	}
3314 	return;
3315     }
3316 
3317     if (test->json_output) {
3318         json_interval = cJSON_CreateObject();
3319 	if (json_interval == NULL)
3320 	    return;
3321 	cJSON_AddItemToArray(test->json_intervals, json_interval);
3322         json_interval_streams = cJSON_CreateArray();
3323 	if (json_interval_streams == NULL)
3324 	    return;
3325 	cJSON_AddItemToObject(json_interval, "streams", json_interval_streams);
3326     } else {
3327         json_interval = NULL;
3328         json_interval_streams = NULL;
3329     }
3330 
3331     /*
3332      * We must to sum streams separately.
3333      * For bidirectional mode we must to display
3334      * information about sender and receiver streams.
3335      * For client side we must handle sender streams
3336      * firstly and receiver streams for server side.
3337      * The following design allows us to do this.
3338      */
3339 
3340     if (test->mode == BIDIRECTIONAL) {
3341         if (test->role == 'c') {
3342             lower_mode = -1;
3343             upper_mode = 0;
3344         } else {
3345             lower_mode = 0;
3346             upper_mode = 1;
3347         }
3348     } else {
3349         lower_mode = test->mode;
3350         upper_mode = lower_mode;
3351     }
3352 
3353 
3354     for (current_mode = lower_mode; current_mode <= upper_mode; ++current_mode) {
3355         char ubuf[UNIT_LEN];
3356         char nbuf[UNIT_LEN];
3357         char mbuf[UNIT_LEN];
3358         char zbuf[] = "          ";
3359 
3360         iperf_size_t bytes = 0;
3361         double bandwidth;
3362         int retransmits = 0;
3363         double start_time, end_time;
3364 
3365         int total_packets = 0, lost_packets = 0;
3366         double avg_jitter = 0.0, lost_percent;
3367         int stream_must_be_sender = current_mode * current_mode;
3368 
3369         char *sum_name;
3370 
3371         /*  Print stream role just for bidirectional mode. */
3372 
3373         if (test->mode == BIDIRECTIONAL) {
3374             sprintf(mbuf, "[%s-%s]", stream_must_be_sender?"TX":"RX", test->role == 'c'?"C":"S");
3375         } else {
3376             mbuf[0] = '\0';
3377             zbuf[0] = '\0';
3378         }
3379 
3380         SLIST_FOREACH(sp, &test->streams, streams) {
3381             if (sp->sender == stream_must_be_sender) {
3382                 print_interval_results(test, sp, json_interval_streams);
3383                 /* sum up all streams */
3384                 irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);
3385                 if (irp == NULL) {
3386                     iperf_err(test,
3387                             "iperf_print_intermediate error: interval_results is NULL");
3388                     return;
3389                 }
3390                 bytes += irp->bytes_transferred;
3391                 if (test->protocol->id == Ptcp) {
3392                     if (test->sender_has_retransmits == 1) {
3393                         retransmits += irp->interval_retrans;
3394                     }
3395                 } else {
3396                     total_packets += irp->interval_packet_count;
3397                     lost_packets += irp->interval_cnt_error;
3398                     avg_jitter += irp->jitter;
3399                 }
3400             }
3401         }
3402 
3403         /* next build string with sum of all streams */
3404         if (test->num_streams > 1 || test->json_output) {
3405             /*
3406              * With BIDIR give a different JSON object name to the one sent/receive sums.
3407              * The different name is given to the data sent from the server, which is
3408              * the "reverse" channel.  This makes sure that the name reported on the server
3409              * and client are compatible, and the names are the same as with non-bidir,
3410              * except for when reverse is used.
3411              */
3412             sum_name = "sum";
3413             if (test->mode == BIDIRECTIONAL) {
3414                 if ((test->role == 'c' && !stream_must_be_sender) ||
3415                     (test->role != 'c' && stream_must_be_sender))
3416                 {
3417                     sum_name = "sum_bidir_reverse";
3418                 }
3419             }
3420 
3421             sp = SLIST_FIRST(&test->streams); /* reset back to 1st stream */
3422             /* Only do this of course if there was a first stream */
3423             if (sp) {
3424 	    irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);    /* use 1st stream for timing info */
3425 
3426 	    unit_snprintf(ubuf, UNIT_LEN, (double) bytes, 'A');
3427 	    bandwidth = (double) bytes / (double) irp->interval_duration;
3428 	    unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3429 
3430 	    iperf_time_diff(&sp->result->start_time,&irp->interval_start_time, &temp_time);
3431 	    start_time = iperf_time_in_secs(&temp_time);
3432 	    iperf_time_diff(&sp->result->start_time,&irp->interval_end_time, &temp_time);
3433 	    end_time = iperf_time_in_secs(&temp_time);
3434                 if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3435                     if (test->sender_has_retransmits == 1 && stream_must_be_sender) {
3436                         /* Interval sum, TCP with retransmits. */
3437                         if (test->json_output)
3438                             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? */
3439                         else
3440                             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? */
3441                     } else {
3442                         /* Interval sum, TCP without retransmits. */
3443                         if (test->json_output)
3444                             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));
3445                         else
3446                             iperf_printf(test, report_sum_bw_format, mbuf, start_time, end_time, ubuf, nbuf, test->omitting?report_omitted:"");
3447                     }
3448                 } else {
3449                     /* Interval sum, UDP. */
3450                     if (stream_must_be_sender) {
3451                         if (test->json_output)
3452                             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));
3453                         else
3454                             iperf_printf(test, report_sum_bw_udp_sender_format, mbuf, start_time, end_time, ubuf, nbuf, zbuf, total_packets, test->omitting?report_omitted:"");
3455                     } else {
3456                         avg_jitter /= test->num_streams;
3457                         if (total_packets > 0) {
3458                             lost_percent = 100.0 * lost_packets / total_packets;
3459                         }
3460                         else {
3461                             lost_percent = 0.0;
3462                         }
3463                         if (test->json_output)
3464                             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));
3465                         else
3466                             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:"");
3467                     }
3468                 }
3469             }
3470         }
3471     }
3472 }
3473 
3474 /**
3475  * Print overall summary statistics at the end of a test.
3476  */
3477 static void
3478 iperf_print_results(struct iperf_test *test)
3479 {
3480 
3481     cJSON *json_summary_streams = NULL;
3482 
3483     int lower_mode, upper_mode;
3484     int current_mode;
3485 
3486     char *sum_sent_name, *sum_received_name, *sum_name;
3487 
3488     int tmp_sender_has_retransmits = test->sender_has_retransmits;
3489 
3490     /* print final summary for all intervals */
3491 
3492     if (test->json_output) {
3493         json_summary_streams = cJSON_CreateArray();
3494 	if (json_summary_streams == NULL)
3495 	    return;
3496 	cJSON_AddItemToObject(test->json_end, "streams", json_summary_streams);
3497     } else {
3498 	iperf_printf(test, "%s", report_bw_separator);
3499 	if (test->verbose)
3500 	    iperf_printf(test, "%s", report_summary);
3501 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3502 	    if (test->sender_has_retransmits || test->other_side_has_retransmits) {
3503 	        if (test->bidirectional)
3504 	            iperf_printf(test, "%s", report_bw_retrans_header_bidir);
3505 	        else
3506 	            iperf_printf(test, "%s", report_bw_retrans_header);
3507 	    }
3508 	    else {
3509 	        if (test->bidirectional)
3510 	            iperf_printf(test, "%s", report_bw_header_bidir);
3511 	        else
3512 	            iperf_printf(test, "%s", report_bw_header);
3513 	    }
3514 	} else {
3515 	    if (test->bidirectional)
3516 	        iperf_printf(test, "%s", report_bw_udp_header_bidir);
3517 	    else
3518 	        iperf_printf(test, "%s", report_bw_udp_header);
3519 	}
3520     }
3521 
3522     /*
3523      * We must to sum streams separately.
3524      * For bidirectional mode we must to display
3525      * information about sender and receiver streams.
3526      * For client side we must handle sender streams
3527      * firstly and receiver streams for server side.
3528      * The following design allows us to do this.
3529      */
3530 
3531     if (test->mode == BIDIRECTIONAL) {
3532         if (test->role == 'c') {
3533             lower_mode = -1;
3534             upper_mode = 0;
3535         } else {
3536             lower_mode = 0;
3537             upper_mode = 1;
3538         }
3539     } else {
3540         lower_mode = test->mode;
3541         upper_mode = lower_mode;
3542     }
3543 
3544 
3545     for (current_mode = lower_mode; current_mode <= upper_mode; ++current_mode) {
3546         cJSON *json_summary_stream = NULL;
3547         int total_retransmits = 0;
3548         int total_packets = 0, lost_packets = 0;
3549         int sender_packet_count = 0, receiver_packet_count = 0; /* for this stream, this interval */
3550         int sender_total_packets = 0, receiver_total_packets = 0; /* running total */
3551         char ubuf[UNIT_LEN];
3552         char nbuf[UNIT_LEN];
3553         struct stat sb;
3554         char sbuf[UNIT_LEN];
3555         struct iperf_stream *sp = NULL;
3556         iperf_size_t bytes_sent, total_sent = 0;
3557         iperf_size_t bytes_received, total_received = 0;
3558         double start_time, end_time = 0.0, avg_jitter = 0.0, lost_percent = 0.0;
3559         double sender_time = 0.0, receiver_time = 0.0;
3560     struct iperf_time temp_time;
3561         double bandwidth;
3562 
3563         char mbuf[UNIT_LEN];
3564         int stream_must_be_sender = current_mode * current_mode;
3565 
3566 
3567         /*  Print stream role just for bidirectional mode. */
3568 
3569         if (test->mode == BIDIRECTIONAL) {
3570             sprintf(mbuf, "[%s-%s]", stream_must_be_sender?"TX":"RX", test->role == 'c'?"C":"S");
3571         } else {
3572             mbuf[0] = '\0';
3573         }
3574 
3575         /* Get sender_has_retransmits for each sender side (client and server) */
3576         if (test->mode == BIDIRECTIONAL && stream_must_be_sender)
3577             test->sender_has_retransmits = tmp_sender_has_retransmits;
3578         else if (test->mode == BIDIRECTIONAL && !stream_must_be_sender)
3579             test->sender_has_retransmits = test->other_side_has_retransmits;
3580 
3581         start_time = 0.;
3582         sp = SLIST_FIRST(&test->streams);
3583 
3584         /*
3585          * If there is at least one stream, then figure out the length of time
3586          * we were running the tests and print out some statistics about
3587          * the streams.  It's possible to not have any streams at all
3588          * if the client got interrupted before it got to do anything.
3589          *
3590          * Also note that we try to keep separate values for the sender
3591          * and receiver ending times.  Earlier iperf (3.1 and earlier)
3592          * servers didn't send that to the clients, so in this case we fall
3593          * back to using the client's ending timestamp.  The fallback is
3594          * basically emulating what iperf 3.1 did.
3595          */
3596 
3597         if (sp) {
3598     iperf_time_diff(&sp->result->start_time, &sp->result->end_time, &temp_time);
3599     end_time = iperf_time_in_secs(&temp_time);
3600         if (sp->sender) {
3601             sp->result->sender_time = end_time;
3602             if (sp->result->receiver_time == 0.0) {
3603                 sp->result->receiver_time = sp->result->sender_time;
3604             }
3605         }
3606         else {
3607             sp->result->receiver_time = end_time;
3608             if (sp->result->sender_time == 0.0) {
3609                 sp->result->sender_time = sp->result->receiver_time;
3610             }
3611         }
3612         sender_time = sp->result->sender_time;
3613         receiver_time = sp->result->receiver_time;
3614         SLIST_FOREACH(sp, &test->streams, streams) {
3615             if (sp->sender == stream_must_be_sender) {
3616                 if (test->json_output) {
3617                     json_summary_stream = cJSON_CreateObject();
3618                     if (json_summary_stream == NULL)
3619                         return;
3620                     cJSON_AddItemToArray(json_summary_streams, json_summary_stream);
3621                 }
3622 
3623                 bytes_sent = sp->result->bytes_sent - sp->result->bytes_sent_omit;
3624                 bytes_received = sp->result->bytes_received;
3625                 total_sent += bytes_sent;
3626                 total_received += bytes_received;
3627 
3628                 if (sp->sender) {
3629                     sender_packet_count = sp->packet_count;
3630                     receiver_packet_count = sp->peer_packet_count;
3631                 }
3632                 else {
3633                     sender_packet_count = sp->peer_packet_count;
3634                     receiver_packet_count = sp->packet_count;
3635                 }
3636 
3637                 if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3638                     if (test->sender_has_retransmits) {
3639                         total_retransmits += sp->result->stream_retrans;
3640                     }
3641                 } else {
3642                     /*
3643                      * Running total of the total number of packets.  Use the sender packet count if we
3644                      * have it, otherwise use the receiver packet count.
3645                      */
3646                     int packet_count = sender_packet_count ? sender_packet_count : receiver_packet_count;
3647                     total_packets += (packet_count - sp->omitted_packet_count);
3648                     sender_total_packets += (sender_packet_count - sp->omitted_packet_count);
3649                     receiver_total_packets += (receiver_packet_count - sp->omitted_packet_count);
3650                     lost_packets += (sp->cnt_error - sp->omitted_cnt_error);
3651                     avg_jitter += sp->jitter;
3652                 }
3653 
3654                 unit_snprintf(ubuf, UNIT_LEN, (double) bytes_sent, 'A');
3655                 if (sender_time > 0.0) {
3656                     bandwidth = (double) bytes_sent / (double) sender_time;
3657                 }
3658                 else {
3659                     bandwidth = 0.0;
3660                 }
3661                 unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3662                 if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3663                     if (test->sender_has_retransmits) {
3664                         /* Sender summary, TCP and SCTP with retransmits. */
3665                         if (test->json_output)
3666                             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));
3667                         else
3668                             if (test->role == 's' && !sp->sender) {
3669                                 if (test->verbose)
3670                                     iperf_printf(test, report_sender_not_available_format, sp->socket);
3671                             }
3672                             else {
3673                                 iperf_printf(test, report_bw_retrans_format, sp->socket, mbuf, start_time, sender_time, ubuf, nbuf, sp->result->stream_retrans, report_sender);
3674                             }
3675                     } else {
3676                         /* Sender summary, TCP and SCTP without retransmits. */
3677                         if (test->json_output)
3678                             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));
3679                         else
3680                             if (test->role == 's' && !sp->sender) {
3681                                 if (test->verbose)
3682                                     iperf_printf(test, report_sender_not_available_format, sp->socket);
3683                             }
3684                             else {
3685                                 iperf_printf(test, report_bw_format, sp->socket, mbuf, start_time, sender_time, ubuf, nbuf, report_sender);
3686                             }
3687                     }
3688                 } else {
3689                     /* Sender summary, UDP. */
3690                     if (sender_packet_count - sp->omitted_packet_count > 0) {
3691                         lost_percent = 100.0 * (sp->cnt_error - sp->omitted_cnt_error) / (sender_packet_count - sp->omitted_packet_count);
3692                     }
3693                     else {
3694                         lost_percent = 0.0;
3695                     }
3696                     if (test->json_output) {
3697                         /*
3698                          * For hysterical raisins, we only emit one JSON
3699                          * object for the UDP summary, and it contains
3700                          * information for both the sender and receiver
3701                          * side.
3702                          *
3703                          * The JSON format as currently defined only includes one
3704                          * value for the number of packets.  We usually want that
3705                          * to be the sender's value (how many packets were sent
3706                          * by the sender).  However this value might not be
3707                          * available on the receiver in certain circumstances
3708                          * specifically on the server side for a normal test or
3709                          * the client side for a reverse-mode test.  If this
3710                          * is the case, then use the receiver's count of packets
3711                          * instead.
3712                          */
3713                         int packet_count = sender_packet_count ? sender_packet_count : receiver_packet_count;
3714                         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));
3715                     }
3716                     else {
3717                         /*
3718                          * Due to ordering of messages on the control channel,
3719                          * the server cannot report on client-side summary
3720                          * statistics.  If we're the server, omit one set of
3721                          * summary statistics to avoid giving meaningless
3722                          * results.
3723                          */
3724                         if (test->role == 's' && !sp->sender) {
3725                             if (test->verbose)
3726                                 iperf_printf(test, report_sender_not_available_format, sp->socket);
3727                         }
3728                         else {
3729                             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);
3730                         }
3731                         if ((sp->outoforder_packets - sp->omitted_outoforder_packets) > 0)
3732                           iperf_printf(test, report_sum_outoforder, mbuf, start_time, sender_time, (sp->outoforder_packets - sp->omitted_outoforder_packets));
3733                     }
3734                 }
3735 
3736                 if (sp->diskfile_fd >= 0) {
3737                     if (fstat(sp->diskfile_fd, &sb) == 0) {
3738                         /* In the odd case that it's a zero-sized file, say it was all transferred. */
3739                         int percent_sent = 100, percent_received = 100;
3740                         if (sb.st_size > 0) {
3741                             percent_sent = (int) ( ( (double) bytes_sent / (double) sb.st_size ) * 100.0 );
3742                             percent_received = (int) ( ( (double) bytes_received / (double) sb.st_size ) * 100.0 );
3743                         }
3744                         unit_snprintf(sbuf, UNIT_LEN, (double) sb.st_size, 'A');
3745                         if (test->json_output)
3746                             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));
3747                         else
3748                             if (stream_must_be_sender) {
3749                                 iperf_printf(test, report_diskfile, ubuf, sbuf, percent_sent, test->diskfile_name);
3750                             }
3751                             else {
3752                                 unit_snprintf(ubuf, UNIT_LEN, (double) bytes_received, 'A');
3753                                 iperf_printf(test, report_diskfile, ubuf, sbuf, percent_received, test->diskfile_name);
3754                             }
3755                     }
3756                 }
3757 
3758                 unit_snprintf(ubuf, UNIT_LEN, (double) bytes_received, 'A');
3759                 if (receiver_time > 0) {
3760                     bandwidth = (double) bytes_received / (double) receiver_time;
3761                 }
3762                 else {
3763                     bandwidth = 0.0;
3764                 }
3765                 unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3766                 if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3767                     /* Receiver summary, TCP and SCTP */
3768                     if (test->json_output)
3769                         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));
3770                     else
3771                         if (test->role == 's' && sp->sender) {
3772                             if (test->verbose)
3773                                 iperf_printf(test, report_receiver_not_available_format, sp->socket);
3774                         }
3775                         else {
3776                             iperf_printf(test, report_bw_format, sp->socket, mbuf, start_time, receiver_time, ubuf, nbuf, report_receiver);
3777                         }
3778                 }
3779                 else {
3780                     /*
3781                      * Receiver summary, UDP.  Note that JSON was emitted with
3782                      * the sender summary, so we only deal with human-readable
3783                      * data here.
3784                      */
3785                     if (! test->json_output) {
3786                         if (receiver_packet_count - sp->omitted_packet_count > 0) {
3787                             lost_percent = 100.0 * (sp->cnt_error - sp->omitted_cnt_error) / (receiver_packet_count - sp->omitted_packet_count);
3788                         }
3789                         else {
3790                             lost_percent = 0.0;
3791                         }
3792 
3793                         if (test->role == 's' && sp->sender) {
3794                             if (test->verbose)
3795                                 iperf_printf(test, report_receiver_not_available_format, sp->socket);
3796                         }
3797                         else {
3798                             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);
3799                         }
3800                     }
3801                 }
3802             }
3803         }
3804         }
3805 
3806         if (test->num_streams > 1 || test->json_output) {
3807             /*
3808              * With BIDIR give a different JSON object name to the one sent/receive sums.
3809              * The different name is given to the data sent from the server, which is
3810              * the "reverse" channel.  This makes sure that the name reported on the server
3811              * and client are compatible, and the names are the same as with non-bidir,
3812              * except for when reverse is used.
3813              */
3814             sum_name = "sum";
3815             sum_sent_name = "sum_sent";
3816             sum_received_name = "sum_received";
3817             if (test->mode == BIDIRECTIONAL) {
3818                 if ((test->role == 'c' && !stream_must_be_sender) ||
3819                     (test->role != 'c' && stream_must_be_sender))
3820                 {
3821                     sum_name = "sum_bidir_reverse";
3822                     sum_sent_name = "sum_sent_bidir_reverse";
3823                     sum_received_name = "sum_received_bidir_reverse";
3824                 }
3825 
3826             }
3827 
3828             unit_snprintf(ubuf, UNIT_LEN, (double) total_sent, 'A');
3829             /* If no tests were run, arbitrarily set bandwidth to 0. */
3830             if (sender_time > 0.0) {
3831                 bandwidth = (double) total_sent / (double) sender_time;
3832             }
3833             else {
3834                 bandwidth = 0.0;
3835             }
3836             unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3837             if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
3838                 if (test->sender_has_retransmits) {
3839                     /* Summary sum, TCP with retransmits. */
3840                     if (test->json_output)
3841                         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));
3842                     else
3843                         if (test->role == 's' && !stream_must_be_sender) {
3844                             if (test->verbose)
3845                                 iperf_printf(test, report_sender_not_available_summary_format, "SUM");
3846                         }
3847                         else {
3848                           iperf_printf(test, report_sum_bw_retrans_format, mbuf, start_time, sender_time, ubuf, nbuf, total_retransmits, report_sender);
3849                         }
3850                 } else {
3851                     /* Summary sum, TCP without retransmits. */
3852                     if (test->json_output)
3853                         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));
3854                     else
3855                         if (test->role == 's' && !stream_must_be_sender) {
3856                             if (test->verbose)
3857                                 iperf_printf(test, report_sender_not_available_summary_format, "SUM");
3858                         }
3859                         else {
3860                             iperf_printf(test, report_sum_bw_format, mbuf, start_time, sender_time, ubuf, nbuf, report_sender);
3861                         }
3862                 }
3863                 unit_snprintf(ubuf, UNIT_LEN, (double) total_received, 'A');
3864                 /* If no tests were run, set received bandwidth to 0 */
3865                 if (receiver_time > 0.0) {
3866                     bandwidth = (double) total_received / (double) receiver_time;
3867                 }
3868                 else {
3869                     bandwidth = 0.0;
3870                 }
3871                 unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3872                 if (test->json_output)
3873                     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));
3874                 else
3875                     if (test->role == 's' && stream_must_be_sender) {
3876                         if (test->verbose)
3877                             iperf_printf(test, report_receiver_not_available_summary_format, "SUM");
3878                     }
3879                     else {
3880                         iperf_printf(test, report_sum_bw_format, mbuf, start_time, receiver_time, ubuf, nbuf, report_receiver);
3881                     }
3882             } else {
3883                 /* Summary sum, UDP. */
3884                 avg_jitter /= test->num_streams;
3885                 /* If no packets were sent, arbitrarily set loss percentage to 0. */
3886                 if (total_packets > 0) {
3887                     lost_percent = 100.0 * lost_packets / total_packets;
3888                 }
3889                 else {
3890                     lost_percent = 0.0;
3891                 }
3892                 if (test->json_output) {
3893                     /*
3894                      * Original, summary structure. Using this
3895                      * structure is not recommended due to
3896                      * ambiguities between the sender and receiver.
3897                      */
3898                     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));
3899                     /*
3900                      * Separate sum_sent and sum_received structures.
3901                      * Using these structures to get the most complete
3902                      * information about UDP transfer.
3903                      */
3904                     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));
3905                     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));
3906                 } else {
3907                     /*
3908                      * On the client we have both sender and receiver overall summary
3909                      * stats.  On the server we have only the side that was on the
3910                      * server.  Output whatever we have.
3911                      */
3912                     if (! (test->role == 's' && !stream_must_be_sender) ) {
3913                         unit_snprintf(ubuf, UNIT_LEN, (double) total_sent, 'A');
3914                         iperf_printf(test, report_sum_bw_udp_format, mbuf, start_time, sender_time, ubuf, nbuf, 0.0, 0, sender_total_packets, 0.0, "sender");
3915                     }
3916                     if (! (test->role == 's' && stream_must_be_sender) ) {
3917 
3918                         unit_snprintf(ubuf, UNIT_LEN, (double) total_received, 'A');
3919                         /* Compute received bandwidth. */
3920                         if (end_time > 0.0) {
3921                             bandwidth = (double) total_received / (double) receiver_time;
3922                         }
3923                         else {
3924                             bandwidth = 0.0;
3925                         }
3926                         unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
3927                         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");
3928                     }
3929                 }
3930             }
3931         }
3932 
3933         if (test->json_output && current_mode == upper_mode) {
3934             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]));
3935             if (test->protocol->id == Ptcp) {
3936                 char *snd_congestion = NULL, *rcv_congestion = NULL;
3937                 if (stream_must_be_sender) {
3938                     snd_congestion = test->congestion_used;
3939                     rcv_congestion = test->remote_congestion_used;
3940                 }
3941                 else {
3942                     snd_congestion = test->remote_congestion_used;
3943                     rcv_congestion = test->congestion_used;
3944                 }
3945                 if (snd_congestion) {
3946                     cJSON_AddStringToObject(test->json_end, "sender_tcp_congestion", snd_congestion);
3947                 }
3948                 if (rcv_congestion) {
3949                     cJSON_AddStringToObject(test->json_end, "receiver_tcp_congestion", rcv_congestion);
3950                 }
3951             }
3952         }
3953         else {
3954             if (test->verbose) {
3955                 if (stream_must_be_sender) {
3956                     if (test->bidirectional) {
3957                         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]);
3958                         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]);
3959                     } else
3960                         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]);
3961                 }
3962                 if (test->protocol->id == Ptcp) {
3963                     char *snd_congestion = NULL, *rcv_congestion = NULL;
3964                     if (stream_must_be_sender) {
3965                         snd_congestion = test->congestion_used;
3966                         rcv_congestion = test->remote_congestion_used;
3967                     }
3968                     else {
3969                         snd_congestion = test->remote_congestion_used;
3970                         rcv_congestion = test->congestion_used;
3971                     }
3972                     if (snd_congestion) {
3973                         iperf_printf(test, "snd_tcp_congestion %s\n", snd_congestion);
3974                     }
3975                     if (rcv_congestion) {
3976                         iperf_printf(test, "rcv_tcp_congestion %s\n", rcv_congestion);
3977                     }
3978                 }
3979             }
3980 
3981             /* Print server output if we're on the client and it was requested/provided */
3982             if (test->role == 'c' && iperf_get_test_get_server_output(test) && !test->json_output) {
3983                 if (test->json_server_output) {
3984 		    char *str = cJSON_Print(test->json_server_output);
3985                     iperf_printf(test, "\nServer JSON output:\n%s\n", str);
3986 		    cJSON_free(str);
3987                     cJSON_Delete(test->json_server_output);
3988                     test->json_server_output = NULL;
3989                 }
3990                 if (test->server_output_text) {
3991                     iperf_printf(test, "\nServer output:\n%s\n", test->server_output_text);
3992                     test->server_output_text = NULL;
3993                 }
3994             }
3995         }
3996     }
3997 
3998     /* Set real sender_has_retransmits for current side */
3999     if (test->mode == BIDIRECTIONAL)
4000         test->sender_has_retransmits = tmp_sender_has_retransmits;
4001 }
4002 
4003 /**************************************************************************/
4004 
4005 /**
4006  * Main report-printing callback.
4007  * Prints results either during a test (interval report only) or
4008  * after the entire test has been run (last interval report plus
4009  * overall summary).
4010  */
4011 void
4012 iperf_reporter_callback(struct iperf_test *test)
4013 {
4014     switch (test->state) {
4015         case TEST_RUNNING:
4016         case STREAM_RUNNING:
4017             /* print interval results for each stream */
4018             iperf_print_intermediate(test);
4019             break;
4020         case TEST_END:
4021         case DISPLAY_RESULTS:
4022             iperf_print_intermediate(test);
4023             iperf_print_results(test);
4024             break;
4025     }
4026 
4027 }
4028 
4029 /**
4030  * Print the interval results for one stream.
4031  * This function needs to know about the overall test so it can determine the
4032  * context for printing headers, separators, etc.
4033  */
4034 static void
4035 print_interval_results(struct iperf_test *test, struct iperf_stream *sp, cJSON *json_interval_streams)
4036 {
4037     char ubuf[UNIT_LEN];
4038     char nbuf[UNIT_LEN];
4039     char cbuf[UNIT_LEN];
4040     char mbuf[UNIT_LEN];
4041     char zbuf[] = "          ";
4042     double st = 0., et = 0.;
4043     struct iperf_time temp_time;
4044     struct iperf_interval_results *irp = NULL;
4045     double bandwidth, lost_percent;
4046 
4047     if (test->mode == BIDIRECTIONAL) {
4048         sprintf(mbuf, "[%s-%s]", sp->sender?"TX":"RX", test->role == 'c'?"C":"S");
4049     } else {
4050         mbuf[0] = '\0';
4051         zbuf[0] = '\0';
4052     }
4053 
4054     irp = TAILQ_LAST(&sp->result->interval_results, irlisthead); /* get last entry in linked list */
4055     if (irp == NULL) {
4056 	iperf_err(test, "print_interval_results error: interval_results is NULL");
4057         return;
4058     }
4059     if (!test->json_output) {
4060 	/* First stream? */
4061 	if (sp == SLIST_FIRST(&test->streams)) {
4062 	    /* It it's the first interval, print the header;
4063 	    ** else if there's more than one stream, print the separator;
4064 	    ** else nothing.
4065 	    */
4066 	    if (iperf_time_compare(&sp->result->start_time, &irp->interval_start_time) == 0) {
4067 		if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
4068 		    if (test->sender_has_retransmits == 1) {
4069 		        if (test->bidirectional)
4070 		            iperf_printf(test, "%s", report_bw_retrans_cwnd_header_bidir);
4071 		        else
4072 		            iperf_printf(test, "%s", report_bw_retrans_cwnd_header);
4073 		    }
4074 		    else {
4075 	                if (test->bidirectional)
4076 	                    iperf_printf(test, "%s", report_bw_header_bidir);
4077 	                else
4078 	                    iperf_printf(test, "%s", report_bw_header);
4079 	            }
4080 		} else {
4081 		    if (test->mode == SENDER) {
4082 		        iperf_printf(test, "%s", report_bw_udp_sender_header);
4083 		    } else if (test->mode == RECEIVER){
4084 		        iperf_printf(test, "%s", report_bw_udp_header);
4085 		    } else {
4086 		        /* BIDIRECTIONAL */
4087 		        iperf_printf(test, "%s", report_bw_udp_header_bidir);
4088 		    }
4089 		}
4090 	    } else if (test->num_streams > 1)
4091 		iperf_printf(test, "%s", report_bw_separator);
4092 	}
4093     }
4094 
4095     unit_snprintf(ubuf, UNIT_LEN, (double) (irp->bytes_transferred), 'A');
4096     if (irp->interval_duration > 0.0) {
4097 	bandwidth = (double) irp->bytes_transferred / (double) irp->interval_duration;
4098     }
4099     else {
4100 	bandwidth = 0.0;
4101     }
4102     unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
4103 
4104     iperf_time_diff(&sp->result->start_time, &irp->interval_start_time, &temp_time);
4105     st = iperf_time_in_secs(&temp_time);
4106     iperf_time_diff(&sp->result->start_time, &irp->interval_end_time, &temp_time);
4107     et = iperf_time_in_secs(&temp_time);
4108 
4109     if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
4110 	if (test->sender_has_retransmits == 1 && sp->sender) {
4111 	    /* Interval, TCP with retransmits. */
4112 	    if (test->json_output)
4113 		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));
4114 	    else {
4115 		unit_snprintf(cbuf, UNIT_LEN, irp->snd_cwnd, 'A');
4116 		iperf_printf(test, report_bw_retrans_cwnd_format, sp->socket, mbuf, st, et, ubuf, nbuf, irp->interval_retrans, cbuf, irp->omitted?report_omitted:"");
4117 	    }
4118 	} else {
4119 	    /* Interval, TCP without retransmits. */
4120 	    if (test->json_output)
4121 		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));
4122 	    else
4123 		iperf_printf(test, report_bw_format, sp->socket, mbuf, st, et, ubuf, nbuf, irp->omitted?report_omitted:"");
4124 	}
4125     } else {
4126 	/* Interval, UDP. */
4127 	if (sp->sender) {
4128 	    if (test->json_output)
4129 		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));
4130 	    else
4131 		iperf_printf(test, report_bw_udp_sender_format, sp->socket, mbuf, st, et, ubuf, nbuf, zbuf, irp->interval_packet_count, irp->omitted?report_omitted:"");
4132 	} else {
4133 	    if (irp->interval_packet_count > 0) {
4134 		lost_percent = 100.0 * irp->interval_cnt_error / irp->interval_packet_count;
4135 	    }
4136 	    else {
4137 		lost_percent = 0.0;
4138 	    }
4139 	    if (test->json_output)
4140 		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));
4141 	    else
4142 		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:"");
4143 	}
4144     }
4145 
4146     if (test->logfile || test->forceflush)
4147         iflush(test);
4148 }
4149 
4150 /**************************************************************************/
4151 void
4152 iperf_free_stream(struct iperf_stream *sp)
4153 {
4154     struct iperf_interval_results *irp, *nirp;
4155 
4156     /* XXX: need to free interval list too! */
4157     munmap(sp->buffer, sp->test->settings->blksize);
4158     close(sp->buffer_fd);
4159     if (sp->diskfile_fd >= 0)
4160 	close(sp->diskfile_fd);
4161     for (irp = TAILQ_FIRST(&sp->result->interval_results); irp != NULL; irp = nirp) {
4162         nirp = TAILQ_NEXT(irp, irlistentries);
4163         free(irp);
4164     }
4165     free(sp->result);
4166     if (sp->send_timer != NULL)
4167 	tmr_cancel(sp->send_timer);
4168     free(sp);
4169 }
4170 
4171 /**************************************************************************/
4172 struct iperf_stream *
4173 iperf_new_stream(struct iperf_test *test, int s, int sender)
4174 {
4175     struct iperf_stream *sp;
4176     int ret = 0;
4177 
4178     char template[1024];
4179     if (test->tmp_template) {
4180         snprintf(template, sizeof(template) / sizeof(char), "%s", test->tmp_template);
4181     } else {
4182         //find the system temporary dir *unix, windows, cygwin support
4183         char* tempdir = getenv("TMPDIR");
4184         if (tempdir == 0){
4185             tempdir = getenv("TEMP");
4186         }
4187         if (tempdir == 0){
4188             tempdir = getenv("TMP");
4189         }
4190         if (tempdir == 0){
4191             tempdir = "/tmp";
4192         }
4193         snprintf(template, sizeof(template) / sizeof(char), "%s/iperf3.XXXXXX", tempdir);
4194     }
4195 
4196     sp = (struct iperf_stream *) malloc(sizeof(struct iperf_stream));
4197     if (!sp) {
4198         i_errno = IECREATESTREAM;
4199         return NULL;
4200     }
4201 
4202     memset(sp, 0, sizeof(struct iperf_stream));
4203 
4204     sp->sender = sender;
4205     sp->test = test;
4206     sp->settings = test->settings;
4207     sp->result = (struct iperf_stream_result *) malloc(sizeof(struct iperf_stream_result));
4208     if (!sp->result) {
4209         free(sp);
4210         i_errno = IECREATESTREAM;
4211         return NULL;
4212     }
4213 
4214     memset(sp->result, 0, sizeof(struct iperf_stream_result));
4215     TAILQ_INIT(&sp->result->interval_results);
4216 
4217     /* Create and randomize the buffer */
4218     sp->buffer_fd = mkstemp(template);
4219     if (sp->buffer_fd == -1) {
4220         i_errno = IECREATESTREAM;
4221         free(sp->result);
4222         free(sp);
4223         return NULL;
4224     }
4225     if (unlink(template) < 0) {
4226         i_errno = IECREATESTREAM;
4227         free(sp->result);
4228         free(sp);
4229         return NULL;
4230     }
4231     if (ftruncate(sp->buffer_fd, test->settings->blksize) < 0) {
4232         i_errno = IECREATESTREAM;
4233         free(sp->result);
4234         free(sp);
4235         return NULL;
4236     }
4237     sp->buffer = (char *) mmap(NULL, test->settings->blksize, PROT_READ|PROT_WRITE, MAP_PRIVATE, sp->buffer_fd, 0);
4238     if (sp->buffer == MAP_FAILED) {
4239         i_errno = IECREATESTREAM;
4240         free(sp->result);
4241         free(sp);
4242         return NULL;
4243     }
4244     sp->pending_size = 0;
4245 
4246     /* Set socket */
4247     sp->socket = s;
4248 
4249     sp->snd = test->protocol->send;
4250     sp->rcv = test->protocol->recv;
4251 
4252     if (test->diskfile_name != (char*) 0) {
4253 	sp->diskfile_fd = open(test->diskfile_name, sender ? O_RDONLY : (O_WRONLY|O_CREAT|O_TRUNC), S_IRUSR|S_IWUSR);
4254 	if (sp->diskfile_fd == -1) {
4255 	    i_errno = IEFILE;
4256             munmap(sp->buffer, sp->test->settings->blksize);
4257             free(sp->result);
4258             free(sp);
4259 	    return NULL;
4260 	}
4261         sp->snd2 = sp->snd;
4262 	sp->snd = diskfile_send;
4263 	sp->rcv2 = sp->rcv;
4264 	sp->rcv = diskfile_recv;
4265     } else
4266         sp->diskfile_fd = -1;
4267 
4268     /* Initialize stream */
4269     if (test->repeating_payload)
4270         fill_with_repeating_pattern(sp->buffer, test->settings->blksize);
4271     else
4272         ret = readentropy(sp->buffer, test->settings->blksize);
4273 
4274     if ((ret < 0) || (iperf_init_stream(sp, test) < 0)) {
4275         close(sp->buffer_fd);
4276         munmap(sp->buffer, sp->test->settings->blksize);
4277         free(sp->result);
4278         free(sp);
4279         return NULL;
4280     }
4281     iperf_add_stream(test, sp);
4282 
4283     return sp;
4284 }
4285 
4286 /**************************************************************************/
4287 int
4288 iperf_init_stream(struct iperf_stream *sp, struct iperf_test *test)
4289 {
4290     socklen_t len;
4291     int opt;
4292 
4293     len = sizeof(struct sockaddr_storage);
4294     if (getsockname(sp->socket, (struct sockaddr *) &sp->local_addr, &len) < 0) {
4295         i_errno = IEINITSTREAM;
4296         return -1;
4297     }
4298     len = sizeof(struct sockaddr_storage);
4299     if (getpeername(sp->socket, (struct sockaddr *) &sp->remote_addr, &len) < 0) {
4300         i_errno = IEINITSTREAM;
4301         return -1;
4302     }
4303 
4304     /* Set IP TOS */
4305     if ((opt = test->settings->tos)) {
4306         if (getsockdomain(sp->socket) == AF_INET6) {
4307 #ifdef IPV6_TCLASS
4308             if (setsockopt(sp->socket, IPPROTO_IPV6, IPV6_TCLASS, &opt, sizeof(opt)) < 0) {
4309                 i_errno = IESETCOS;
4310                 return -1;
4311             }
4312 #else
4313             i_errno = IESETCOS;
4314             return -1;
4315 #endif
4316         } else {
4317             if (setsockopt(sp->socket, IPPROTO_IP, IP_TOS, &opt, sizeof(opt)) < 0) {
4318                 i_errno = IESETTOS;
4319                 return -1;
4320             }
4321         }
4322     }
4323 
4324 #if defined(HAVE_DONT_FRAGMENT)
4325     /* Set Don't Fragment (DF). Only applicable to IPv4/UDP tests. */
4326     if (iperf_get_test_protocol_id(test) == Pudp &&
4327         getsockdomain(sp->socket) == AF_INET &&
4328         iperf_get_dont_fragment(test)) {
4329 
4330         /*
4331          * There are multiple implementations of this feature depending on the OS.
4332          * We need to handle separately Linux, UNIX, and Windows, as well as
4333          * the case that DF isn't supported at all (such as on macOS).
4334          */
4335 #if defined(IP_MTU_DISCOVER) /* Linux version of IP_DONTFRAG */
4336         opt = IP_PMTUDISC_DO;
4337         if (setsockopt(sp->socket, IPPROTO_IP, IP_MTU_DISCOVER, &opt, sizeof(opt)) < 0) {
4338             i_errno = IESETDONTFRAGMENT;
4339             return -1;
4340         }
4341 #else
4342 #if defined(IP_DONTFRAG) /* UNIX does IP_DONTFRAG */
4343         opt = 1;
4344         if (setsockopt(sp->socket, IPPROTO_IP, IP_DONTFRAG, &opt, sizeof(opt)) < 0) {
4345             i_errno = IESETDONTFRAGMENT;
4346             return -1;
4347         }
4348 #else
4349 #if defined(IP_DONTFRAGMENT) /* Windows does IP_DONTFRAGMENT */
4350         opt = 1;
4351         if (setsockopt(sp->socket, IPPROTO_IP, IP_DONTFRAGMENT, &opt, sizeof(opt)) < 0) {
4352             i_errno = IESETDONTFRAGMENT;
4353             return -1;
4354         }
4355 #else
4356 	i_errno = IESETDONTFRAGMENT;
4357 	return -1;
4358 #endif /* IP_DONTFRAGMENT */
4359 #endif /* IP_DONTFRAG */
4360 #endif /* IP_MTU_DISCOVER */
4361     }
4362 #endif /* HAVE_DONT_FRAGMENT */
4363     return 0;
4364 }
4365 
4366 /**************************************************************************/
4367 void
4368 iperf_add_stream(struct iperf_test *test, struct iperf_stream *sp)
4369 {
4370     int i;
4371     struct iperf_stream *n, *prev;
4372 
4373     if (SLIST_EMPTY(&test->streams)) {
4374         SLIST_INSERT_HEAD(&test->streams, sp, streams);
4375         sp->id = 1;
4376     } else {
4377         // for (n = test->streams, i = 2; n->next; n = n->next, ++i);
4378         // NOTE: this would ideally be set to 1, however this will not
4379         //       be changed since it is not causing a significant problem
4380         //       and changing it would break multi-stream tests between old
4381         //       and new iperf3 versions.
4382         i = 2;
4383         SLIST_FOREACH(n, &test->streams, streams) {
4384             prev = n;
4385             ++i;
4386         }
4387         SLIST_INSERT_AFTER(prev, sp, streams);
4388         sp->id = i;
4389     }
4390 }
4391 
4392 /* This pair of routines gets inserted into the snd/rcv function pointers
4393 ** when there's a -F flag. They handle the file stuff and call the real
4394 ** snd/rcv functions, which have been saved in snd2/rcv2.
4395 **
4396 ** The advantage of doing it this way is that in the much more common
4397 ** case of no -F flag, there is zero extra overhead.
4398 */
4399 
4400 static int
4401 diskfile_send(struct iperf_stream *sp)
4402 {
4403     int r;
4404     int buffer_left = sp->diskfile_left; // represents total data in buffer to be sent out
4405     static int rtot;
4406 
4407     /* if needed, read enough data from the disk to fill up the buffer */
4408     if (sp->diskfile_left < sp->test->settings->blksize && !sp->test->done) {
4409     	r = read(sp->diskfile_fd, sp->buffer, sp->test->settings->blksize -
4410     		 sp->diskfile_left);
4411         buffer_left += r;
4412     	rtot += r;
4413     	if (sp->test->debug) {
4414     	    printf("read %d bytes from file, %d total\n", r, rtot);
4415     	}
4416 
4417         // If the buffer doesn't contain a full buffer at this point,
4418         // adjust the size of the data to send.
4419         if (buffer_left != sp->test->settings->blksize) {
4420             if (sp->test->debug)
4421                 printf("possible eof\n");
4422             // setting data size to be sent,
4423             // which is less than full block/buffer size
4424             // (to be used by iperf_tcp_send, etc.)
4425             sp->pending_size = buffer_left;
4426         }
4427 
4428         // If there's no work left, we're done.
4429         if (buffer_left == 0) {
4430     	    sp->test->done = 1;
4431     	    if (sp->test->debug)
4432     		  printf("done\n");
4433     	}
4434     }
4435 
4436     // If there's no data left in the file or in the buffer, we're done.
4437     // No more data available to be sent.
4438     // Return without sending data to the network
4439     if( sp->test->done || buffer_left == 0 ){
4440         if (sp->test->debug)
4441               printf("already done\n");
4442         sp->test->done = 1;
4443         return 0;
4444     }
4445 
4446     r = sp->snd2(sp);
4447     if (r < 0) {
4448 	return r;
4449     }
4450     /*
4451      * Compute how much data is in the buffer but didn't get sent.
4452      * If there are bytes that got left behind, slide them to the
4453      * front of the buffer so they can hopefully go out on the next
4454      * pass.
4455      */
4456     sp->diskfile_left = buffer_left - r;
4457     if (sp->diskfile_left && sp->diskfile_left < sp->test->settings->blksize) {
4458 	memcpy(sp->buffer,
4459 	       sp->buffer + (sp->test->settings->blksize - sp->diskfile_left),
4460 	       sp->diskfile_left);
4461 	if (sp->test->debug)
4462 	    printf("Shifting %d bytes by %d\n", sp->diskfile_left, (sp->test->settings->blksize - sp->diskfile_left));
4463     }
4464     return r;
4465 }
4466 
4467 static int
4468 diskfile_recv(struct iperf_stream *sp)
4469 {
4470     int r;
4471 
4472     r = sp->rcv2(sp);
4473     if (r > 0) {
4474 	// NOTE: Currently ignoring the return value of writing to disk
4475 	(void) (write(sp->diskfile_fd, sp->buffer, r) + 1);
4476     }
4477     return r;
4478 }
4479 
4480 
4481 void
4482 iperf_catch_sigend(void (*handler)(int))
4483 {
4484 #ifdef SIGINT
4485     signal(SIGINT, handler);
4486 #endif
4487 #ifdef SIGTERM
4488     signal(SIGTERM, handler);
4489 #endif
4490 #ifdef SIGHUP
4491     signal(SIGHUP, handler);
4492 #endif
4493 }
4494 
4495 /**
4496  * Called as a result of getting a signal.
4497  * Depending on the current state of the test (and the role of this
4498  * process) compute and report one more set of ending statistics
4499  * before cleaning up and exiting.
4500  */
4501 void
4502 iperf_got_sigend(struct iperf_test *test)
4503 {
4504     /*
4505      * If we're the client, or if we're a server and running a test,
4506      * then dump out the accumulated stats so far.
4507      */
4508     if (test->role == 'c' ||
4509       (test->role == 's' && test->state == TEST_RUNNING)) {
4510 
4511 	test->done = 1;
4512 	cpu_util(test->cpu_util);
4513 	test->stats_callback(test);
4514 	test->state = DISPLAY_RESULTS; /* change local state only */
4515 	if (test->on_test_finish)
4516 	    test->on_test_finish(test);
4517 	test->reporter_callback(test);
4518     }
4519 
4520     if (test->ctrl_sck >= 0) {
4521 	test->state = (test->role == 'c') ? CLIENT_TERMINATE : SERVER_TERMINATE;
4522 	(void) Nwrite(test->ctrl_sck, (char*) &test->state, sizeof(signed char), Ptcp);
4523     }
4524     i_errno = (test->role == 'c') ? IECLIENTTERM : IESERVERTERM;
4525     iperf_errexit(test, "interrupt - %s", iperf_strerror(i_errno));
4526 }
4527 
4528 /* Try to write a PID file if requested, return -1 on an error. */
4529 int
4530 iperf_create_pidfile(struct iperf_test *test)
4531 {
4532     if (test->pidfile) {
4533 	int fd;
4534 	char buf[8];
4535 
4536 	/* See if the file already exists and we can read it. */
4537 	fd = open(test->pidfile, O_RDONLY, 0);
4538 	if (fd >= 0) {
4539 	    if (read(fd, buf, sizeof(buf) - 1) >= 0) {
4540 
4541 		/* We read some bytes, see if they correspond to a valid PID */
4542 		pid_t pid;
4543 		pid = atoi(buf);
4544 		if (pid > 0) {
4545 
4546 		    /* See if the process exists. */
4547 		    if (kill(pid, 0) == 0) {
4548 			/*
4549 			 * Make sure not to try to delete existing PID file by
4550 			 * scribbling over the pathname we'd use to refer to it.
4551 			 * Then exit with an error.
4552 			 */
4553 			free(test->pidfile);
4554 			test->pidfile = NULL;
4555 			iperf_errexit(test, "Another instance of iperf3 appears to be running");
4556 		    }
4557 		}
4558 	    }
4559 	}
4560 
4561 	/*
4562 	 * File didn't exist, we couldn't read it, or it didn't correspond to
4563 	 * a running process.  Try to create it.
4564 	 */
4565 	fd = open(test->pidfile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR|S_IWUSR);
4566 	if (fd < 0) {
4567 	    return -1;
4568 	}
4569 	snprintf(buf, sizeof(buf), "%d", getpid()); /* no trailing newline */
4570 	if (write(fd, buf, strlen(buf)) < 0) {
4571 	    return -1;
4572 	}
4573 	if (close(fd) < 0) {
4574 	    return -1;
4575 	};
4576     }
4577     return 0;
4578 }
4579 
4580 /* Get rid of a PID file, return -1 on error. */
4581 int
4582 iperf_delete_pidfile(struct iperf_test *test)
4583 {
4584     if (test->pidfile) {
4585 	if (unlink(test->pidfile) < 0) {
4586 	    return -1;
4587 	}
4588     }
4589     return 0;
4590 }
4591 
4592 int
4593 iperf_json_start(struct iperf_test *test)
4594 {
4595     test->json_top = cJSON_CreateObject();
4596     if (test->json_top == NULL)
4597         return -1;
4598     test->json_start = cJSON_CreateObject();
4599     if (test->json_start == NULL)
4600         return -1;
4601     cJSON_AddItemToObject(test->json_top, "start", test->json_start);
4602     test->json_connected = cJSON_CreateArray();
4603     if (test->json_connected == NULL)
4604         return -1;
4605     cJSON_AddItemToObject(test->json_start, "connected", test->json_connected);
4606     test->json_intervals = cJSON_CreateArray();
4607     if (test->json_intervals == NULL)
4608         return -1;
4609     cJSON_AddItemToObject(test->json_top, "intervals", test->json_intervals);
4610     test->json_end = cJSON_CreateObject();
4611     if (test->json_end == NULL)
4612         return -1;
4613     cJSON_AddItemToObject(test->json_top, "end", test->json_end);
4614     return 0;
4615 }
4616 
4617 int
4618 iperf_json_finish(struct iperf_test *test)
4619 {
4620     if (test->title)
4621 	cJSON_AddStringToObject(test->json_top, "title", test->title);
4622     if (test->extra_data)
4623 	cJSON_AddStringToObject(test->json_top, "extra_data", test->extra_data);
4624     /* Include server output */
4625     if (test->json_server_output) {
4626 	cJSON_AddItemToObject(test->json_top, "server_output_json", test->json_server_output);
4627     }
4628     if (test->server_output_text) {
4629 	cJSON_AddStringToObject(test->json_top, "server_output_text", test->server_output_text);
4630     }
4631     // Get ASCII rendering of JSON structure.  Then make our
4632     // own copy of it and return the storage that cJSON allocated
4633     // on our behalf.  We keep our own copy around.
4634     char *str = cJSON_Print(test->json_top);
4635     if (str == NULL)
4636 	return -1;
4637     test->json_output_string = strdup(str);
4638     cJSON_free(str);
4639     if (test->json_output_string == NULL)
4640         return -1;
4641     fprintf(test->outfile, "%s\n", test->json_output_string);
4642     iflush(test);
4643     cJSON_Delete(test->json_top);
4644     test->json_top = test->json_start = test->json_connected = test->json_intervals = test->json_server_output = test->json_end = NULL;
4645     return 0;
4646 }
4647 
4648 
4649 /* CPU affinity stuff - Linux, FreeBSD, and Windows only. */
4650 
4651 int
4652 iperf_setaffinity(struct iperf_test *test, int affinity)
4653 {
4654 #if defined(HAVE_SCHED_SETAFFINITY)
4655     cpu_set_t cpu_set;
4656 
4657     CPU_ZERO(&cpu_set);
4658     CPU_SET(affinity, &cpu_set);
4659     if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0) {
4660 	i_errno = IEAFFINITY;
4661         return -1;
4662     }
4663     return 0;
4664 #elif defined(HAVE_CPUSET_SETAFFINITY)
4665     cpuset_t cpumask;
4666 
4667     if(cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1,
4668                           sizeof(cpuset_t), &test->cpumask) != 0) {
4669         i_errno = IEAFFINITY;
4670         return -1;
4671     }
4672 
4673     CPU_ZERO(&cpumask);
4674     CPU_SET(affinity, &cpumask);
4675 
4676     if(cpuset_setaffinity(CPU_LEVEL_WHICH,CPU_WHICH_PID, -1,
4677                           sizeof(cpuset_t), &cpumask) != 0) {
4678         i_errno = IEAFFINITY;
4679         return -1;
4680     }
4681     return 0;
4682 #elif defined(HAVE_SETPROCESSAFFINITYMASK)
4683 	HANDLE process = GetCurrentProcess();
4684 	DWORD_PTR processAffinityMask = 1 << affinity;
4685 
4686 	if (SetProcessAffinityMask(process, processAffinityMask) == 0) {
4687 		i_errno = IEAFFINITY;
4688 		return -1;
4689 	}
4690 	return 0;
4691 #else /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY nor HAVE_SETPROCESSAFFINITYMASK */
4692     i_errno = IEAFFINITY;
4693     return -1;
4694 #endif /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY nor HAVE_SETPROCESSAFFINITYMASK */
4695 }
4696 
4697 int
4698 iperf_clearaffinity(struct iperf_test *test)
4699 {
4700 #if defined(HAVE_SCHED_SETAFFINITY)
4701     cpu_set_t cpu_set;
4702     int i;
4703 
4704     CPU_ZERO(&cpu_set);
4705     for (i = 0; i < CPU_SETSIZE; ++i)
4706 	CPU_SET(i, &cpu_set);
4707     if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0) {
4708 	i_errno = IEAFFINITY;
4709         return -1;
4710     }
4711     return 0;
4712 #elif defined(HAVE_CPUSET_SETAFFINITY)
4713     if(cpuset_setaffinity(CPU_LEVEL_WHICH,CPU_WHICH_PID, -1,
4714                           sizeof(cpuset_t), &test->cpumask) != 0) {
4715         i_errno = IEAFFINITY;
4716         return -1;
4717     }
4718     return 0;
4719 #elif defined(HAVE_SETPROCESSAFFINITYMASK)
4720 	HANDLE process = GetCurrentProcess();
4721 	DWORD_PTR processAffinityMask;
4722 	DWORD_PTR lpSystemAffinityMask;
4723 
4724 	if (GetProcessAffinityMask(process, &processAffinityMask, &lpSystemAffinityMask) == 0
4725 			|| SetProcessAffinityMask(process, lpSystemAffinityMask) == 0) {
4726 		i_errno = IEAFFINITY;
4727 		return -1;
4728 	}
4729 	return 0;
4730 #else /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY nor HAVE_SETPROCESSAFFINITYMASK */
4731     i_errno = IEAFFINITY;
4732     return -1;
4733 #endif /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY nor HAVE_SETPROCESSAFFINITYMASK */
4734 }
4735 
4736 static char iperf_timestr[100];
4737 static char linebuffer[1024];
4738 
4739 int
4740 iperf_printf(struct iperf_test *test, const char* format, ...)
4741 {
4742     va_list argp;
4743     int r = 0, r0;
4744     time_t now;
4745     struct tm *ltm = NULL;
4746     char *ct = NULL;
4747 
4748     /* Timestamp if requested */
4749     if (iperf_get_test_timestamps(test)) {
4750 	time(&now);
4751 	ltm = localtime(&now);
4752 	strftime(iperf_timestr, sizeof(iperf_timestr), iperf_get_test_timestamp_format(test), ltm);
4753 	ct = iperf_timestr;
4754     }
4755 
4756     /*
4757      * There are roughly two use cases here.  If we're the client,
4758      * want to print stuff directly to the output stream.
4759      * If we're the sender we might need to buffer up output to send
4760      * to the client.
4761      *
4762      * This doesn't make a whole lot of difference except there are
4763      * some chunks of output on the client (on particular the whole
4764      * of the server output with --get-server-output) that could
4765      * easily exceed the size of the line buffer, but which don't need
4766      * to be buffered up anyway.
4767      */
4768     if (test->role == 'c') {
4769 	if (ct) {
4770             r0 = fprintf(test->outfile, "%s", ct);
4771             if (r0 < 0)
4772                 return r0;
4773             r += r0;
4774 	}
4775 	if (test->title) {
4776 	    r0 = fprintf(test->outfile, "%s:  ", test->title);
4777             if (r0 < 0)
4778                 return r0;
4779             r += r0;
4780         }
4781 	va_start(argp, format);
4782 	r0 = vfprintf(test->outfile, format, argp);
4783 	va_end(argp);
4784         if (r0 < 0)
4785             return r0;
4786         r += r0;
4787     }
4788     else if (test->role == 's') {
4789 	if (ct) {
4790 	    r0 = snprintf(linebuffer, sizeof(linebuffer), "%s", ct);
4791             if (r0 < 0)
4792                 return r0;
4793             r += r0;
4794 	}
4795         /* Should always be true as long as sizeof(ct) < sizeof(linebuffer) */
4796         if (r < sizeof(linebuffer)) {
4797             va_start(argp, format);
4798             r0 = vsnprintf(linebuffer + r, sizeof(linebuffer) - r, format, argp);
4799             va_end(argp);
4800             if (r0 < 0)
4801                 return r0;
4802             r += r0;
4803         }
4804 	fprintf(test->outfile, "%s", linebuffer);
4805 
4806 	if (test->role == 's' && iperf_get_test_get_server_output(test)) {
4807 	    struct iperf_textline *l = (struct iperf_textline *) malloc(sizeof(struct iperf_textline));
4808 	    l->line = strdup(linebuffer);
4809 	    TAILQ_INSERT_TAIL(&(test->server_output_list), l, textlineentries);
4810 	}
4811     }
4812     return r;
4813 }
4814 
4815 int
4816 iflush(struct iperf_test *test)
4817 {
4818     return fflush(test->outfile);
4819 }
4820