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