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