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