xref: /iperf/src/iperf_api.c (revision a026b29b)
1 /*
2  * iperf, Copyright (c) 2014-2017, 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 #define _GNU_SOURCE
28 #define __USE_GNU
29 
30 #include "iperf_config.h"
31 
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <getopt.h>
36 #include <errno.h>
37 #include <signal.h>
38 #include <unistd.h>
39 #include <assert.h>
40 #include <fcntl.h>
41 #include <sys/socket.h>
42 #include <sys/types.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #include <netdb.h>
46 #include <pthread.h>
47 #ifdef HAVE_STDINT_H
48 #include <stdint.h>
49 #endif
50 #include <netinet/tcp.h>
51 #include <sys/time.h>
52 #include <sys/resource.h>
53 #include <sys/mman.h>
54 #include <sys/stat.h>
55 #include <sched.h>
56 #include <setjmp.h>
57 #include <stdarg.h>
58 
59 #if defined(HAVE_CPUSET_SETAFFINITY)
60 #include <sys/param.h>
61 #include <sys/cpuset.h>
62 #endif /* HAVE_CPUSET_SETAFFINITY */
63 
64 #include "net.h"
65 #include "iperf.h"
66 #include "iperf_api.h"
67 #include "iperf_udp.h"
68 #include "iperf_tcp.h"
69 #if defined(HAVE_SCTP)
70 #include "iperf_sctp.h"
71 #endif /* HAVE_SCTP */
72 #include "timer.h"
73 
74 #include "cjson.h"
75 #include "units.h"
76 #include "tcp_window_size.h"
77 #include "iperf_util.h"
78 #include "iperf_locale.h"
79 #include "version.h"
80 #if defined(HAVE_SSL)
81 #include "iperf_auth.h"
82 #endif /* HAVE_SSL */
83 
84 /* Forwards. */
85 static int send_parameters(struct iperf_test *test);
86 static int get_parameters(struct iperf_test *test);
87 static int send_results(struct iperf_test *test);
88 static int get_results(struct iperf_test *test);
89 static int diskfile_send(struct iperf_stream *sp);
90 static int diskfile_recv(struct iperf_stream *sp);
91 static int JSON_write(int fd, cJSON *json);
92 static void print_interval_results(struct iperf_test *test, struct iperf_stream *sp, cJSON *json_interval_streams);
93 static cJSON *JSON_read(int fd);
94 
95 
96 /*************************** Print usage functions ****************************/
97 
98 void
99 usage()
100 {
101     fputs(usage_shortstr, stderr);
102 }
103 
104 
105 void
106 usage_long(FILE *f)
107 {
108     fprintf(f, usage_longstr, UDP_RATE / (1024*1024), DURATION, DEFAULT_TCP_BLKSIZE / 1024, DEFAULT_UDP_BLKSIZE / 1024);
109 }
110 
111 
112 void warning(char *str)
113 {
114     fprintf(stderr, "warning: %s\n", str);
115 }
116 
117 
118 /************** Getter routines for some fields inside iperf_test *************/
119 
120 int
121 iperf_get_verbose(struct iperf_test *ipt)
122 {
123     return ipt->verbose;
124 }
125 
126 int
127 iperf_get_control_socket(struct iperf_test *ipt)
128 {
129     return ipt->ctrl_sck;
130 }
131 
132 int
133 iperf_get_control_socket_mss(struct iperf_test *ipt)
134 {
135     return ipt->ctrl_sck_mss;
136 }
137 
138 int
139 iperf_get_test_omit(struct iperf_test *ipt)
140 {
141     return ipt->omit;
142 }
143 
144 int
145 iperf_get_test_duration(struct iperf_test *ipt)
146 {
147     return ipt->duration;
148 }
149 
150 uint64_t
151 iperf_get_test_rate(struct iperf_test *ipt)
152 {
153     return ipt->settings->rate;
154 }
155 
156 uint64_t
157 iperf_get_test_fqrate(struct iperf_test *ipt)
158 {
159     return ipt->settings->fqrate;
160 }
161 
162 int
163 iperf_get_test_burst(struct iperf_test *ipt)
164 {
165     return ipt->settings->burst;
166 }
167 
168 char
169 iperf_get_test_role(struct iperf_test *ipt)
170 {
171     return ipt->role;
172 }
173 
174 int
175 iperf_get_test_reverse(struct iperf_test *ipt)
176 {
177     return ipt->reverse;
178 }
179 
180 int
181 iperf_get_test_blksize(struct iperf_test *ipt)
182 {
183     return ipt->settings->blksize;
184 }
185 
186 FILE *
187 iperf_get_test_outfile (struct iperf_test *ipt)
188 {
189     return ipt->outfile;
190 }
191 
192 int
193 iperf_get_test_socket_bufsize(struct iperf_test *ipt)
194 {
195     return ipt->settings->socket_bufsize;
196 }
197 
198 double
199 iperf_get_test_reporter_interval(struct iperf_test *ipt)
200 {
201     return ipt->reporter_interval;
202 }
203 
204 double
205 iperf_get_test_stats_interval(struct iperf_test *ipt)
206 {
207     return ipt->stats_interval;
208 }
209 
210 int
211 iperf_get_test_num_streams(struct iperf_test *ipt)
212 {
213     return ipt->num_streams;
214 }
215 
216 int
217 iperf_get_test_server_port(struct iperf_test *ipt)
218 {
219     return ipt->server_port;
220 }
221 
222 char*
223 iperf_get_test_server_hostname(struct iperf_test *ipt)
224 {
225     return ipt->server_hostname;
226 }
227 
228 char*
229 iperf_get_test_template(struct iperf_test *ipt)
230 {
231     return ipt->tmp_template;
232 }
233 
234 int
235 iperf_get_test_protocol_id(struct iperf_test *ipt)
236 {
237     return ipt->protocol->id;
238 }
239 
240 int
241 iperf_get_test_json_output(struct iperf_test *ipt)
242 {
243     return ipt->json_output;
244 }
245 
246 char *
247 iperf_get_test_json_output_string(struct iperf_test *ipt)
248 {
249     return ipt->json_output_string;
250 }
251 
252 int
253 iperf_get_test_zerocopy(struct iperf_test *ipt)
254 {
255     return ipt->zerocopy;
256 }
257 
258 int
259 iperf_get_test_get_server_output(struct iperf_test *ipt)
260 {
261     return ipt->get_server_output;
262 }
263 
264 char
265 iperf_get_test_unit_format(struct iperf_test *ipt)
266 {
267     return ipt->settings->unit_format;
268 }
269 
270 char *
271 iperf_get_test_bind_address(struct iperf_test *ipt)
272 {
273     return ipt->bind_address;
274 }
275 
276 int
277 iperf_get_test_udp_counters_64bit(struct iperf_test *ipt)
278 {
279     return ipt->udp_counters_64bit;
280 }
281 
282 int
283 iperf_get_test_one_off(struct iperf_test *ipt)
284 {
285     return ipt->one_off;
286 }
287 
288 /************** Setter routines for some fields inside iperf_test *************/
289 
290 void
291 iperf_set_verbose(struct iperf_test *ipt, int verbose)
292 {
293     ipt->verbose = verbose;
294 }
295 
296 void
297 iperf_set_control_socket(struct iperf_test *ipt, int ctrl_sck)
298 {
299     ipt->ctrl_sck = ctrl_sck;
300 }
301 
302 void
303 iperf_set_test_omit(struct iperf_test *ipt, int omit)
304 {
305     ipt->omit = omit;
306 }
307 
308 void
309 iperf_set_test_duration(struct iperf_test *ipt, int duration)
310 {
311     ipt->duration = duration;
312 }
313 
314 void
315 iperf_set_test_reporter_interval(struct iperf_test *ipt, double reporter_interval)
316 {
317     ipt->reporter_interval = reporter_interval;
318 }
319 
320 void
321 iperf_set_test_stats_interval(struct iperf_test *ipt, double stats_interval)
322 {
323     ipt->stats_interval = stats_interval;
324 }
325 
326 void
327 iperf_set_test_state(struct iperf_test *ipt, signed char state)
328 {
329     ipt->state = state;
330 }
331 
332 void
333 iperf_set_test_blksize(struct iperf_test *ipt, int blksize)
334 {
335     ipt->settings->blksize = blksize;
336 }
337 
338 void
339 iperf_set_test_rate(struct iperf_test *ipt, uint64_t rate)
340 {
341     ipt->settings->rate = rate;
342 }
343 
344 void
345 iperf_set_test_fqrate(struct iperf_test *ipt, uint64_t fqrate)
346 {
347     ipt->settings->fqrate = fqrate;
348 }
349 
350 void
351 iperf_set_test_burst(struct iperf_test *ipt, int burst)
352 {
353     ipt->settings->burst = burst;
354 }
355 
356 void
357 iperf_set_test_server_port(struct iperf_test *ipt, int server_port)
358 {
359     ipt->server_port = server_port;
360 }
361 
362 void
363 iperf_set_test_socket_bufsize(struct iperf_test *ipt, int socket_bufsize)
364 {
365     ipt->settings->socket_bufsize = socket_bufsize;
366 }
367 
368 void
369 iperf_set_test_num_streams(struct iperf_test *ipt, int num_streams)
370 {
371     ipt->num_streams = num_streams;
372 }
373 
374 static void
375 check_sender_has_retransmits(struct iperf_test *ipt)
376 {
377     if (ipt->sender && ipt->protocol->id == Ptcp && has_tcpinfo_retransmits())
378 	ipt->sender_has_retransmits = 1;
379     else
380 	ipt->sender_has_retransmits = 0;
381 }
382 
383 void
384 iperf_set_test_role(struct iperf_test *ipt, char role)
385 {
386     ipt->role = role;
387     if (role == 'c')
388 	ipt->sender = 1;
389     else if (role == 's')
390 	ipt->sender = 0;
391     if (ipt->reverse)
392         ipt->sender = ! ipt->sender;
393     check_sender_has_retransmits(ipt);
394 }
395 
396 void
397 iperf_set_test_server_hostname(struct iperf_test *ipt, char *server_hostname)
398 {
399     ipt->server_hostname = strdup(server_hostname);
400 }
401 
402 void
403 iperf_set_test_template(struct iperf_test *ipt, char *tmp_template)
404 {
405     ipt->tmp_template = strdup(tmp_template);
406 }
407 
408 void
409 iperf_set_test_reverse(struct iperf_test *ipt, int reverse)
410 {
411     ipt->reverse = reverse;
412     if (ipt->reverse)
413         ipt->sender = ! ipt->sender;
414     check_sender_has_retransmits(ipt);
415 }
416 
417 void
418 iperf_set_test_json_output(struct iperf_test *ipt, int json_output)
419 {
420     ipt->json_output = json_output;
421 }
422 
423 int
424 iperf_has_zerocopy( void )
425 {
426     return has_sendfile();
427 }
428 
429 void
430 iperf_set_test_zerocopy(struct iperf_test *ipt, int zerocopy)
431 {
432     ipt->zerocopy = (zerocopy && has_sendfile());
433 }
434 
435 void
436 iperf_set_test_get_server_output(struct iperf_test *ipt, int get_server_output)
437 {
438     ipt->get_server_output = get_server_output;
439 }
440 
441 void
442 iperf_set_test_unit_format(struct iperf_test *ipt, char unit_format)
443 {
444     ipt->settings->unit_format = unit_format;
445 }
446 
447 void
448 iperf_set_test_bind_address(struct iperf_test *ipt, char *bind_address)
449 {
450     ipt->bind_address = strdup(bind_address);
451 }
452 
453 void
454 iperf_set_test_udp_counters_64bit(struct iperf_test *ipt, int udp_counters_64bit)
455 {
456     ipt->udp_counters_64bit = udp_counters_64bit;
457 }
458 
459 void
460 iperf_set_test_one_off(struct iperf_test *ipt, int one_off)
461 {
462     ipt->one_off = one_off;
463 }
464 
465 /********************** Get/set test protocol structure ***********************/
466 
467 struct protocol *
468 get_protocol(struct iperf_test *test, int prot_id)
469 {
470     struct protocol *prot;
471 
472     SLIST_FOREACH(prot, &test->protocols, protocols) {
473         if (prot->id == prot_id)
474             break;
475     }
476 
477     if (prot == NULL)
478         i_errno = IEPROTOCOL;
479 
480     return prot;
481 }
482 
483 int
484 set_protocol(struct iperf_test *test, int prot_id)
485 {
486     struct protocol *prot = NULL;
487 
488     SLIST_FOREACH(prot, &test->protocols, protocols) {
489         if (prot->id == prot_id) {
490             test->protocol = prot;
491 	    check_sender_has_retransmits(test);
492             return 0;
493         }
494     }
495 
496     i_errno = IEPROTOCOL;
497     return -1;
498 }
499 
500 
501 /************************** Iperf callback functions **************************/
502 
503 void
504 iperf_on_new_stream(struct iperf_stream *sp)
505 {
506     connect_msg(sp);
507 }
508 
509 void
510 iperf_on_test_start(struct iperf_test *test)
511 {
512     if (test->json_output) {
513 	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", 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));
514     } else {
515 	if (test->verbose) {
516 	    if (test->settings->bytes)
517 		iperf_printf(test, test_start_bytes, test->protocol->name, test->num_streams, test->settings->blksize, test->omit, test->settings->bytes);
518 	    else if (test->settings->blocks)
519 		iperf_printf(test, test_start_blocks, test->protocol->name, test->num_streams, test->settings->blksize, test->omit, test->settings->blocks);
520 	    else
521 		iperf_printf(test, test_start_time, test->protocol->name, test->num_streams, test->settings->blksize, test->omit, test->duration);
522 	}
523     }
524 }
525 
526 /* This converts an IPv6 string address from IPv4-mapped format into regular
527 ** old IPv4 format, which is easier on the eyes of network veterans.
528 **
529 ** If the v6 address is not v4-mapped it is left alone.
530 */
531 static void
532 mapped_v4_to_regular_v4(char *str)
533 {
534     char *prefix = "::ffff:";
535     int prefix_len;
536 
537     prefix_len = strlen(prefix);
538     if (strncmp(str, prefix, prefix_len) == 0) {
539 	int str_len = strlen(str);
540 	memmove(str, str + prefix_len, str_len - prefix_len + 1);
541     }
542 }
543 
544 void
545 iperf_on_connect(struct iperf_test *test)
546 {
547     time_t now_secs;
548     const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT";
549     char now_str[100];
550     char ipr[INET6_ADDRSTRLEN];
551     int port;
552     struct sockaddr_storage sa;
553     struct sockaddr_in *sa_inP;
554     struct sockaddr_in6 *sa_in6P;
555     socklen_t len;
556 
557     now_secs = time((time_t*) 0);
558     (void) strftime(now_str, sizeof(now_str), rfc1123_fmt, gmtime(&now_secs));
559     if (test->json_output)
560 	cJSON_AddItemToObject(test->json_start, "timestamp", iperf_json_printf("time: %s  timesecs: %d", now_str, (int64_t) now_secs));
561     else if (test->verbose)
562 	iperf_printf(test, report_time, now_str);
563 
564     if (test->role == 'c') {
565 	if (test->json_output)
566 	    cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s  port: %d", test->server_hostname, (int64_t) test->server_port));
567 	else {
568 	    iperf_printf(test, report_connecting, test->server_hostname, test->server_port);
569 	    if (test->reverse)
570 		iperf_printf(test, report_reverse, test->server_hostname);
571 	}
572     } else {
573         len = sizeof(sa);
574         getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len);
575         if (getsockdomain(test->ctrl_sck) == AF_INET) {
576 	    sa_inP = (struct sockaddr_in *) &sa;
577             inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr));
578 	    port = ntohs(sa_inP->sin_port);
579         } else {
580 	    sa_in6P = (struct sockaddr_in6 *) &sa;
581             inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr));
582 	    port = ntohs(sa_in6P->sin6_port);
583         }
584 	mapped_v4_to_regular_v4(ipr);
585 	if (test->json_output)
586 	    cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s  port: %d", ipr, (int64_t) port));
587 	else
588 	    iperf_printf(test, report_accepted, ipr, port);
589     }
590     if (test->json_output) {
591 	cJSON_AddStringToObject(test->json_start, "cookie", test->cookie);
592         if (test->protocol->id == SOCK_STREAM) {
593 	    if (test->settings->mss)
594 		cJSON_AddNumberToObject(test->json_start, "tcp_mss", test->settings->mss);
595 	    else {
596 		cJSON_AddNumberToObject(test->json_start, "tcp_mss_default", test->ctrl_sck_mss);
597 	    }
598 	}
599     } else if (test->verbose) {
600         iperf_printf(test, report_cookie, test->cookie);
601         if (test->protocol->id == SOCK_STREAM) {
602             if (test->settings->mss)
603                 iperf_printf(test, "      TCP MSS: %d\n", test->settings->mss);
604             else {
605                 iperf_printf(test, "      TCP MSS: %d (default)\n", test->ctrl_sck_mss);
606             }
607         }
608 
609     }
610 }
611 
612 void
613 iperf_on_test_finish(struct iperf_test *test)
614 {
615 }
616 
617 
618 /******************************************************************************/
619 
620 int
621 iperf_parse_arguments(struct iperf_test *test, int argc, char **argv)
622 {
623     static struct option longopts[] =
624     {
625         {"port", required_argument, NULL, 'p'},
626         {"format", required_argument, NULL, 'f'},
627         {"interval", required_argument, NULL, 'i'},
628         {"daemon", no_argument, NULL, 'D'},
629         {"one-off", no_argument, NULL, '1'},
630         {"verbose", no_argument, NULL, 'V'},
631         {"json", no_argument, NULL, 'J'},
632         {"version", no_argument, NULL, 'v'},
633         {"server", no_argument, NULL, 's'},
634         {"client", required_argument, NULL, 'c'},
635         {"udp", no_argument, NULL, 'u'},
636         {"bandwidth", required_argument, NULL, 'b'},
637         {"time", required_argument, NULL, 't'},
638         {"bytes", required_argument, NULL, 'n'},
639         {"blockcount", required_argument, NULL, 'k'},
640         {"length", required_argument, NULL, 'l'},
641         {"parallel", required_argument, NULL, 'P'},
642         {"reverse", no_argument, NULL, 'R'},
643         {"window", required_argument, NULL, 'w'},
644         {"bind", required_argument, NULL, 'B'},
645         {"cport", required_argument, NULL, OPT_CLIENT_PORT},
646         {"set-mss", required_argument, NULL, 'M'},
647         {"no-delay", no_argument, NULL, 'N'},
648         {"version4", no_argument, NULL, '4'},
649         {"version6", no_argument, NULL, '6'},
650         {"tos", required_argument, NULL, 'S'},
651         {"dscp", required_argument, NULL, OPT_DSCP},
652 #if defined(HAVE_FLOWLABEL)
653         {"flowlabel", required_argument, NULL, 'L'},
654 #endif /* HAVE_FLOWLABEL */
655         {"zerocopy", no_argument, NULL, 'Z'},
656         {"omit", required_argument, NULL, 'O'},
657         {"file", required_argument, NULL, 'F'},
658 #if defined(HAVE_CPU_AFFINITY)
659         {"affinity", required_argument, NULL, 'A'},
660 #endif /* HAVE_CPU_AFFINITY */
661         {"title", required_argument, NULL, 'T'},
662 #if defined(HAVE_TCP_CONGESTION)
663         {"congestion", required_argument, NULL, 'C'},
664         {"linux-congestion", required_argument, NULL, 'C'},
665 #endif /* HAVE_TCP_CONGESTION */
666 #if defined(HAVE_SCTP)
667         {"sctp", no_argument, NULL, OPT_SCTP},
668         {"nstreams", required_argument, NULL, OPT_NUMSTREAMS},
669         {"xbind", required_argument, NULL, 'X'},
670 #endif
671 	{"pidfile", required_argument, NULL, 'I'},
672 	{"logfile", required_argument, NULL, OPT_LOGFILE},
673 	{"forceflush", no_argument, NULL, OPT_FORCEFLUSH},
674 	{"get-server-output", no_argument, NULL, OPT_GET_SERVER_OUTPUT},
675 	{"udp-counters-64bit", no_argument, NULL, OPT_UDP_COUNTERS_64BIT},
676  	{"no-fq-socket-pacing", no_argument, NULL, OPT_NO_FQ_SOCKET_PACING},
677 #if defined(HAVE_SSL)
678     {"username", required_argument, NULL, OPT_CLIENT_USERNAME},
679     {"rsa-public-key-path", required_argument, NULL, OPT_CLIENT_RSA_PUBLIC_KEY},
680     {"rsa-private-key-path", required_argument, NULL, OPT_SERVER_RSA_PRIVATE_KEY},
681     {"authorized-users-path", required_argument, NULL, OPT_SERVER_AUTHORIZED_USERS},
682 #endif /* HAVE_SSL */
683 	{"fq-rate", required_argument, NULL, OPT_FQ_RATE},
684         {"debug", no_argument, NULL, 'd'},
685         {"help", no_argument, NULL, 'h'},
686         {NULL, 0, NULL, 0}
687     };
688     int flag;
689     int blksize;
690     int server_flag, client_flag, rate_flag, duration_flag;
691     char *endptr;
692 #if defined(HAVE_CPU_AFFINITY)
693     char* comma;
694 #endif /* HAVE_CPU_AFFINITY */
695     char* slash;
696     struct xbind_entry *xbe;
697 
698     blksize = 0;
699     server_flag = client_flag = rate_flag = duration_flag = 0;
700 #if defined(HAVE_SSL)
701     char *client_username = NULL, *client_rsa_public_key = NULL;
702 #endif /* HAVE_SSL */
703 
704     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) {
705         switch (flag) {
706             case 'p':
707                 test->server_port = atoi(optarg);
708                 break;
709             case 'f':
710                 test->settings->unit_format = *optarg;
711                 break;
712             case 'i':
713                 /* XXX: could potentially want separate stat collection and reporting intervals,
714                    but just set them to be the same for now */
715                 test->stats_interval = test->reporter_interval = atof(optarg);
716                 if ((test->stats_interval < MIN_INTERVAL || test->stats_interval > MAX_INTERVAL) && test->stats_interval != 0) {
717                     i_errno = IEINTERVAL;
718                     return -1;
719                 }
720                 break;
721             case 'D':
722 		test->daemon = 1;
723 		server_flag = 1;
724 	        break;
725             case '1':
726 		test->one_off = 1;
727 		server_flag = 1;
728 	        break;
729             case 'V':
730                 test->verbose = 1;
731                 break;
732             case 'J':
733                 test->json_output = 1;
734                 break;
735             case 'v':
736                 printf("%s\n%s\n%s\n", version, get_system_info(),
737 		       get_optional_features());
738                 exit(0);
739             case 's':
740                 if (test->role == 'c') {
741                     i_errno = IESERVCLIENT;
742                     return -1;
743                 }
744 		iperf_set_test_role(test, 's');
745                 break;
746             case 'c':
747                 if (test->role == 's') {
748                     i_errno = IESERVCLIENT;
749                     return -1;
750                 }
751 		iperf_set_test_role(test, 'c');
752 		iperf_set_test_server_hostname(test, optarg);
753                 break;
754             case 'u':
755                 set_protocol(test, Pudp);
756 		client_flag = 1;
757                 break;
758             case OPT_SCTP:
759 #if defined(HAVE_SCTP)
760                 set_protocol(test, Psctp);
761                 client_flag = 1;
762 #else /* HAVE_SCTP */
763                 i_errno = IEUNIMP;
764                 return -1;
765 #endif /* HAVE_SCTP */
766             break;
767 
768             case OPT_NUMSTREAMS:
769 #if defined(linux) || defined(__FreeBSD__)
770                 test->settings->num_ostreams = unit_atoi(optarg);
771                 client_flag = 1;
772 #else /* linux */
773                 i_errno = IEUNIMP;
774                 return -1;
775 #endif /* linux */
776             case 'b':
777 		slash = strchr(optarg, '/');
778 		if (slash) {
779 		    *slash = '\0';
780 		    ++slash;
781 		    test->settings->burst = atoi(slash);
782 		    if (test->settings->burst <= 0 ||
783 		        test->settings->burst > MAX_BURST) {
784 			i_errno = IEBURST;
785 			return -1;
786 		    }
787 		}
788                 test->settings->rate = unit_atof_rate(optarg);
789 		rate_flag = 1;
790 		client_flag = 1;
791                 break;
792             case 't':
793                 test->duration = atoi(optarg);
794                 if (test->duration > MAX_TIME) {
795                     i_errno = IEDURATION;
796                     return -1;
797                 }
798 		duration_flag = 1;
799 		client_flag = 1;
800                 break;
801             case 'n':
802                 test->settings->bytes = unit_atoi(optarg);
803 		client_flag = 1;
804                 break;
805             case 'k':
806                 test->settings->blocks = unit_atoi(optarg);
807 		client_flag = 1;
808                 break;
809             case 'l':
810                 blksize = unit_atoi(optarg);
811 		client_flag = 1;
812                 break;
813             case 'P':
814                 test->num_streams = atoi(optarg);
815                 if (test->num_streams > MAX_STREAMS) {
816                     i_errno = IENUMSTREAMS;
817                     return -1;
818                 }
819 		client_flag = 1;
820                 break;
821             case 'R':
822 		iperf_set_test_reverse(test, 1);
823 		client_flag = 1;
824                 break;
825             case 'w':
826                 // XXX: This is a socket buffer, not specific to TCP
827                 test->settings->socket_bufsize = unit_atof(optarg);
828                 if (test->settings->socket_bufsize > MAX_TCP_BUFFER) {
829                     i_errno = IEBUFSIZE;
830                     return -1;
831                 }
832 		client_flag = 1;
833                 break;
834             case 'B':
835                 test->bind_address = strdup(optarg);
836                 break;
837             case OPT_CLIENT_PORT:
838                 test->bind_port = atoi(optarg);
839                 break;
840             case 'M':
841                 test->settings->mss = atoi(optarg);
842                 if (test->settings->mss > MAX_MSS) {
843                     i_errno = IEMSS;
844                     return -1;
845                 }
846 		client_flag = 1;
847                 break;
848             case 'N':
849                 test->no_delay = 1;
850 		client_flag = 1;
851                 break;
852             case '4':
853                 test->settings->domain = AF_INET;
854                 break;
855             case '6':
856                 test->settings->domain = AF_INET6;
857                 break;
858             case 'S':
859                 test->settings->tos = strtol(optarg, &endptr, 0);
860 		if (endptr == optarg ||
861 		    test->settings->tos < 0 ||
862 		    test->settings->tos > 255) {
863 		    i_errno = IEBADTOS;
864 		    return -1;
865 		}
866 		client_flag = 1;
867                 break;
868 	    case OPT_DSCP:
869                 test->settings->tos = parse_qos(optarg);
870 		if(test->settings->tos < 0) {
871 			i_errno = IEBADTOS;
872 			return -1;
873 		}
874 		client_flag = 1;
875                 break;
876             case 'L':
877 #if defined(HAVE_FLOWLABEL)
878                 test->settings->flowlabel = strtol(optarg, &endptr, 0);
879 		if (endptr == optarg ||
880 		    test->settings->flowlabel < 1 || test->settings->flowlabel > 0xfffff) {
881                     i_errno = IESETFLOW;
882                     return -1;
883 		}
884 		client_flag = 1;
885 #else /* HAVE_FLOWLABEL */
886                 i_errno = IEUNIMP;
887                 return -1;
888 #endif /* HAVE_FLOWLABEL */
889                 break;
890             case 'X':
891 		xbe = (struct xbind_entry *)malloc(sizeof(struct xbind_entry));
892                 if (!xbe) {
893 		    i_errno = IESETSCTPBINDX;
894                     return -1;
895                 }
896 	        memset(xbe, 0, sizeof(*xbe));
897                 xbe->name = strdup(optarg);
898                 if (!xbe->name) {
899 		    i_errno = IESETSCTPBINDX;
900                     return -1;
901                 }
902 		TAILQ_INSERT_TAIL(&test->xbind_addrs, xbe, link);
903                 break;
904             case 'Z':
905                 if (!has_sendfile()) {
906                     i_errno = IENOSENDFILE;
907                     return -1;
908                 }
909                 test->zerocopy = 1;
910 		client_flag = 1;
911                 break;
912             case 'O':
913                 test->omit = atoi(optarg);
914                 if (test->omit < 0 || test->omit > 60) {
915                     i_errno = IEOMIT;
916                     return -1;
917                 }
918 		client_flag = 1;
919                 break;
920             case 'F':
921                 test->diskfile_name = optarg;
922                 break;
923             case 'A':
924 #if defined(HAVE_CPU_AFFINITY)
925                 test->affinity = strtol(optarg, &endptr, 0);
926                 if (endptr == optarg ||
927 		    test->affinity < 0 || test->affinity > 1024) {
928                     i_errno = IEAFFINITY;
929                     return -1;
930                 }
931 		comma = strchr(optarg, ',');
932 		if (comma != NULL) {
933 		    test->server_affinity = atoi(comma+1);
934 		    if (test->server_affinity < 0 || test->server_affinity > 1024) {
935 			i_errno = IEAFFINITY;
936 			return -1;
937 		    }
938 		    client_flag = 1;
939 		}
940 #else /* HAVE_CPU_AFFINITY */
941                 i_errno = IEUNIMP;
942                 return -1;
943 #endif /* HAVE_CPU_AFFINITY */
944                 break;
945             case 'T':
946                 test->title = strdup(optarg);
947 		client_flag = 1;
948                 break;
949 	    case 'C':
950 #if defined(HAVE_TCP_CONGESTION)
951 		test->congestion = strdup(optarg);
952 		client_flag = 1;
953 #else /* HAVE_TCP_CONGESTION */
954 		i_errno = IEUNIMP;
955 		return -1;
956 #endif /* HAVE_TCP_CONGESTION */
957 		break;
958 	    case 'd':
959 		test->debug = 1;
960 		break;
961 	    case 'I':
962 		test->pidfile = strdup(optarg);
963 		server_flag = 1;
964 	        break;
965 	    case OPT_LOGFILE:
966 		test->logfile = strdup(optarg);
967 		break;
968 	    case OPT_FORCEFLUSH:
969 		test->forceflush = 1;
970 		break;
971 	    case OPT_GET_SERVER_OUTPUT:
972 		test->get_server_output = 1;
973 		client_flag = 1;
974 		break;
975 	    case OPT_UDP_COUNTERS_64BIT:
976 		test->udp_counters_64bit = 1;
977 		break;
978 	    case OPT_NO_FQ_SOCKET_PACING:
979 #if defined(HAVE_SO_MAX_PACING_RATE)
980 		printf("Warning:  --no-fq-socket-pacing is deprecated\n");
981 		test->settings->fqrate = 0;
982 		client_flag = 1;
983 #else /* HAVE_SO_MAX_PACING_RATE */
984 		i_errno = IEUNIMP;
985 		return -1;
986 #endif
987 		break;
988 	    case OPT_FQ_RATE:
989 #if defined(HAVE_SO_MAX_PACING_RATE)
990 		test->settings->fqrate = unit_atof_rate(optarg);
991 		client_flag = 1;
992 #else /* HAVE_SO_MAX_PACING_RATE */
993 		i_errno = IEUNIMP;
994 		return -1;
995 #endif
996 		break;
997 #if defined(HAVE_SSL)
998         case OPT_CLIENT_USERNAME:
999             client_username = strdup(optarg);
1000             break;
1001         case OPT_CLIENT_RSA_PUBLIC_KEY:
1002             client_rsa_public_key = strdup(optarg);
1003             break;
1004         case OPT_SERVER_RSA_PRIVATE_KEY:
1005             test->server_rsa_private_key = strdup(optarg);
1006             break;
1007         case OPT_SERVER_AUTHORIZED_USERS:
1008             test->server_authorized_users = strdup(optarg);
1009             break;
1010 #endif /* HAVE_SSL */
1011             case 'h':
1012 		usage_long(stdout);
1013 		exit(0);
1014             default:
1015                 usage_long(stderr);
1016                 exit(1);
1017         }
1018     }
1019 
1020     /* Set logging to a file if specified, otherwise use the default (stdout) */
1021     if (test->logfile) {
1022         test->outfile = fopen(test->logfile, "a+");
1023         if (test->outfile == NULL) {
1024             i_errno = IELOGFILE;
1025             return -1;
1026         }
1027     }
1028 
1029     /* Check flag / role compatibility. */
1030     if (test->role == 'c' && server_flag) {
1031         i_errno = IESERVERONLY;
1032         return -1;
1033     }
1034     if (test->role == 's' && client_flag) {
1035         i_errno = IECLIENTONLY;
1036         return -1;
1037     }
1038 
1039 #if defined(HAVE_SSL)
1040 
1041     if (test->role == 's' && (client_username || client_rsa_public_key)){
1042         i_errno = IECLIENTONLY;
1043         return -1;
1044     } else if (test->role == 'c' && (client_username || client_rsa_public_key) &&
1045         !(client_username && client_rsa_public_key)) {
1046         i_errno = IESETCLIENTAUTH;
1047         return -1;
1048     } else if (test->role == 'c' && (client_username && client_rsa_public_key)){
1049 
1050         char *client_password = NULL;
1051         size_t s;
1052         if (iperf_getpass(&client_password, &s, stdin) < 0){
1053             return -1;
1054         }
1055 
1056         if (strlen(client_username) > 20 || strlen(client_password) > 20){
1057             i_errno = IESETCLIENTAUTH;
1058             return -1;
1059         }
1060 
1061         if (test_load_pubkey(client_rsa_public_key) < 0){
1062             i_errno = IESETCLIENTAUTH;
1063             return -1;
1064         }
1065         encode_auth_setting(client_username, client_password, client_rsa_public_key, &test->settings->authtoken);
1066     }
1067 
1068     if (test->role == 'c' && (test->server_rsa_private_key || test->server_authorized_users)){
1069         i_errno = IESERVERONLY;
1070         return -1;
1071     } else if (test->role == 's' && (test->server_rsa_private_key || test->server_authorized_users) &&
1072         !(test->server_rsa_private_key && test->server_authorized_users)) {
1073          i_errno = IESETSERVERAUTH;
1074         return -1;
1075     } else if (test->role == 's' && test->server_rsa_private_key && test_load_private_key(test->server_rsa_private_key) < 0){
1076         i_errno = IESETSERVERAUTH;
1077         return -1;
1078     }
1079 #endif //HAVE_SSL
1080     if (!test->bind_address && test->bind_port) {
1081         i_errno = IEBIND;
1082         return -1;
1083     }
1084     if (blksize == 0) {
1085 	if (test->protocol->id == Pudp)
1086 	    blksize = 0;	/* try to dynamically determine from MSS */
1087 	else if (test->protocol->id == Psctp)
1088 	    blksize = DEFAULT_SCTP_BLKSIZE;
1089 	else
1090 	    blksize = DEFAULT_TCP_BLKSIZE;
1091     }
1092     if ((test->protocol->id != Pudp && blksize <= 0)
1093 	|| blksize > MAX_BLOCKSIZE) {
1094 	i_errno = IEBLOCKSIZE;
1095 	return -1;
1096     }
1097     if (test->protocol->id == Pudp &&
1098 	(blksize < MIN_UDP_BLOCKSIZE || blksize > MAX_UDP_BLOCKSIZE)) {
1099 	i_errno = IEUDPBLOCKSIZE;
1100 	return -1;
1101     }
1102     test->settings->blksize = blksize;
1103 
1104     if (!rate_flag)
1105 	test->settings->rate = test->protocol->id == Pudp ? UDP_RATE : 0;
1106 
1107     if ((test->settings->bytes != 0 || test->settings->blocks != 0) && ! duration_flag)
1108         test->duration = 0;
1109 
1110     /* Disallow specifying multiple test end conditions. The code actually
1111     ** works just fine without this prohibition. As soon as any one of the
1112     ** three possible end conditions is met, the test ends. So this check
1113     ** could be removed if desired.
1114     */
1115     if ((duration_flag && test->settings->bytes != 0) ||
1116         (duration_flag && test->settings->blocks != 0) ||
1117 	(test->settings->bytes != 0 && test->settings->blocks != 0)) {
1118         i_errno = IEENDCONDITIONS;
1119         return -1;
1120     }
1121 
1122     /* For subsequent calls to getopt */
1123 #ifdef __APPLE__
1124     optreset = 1;
1125 #endif
1126     optind = 0;
1127 
1128     if ((test->role != 'c') && (test->role != 's')) {
1129         i_errno = IENOROLE;
1130         return -1;
1131     }
1132 
1133     return 0;
1134 }
1135 
1136 int
1137 iperf_set_send_state(struct iperf_test *test, signed char state)
1138 {
1139     test->state = state;
1140     if (Nwrite(test->ctrl_sck, (char*) &state, sizeof(state), Ptcp) < 0) {
1141 	i_errno = IESENDMESSAGE;
1142 	return -1;
1143     }
1144     return 0;
1145 }
1146 
1147 void
1148 iperf_check_throttle(struct iperf_stream *sp, struct timeval *nowP)
1149 {
1150     double seconds;
1151     uint64_t bits_per_second;
1152 
1153     if (sp->test->done)
1154         return;
1155     seconds = timeval_diff(&sp->result->start_time_fixed, nowP);
1156     bits_per_second = sp->result->bytes_sent * 8 / seconds;
1157     if (bits_per_second < sp->test->settings->rate) {
1158         sp->green_light = 1;
1159         FD_SET(sp->socket, &sp->test->write_set);
1160     } else {
1161         sp->green_light = 0;
1162         FD_CLR(sp->socket, &sp->test->write_set);
1163     }
1164 }
1165 
1166 int
1167 iperf_send(struct iperf_test *test, fd_set *write_setP)
1168 {
1169     register int multisend, r, streams_active;
1170     register struct iperf_stream *sp;
1171     struct timeval now;
1172 
1173     /* Can we do multisend mode? */
1174     if (test->settings->burst != 0)
1175         multisend = test->settings->burst;
1176     else if (test->settings->rate == 0)
1177         multisend = test->multisend;
1178     else
1179         multisend = 1;	/* nope */
1180 
1181     for (; multisend > 0; --multisend) {
1182 	if (test->settings->rate != 0 && test->settings->burst == 0)
1183 	    gettimeofday(&now, NULL);
1184 	streams_active = 0;
1185 	SLIST_FOREACH(sp, &test->streams, streams) {
1186 	    if ((sp->green_light &&
1187 		 (write_setP == NULL || FD_ISSET(sp->socket, write_setP)))) {
1188 		if ((r = sp->snd(sp)) < 0) {
1189 		    if (r == NET_SOFTERROR)
1190 			break;
1191 		    i_errno = IESTREAMWRITE;
1192 		    return r;
1193 		}
1194 		streams_active = 1;
1195 		test->bytes_sent += r;
1196 		++test->blocks_sent;
1197 		if (test->settings->rate != 0 && test->settings->burst == 0)
1198 		    iperf_check_throttle(sp, &now);
1199 		if (multisend > 1 && test->settings->bytes != 0 && test->bytes_sent >= test->settings->bytes)
1200 		    break;
1201 		if (multisend > 1 && test->settings->blocks != 0 && test->blocks_sent >= test->settings->blocks)
1202 		    break;
1203 	    }
1204 	}
1205 	if (!streams_active)
1206 	    break;
1207     }
1208     if (test->settings->burst != 0) {
1209 	gettimeofday(&now, NULL);
1210 	SLIST_FOREACH(sp, &test->streams, streams)
1211 	    iperf_check_throttle(sp, &now);
1212     }
1213     if (write_setP != NULL)
1214 	SLIST_FOREACH(sp, &test->streams, streams)
1215 	    if (FD_ISSET(sp->socket, write_setP))
1216 		FD_CLR(sp->socket, write_setP);
1217 
1218     return 0;
1219 }
1220 
1221 int
1222 iperf_recv(struct iperf_test *test, fd_set *read_setP)
1223 {
1224     int r;
1225     struct iperf_stream *sp;
1226 
1227     SLIST_FOREACH(sp, &test->streams, streams) {
1228 	if (FD_ISSET(sp->socket, read_setP)) {
1229 	    if ((r = sp->rcv(sp)) < 0) {
1230 		i_errno = IESTREAMREAD;
1231 		return r;
1232 	    }
1233 	    test->bytes_sent += r;
1234 	    ++test->blocks_sent;
1235 	    FD_CLR(sp->socket, read_setP);
1236 	}
1237     }
1238 
1239     return 0;
1240 }
1241 
1242 int
1243 iperf_init_test(struct iperf_test *test)
1244 {
1245     struct timeval now;
1246     struct iperf_stream *sp;
1247 
1248     if (test->protocol->init) {
1249         if (test->protocol->init(test) < 0)
1250             return -1;
1251     }
1252 
1253     /* Init each stream. */
1254     if (gettimeofday(&now, NULL) < 0) {
1255 	i_errno = IEINITTEST;
1256 	return -1;
1257     }
1258     SLIST_FOREACH(sp, &test->streams, streams) {
1259 	sp->result->start_time = sp->result->start_time_fixed = now;
1260     }
1261 
1262     if (test->on_test_start)
1263         test->on_test_start(test);
1264 
1265     return 0;
1266 }
1267 
1268 static void
1269 send_timer_proc(TimerClientData client_data, struct timeval *nowP)
1270 {
1271     struct iperf_stream *sp = client_data.p;
1272 
1273     /* All we do here is set or clear the flag saying that this stream may
1274     ** be sent to.  The actual sending gets done in the send proc, after
1275     ** checking the flag.
1276     */
1277     iperf_check_throttle(sp, nowP);
1278 }
1279 
1280 int
1281 iperf_create_send_timers(struct iperf_test * test)
1282 {
1283     struct timeval now;
1284     struct iperf_stream *sp;
1285     TimerClientData cd;
1286 
1287     if (gettimeofday(&now, NULL) < 0) {
1288 	i_errno = IEINITTEST;
1289 	return -1;
1290     }
1291     SLIST_FOREACH(sp, &test->streams, streams) {
1292         sp->green_light = 1;
1293 	if (test->settings->rate != 0) {
1294 	    cd.p = sp;
1295 	    /* (Repeat every millisecond - arbitrary value to provide smooth pacing.) */
1296 	    sp->send_timer = tmr_create((struct timeval*) 0, send_timer_proc, cd, 1000L, 1);
1297 	    if (sp->send_timer == NULL) {
1298 		i_errno = IEINITTEST;
1299 		return -1;
1300 	    }
1301 	}
1302     }
1303     return 0;
1304 }
1305 
1306 #if defined(HAVE_SSL)
1307 int test_is_authorized(struct iperf_test *test){
1308     if ( !(test->server_rsa_private_key && test->server_authorized_users)) {
1309         return 0;
1310     }
1311 
1312     if (test->settings->authtoken){
1313         char *username = NULL, *password = NULL;
1314         time_t ts;
1315         decode_auth_setting(test->debug, test->settings->authtoken, test->server_rsa_private_key, &username, &password, &ts);
1316         int ret = check_authentication(username, password, ts, test->server_authorized_users);
1317         if (ret == 0){
1318             iperf_printf(test, report_authetication_successed, username, ts);
1319             return 0;
1320         } else {
1321             iperf_printf(test, report_authetication_failed, username, ts);
1322             return -1;
1323         }
1324     }
1325     return -1;
1326 }
1327 #endif //HAVE_SSL
1328 
1329 /**
1330  * iperf_exchange_parameters - handles the param_Exchange part for client
1331  *
1332  */
1333 
1334 int
1335 iperf_exchange_parameters(struct iperf_test *test)
1336 {
1337     int s;
1338     int32_t err;
1339 
1340     if (test->role == 'c') {
1341 
1342         if (send_parameters(test) < 0)
1343             return -1;
1344 
1345     } else {
1346 
1347         if (get_parameters(test) < 0)
1348             return -1;
1349 
1350 #if defined(HAVE_SSL)
1351         if (test_is_authorized(test) < 0){
1352             if (iperf_set_send_state(test, SERVER_ERROR) != 0)
1353                 return -1;
1354             i_errno = IEAUTHTEST;
1355             err = htonl(i_errno);
1356             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
1357                 i_errno = IECTRLWRITE;
1358                 return -1;
1359             }
1360             return -1;
1361         }
1362 #endif //HAVE_SSL
1363 
1364         if ((s = test->protocol->listen(test)) < 0) {
1365 	        if (iperf_set_send_state(test, SERVER_ERROR) != 0)
1366                 return -1;
1367             err = htonl(i_errno);
1368             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
1369                 i_errno = IECTRLWRITE;
1370                 return -1;
1371             }
1372             err = htonl(errno);
1373             if (Nwrite(test->ctrl_sck, (char*) &err, sizeof(err), Ptcp) < 0) {
1374                 i_errno = IECTRLWRITE;
1375                 return -1;
1376             }
1377             return -1;
1378         }
1379         FD_SET(s, &test->read_set);
1380         test->max_fd = (s > test->max_fd) ? s : test->max_fd;
1381         test->prot_listener = s;
1382 
1383         // Send the control message to create streams and start the test
1384 	if (iperf_set_send_state(test, CREATE_STREAMS) != 0)
1385             return -1;
1386 
1387     }
1388 
1389     return 0;
1390 }
1391 
1392 /*************************************************************/
1393 
1394 int
1395 iperf_exchange_results(struct iperf_test *test)
1396 {
1397     if (test->role == 'c') {
1398         /* Send results to server. */
1399 	if (send_results(test) < 0)
1400             return -1;
1401         /* Get server results. */
1402         if (get_results(test) < 0)
1403             return -1;
1404     } else {
1405         /* Get client results. */
1406         if (get_results(test) < 0)
1407             return -1;
1408         /* Send results to client. */
1409 	if (send_results(test) < 0)
1410             return -1;
1411     }
1412     return 0;
1413 }
1414 
1415 /*************************************************************/
1416 
1417 static int
1418 send_parameters(struct iperf_test *test)
1419 {
1420     int r = 0;
1421     cJSON *j;
1422 
1423     j = cJSON_CreateObject();
1424     if (j == NULL) {
1425 	i_errno = IESENDPARAMS;
1426 	r = -1;
1427     } else {
1428 	if (test->protocol->id == Ptcp)
1429 	    cJSON_AddTrueToObject(j, "tcp");
1430 	else if (test->protocol->id == Pudp)
1431 	    cJSON_AddTrueToObject(j, "udp");
1432         else if (test->protocol->id == Psctp)
1433             cJSON_AddTrueToObject(j, "sctp");
1434 	cJSON_AddNumberToObject(j, "omit", test->omit);
1435 	if (test->server_affinity != -1)
1436 	    cJSON_AddNumberToObject(j, "server_affinity", test->server_affinity);
1437 	if (test->duration)
1438 	    cJSON_AddNumberToObject(j, "time", test->duration);
1439 	if (test->settings->bytes)
1440 	    cJSON_AddNumberToObject(j, "num", test->settings->bytes);
1441 	if (test->settings->blocks)
1442 	    cJSON_AddNumberToObject(j, "blockcount", test->settings->blocks);
1443 	if (test->settings->mss)
1444 	    cJSON_AddNumberToObject(j, "MSS", test->settings->mss);
1445 	if (test->no_delay)
1446 	    cJSON_AddTrueToObject(j, "nodelay");
1447 	cJSON_AddNumberToObject(j, "parallel", test->num_streams);
1448 	if (test->reverse)
1449 	    cJSON_AddTrueToObject(j, "reverse");
1450 	if (test->settings->socket_bufsize)
1451 	    cJSON_AddNumberToObject(j, "window", test->settings->socket_bufsize);
1452 	if (test->settings->blksize)
1453 	    cJSON_AddNumberToObject(j, "len", test->settings->blksize);
1454 	if (test->settings->rate)
1455 	    cJSON_AddNumberToObject(j, "bandwidth", test->settings->rate);
1456 	if (test->settings->fqrate)
1457 	    cJSON_AddNumberToObject(j, "fqrate", test->settings->fqrate);
1458 	if (test->settings->burst)
1459 	    cJSON_AddNumberToObject(j, "burst", test->settings->burst);
1460 	if (test->settings->tos)
1461 	    cJSON_AddNumberToObject(j, "TOS", test->settings->tos);
1462 	if (test->settings->flowlabel)
1463 	    cJSON_AddNumberToObject(j, "flowlabel", test->settings->flowlabel);
1464 	if (test->title)
1465 	    cJSON_AddStringToObject(j, "title", test->title);
1466 	if (test->congestion)
1467 	    cJSON_AddStringToObject(j, "congestion", test->congestion);
1468 	if (test->congestion_used)
1469 	    cJSON_AddStringToObject(j, "congestion_used", test->congestion_used);
1470 	if (test->get_server_output)
1471 	    cJSON_AddNumberToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
1472 	if (test->udp_counters_64bit)
1473 	    cJSON_AddNumberToObject(j, "udp_counters_64bit", iperf_get_test_udp_counters_64bit(test));
1474 #if defined(HAVE_SSL)
1475     if (test->settings->authtoken)
1476         cJSON_AddStringToObject(j, "authtoken", test->settings->authtoken);
1477 #endif // HAVE_SSL
1478 	cJSON_AddStringToObject(j, "client_version", IPERF_VERSION);
1479 
1480 	if (test->debug) {
1481 	    printf("send_parameters:\n%s\n", cJSON_Print(j));
1482 	}
1483 
1484 	if (JSON_write(test->ctrl_sck, j) < 0) {
1485 	    i_errno = IESENDPARAMS;
1486 	    r = -1;
1487 	}
1488 	cJSON_Delete(j);
1489     }
1490     return r;
1491 }
1492 
1493 /*************************************************************/
1494 
1495 static int
1496 get_parameters(struct iperf_test *test)
1497 {
1498     int r = 0;
1499     cJSON *j;
1500     cJSON *j_p;
1501 
1502     j = JSON_read(test->ctrl_sck);
1503     if (j == NULL) {
1504 	i_errno = IERECVPARAMS;
1505         r = -1;
1506     } else {
1507 	if (test->debug) {
1508 	    printf("get_parameters:\n%s\n", cJSON_Print(j));
1509 	}
1510 
1511 	if ((j_p = cJSON_GetObjectItem(j, "tcp")) != NULL)
1512 	    set_protocol(test, Ptcp);
1513 	if ((j_p = cJSON_GetObjectItem(j, "udp")) != NULL)
1514 	    set_protocol(test, Pudp);
1515         if ((j_p = cJSON_GetObjectItem(j, "sctp")) != NULL)
1516             set_protocol(test, Psctp);
1517 	if ((j_p = cJSON_GetObjectItem(j, "omit")) != NULL)
1518 	    test->omit = j_p->valueint;
1519 	if ((j_p = cJSON_GetObjectItem(j, "server_affinity")) != NULL)
1520 	    test->server_affinity = j_p->valueint;
1521 	if ((j_p = cJSON_GetObjectItem(j, "time")) != NULL)
1522 	    test->duration = j_p->valueint;
1523 	if ((j_p = cJSON_GetObjectItem(j, "num")) != NULL)
1524 	    test->settings->bytes = j_p->valueint;
1525 	if ((j_p = cJSON_GetObjectItem(j, "blockcount")) != NULL)
1526 	    test->settings->blocks = j_p->valueint;
1527 	if ((j_p = cJSON_GetObjectItem(j, "MSS")) != NULL)
1528 	    test->settings->mss = j_p->valueint;
1529 	if ((j_p = cJSON_GetObjectItem(j, "nodelay")) != NULL)
1530 	    test->no_delay = 1;
1531 	if ((j_p = cJSON_GetObjectItem(j, "parallel")) != NULL)
1532 	    test->num_streams = j_p->valueint;
1533 	if ((j_p = cJSON_GetObjectItem(j, "reverse")) != NULL)
1534 	    iperf_set_test_reverse(test, 1);
1535 	if ((j_p = cJSON_GetObjectItem(j, "window")) != NULL)
1536 	    test->settings->socket_bufsize = j_p->valueint;
1537 	if ((j_p = cJSON_GetObjectItem(j, "len")) != NULL)
1538 	    test->settings->blksize = j_p->valueint;
1539 	if ((j_p = cJSON_GetObjectItem(j, "bandwidth")) != NULL)
1540 	    test->settings->rate = j_p->valueint;
1541 	if ((j_p = cJSON_GetObjectItem(j, "fqrate")) != NULL)
1542 	    test->settings->fqrate = j_p->valueint;
1543 	if ((j_p = cJSON_GetObjectItem(j, "burst")) != NULL)
1544 	    test->settings->burst = j_p->valueint;
1545 	if ((j_p = cJSON_GetObjectItem(j, "TOS")) != NULL)
1546 	    test->settings->tos = j_p->valueint;
1547 	if ((j_p = cJSON_GetObjectItem(j, "flowlabel")) != NULL)
1548 	    test->settings->flowlabel = j_p->valueint;
1549 	if ((j_p = cJSON_GetObjectItem(j, "title")) != NULL)
1550 	    test->title = strdup(j_p->valuestring);
1551 	if ((j_p = cJSON_GetObjectItem(j, "congestion")) != NULL)
1552 	    test->congestion = strdup(j_p->valuestring);
1553 	if ((j_p = cJSON_GetObjectItem(j, "congestion_used")) != NULL)
1554 	    test->congestion_used = strdup(j_p->valuestring);
1555 	if ((j_p = cJSON_GetObjectItem(j, "get_server_output")) != NULL)
1556 	    iperf_set_test_get_server_output(test, 1);
1557 	if ((j_p = cJSON_GetObjectItem(j, "udp_counters_64bit")) != NULL)
1558 	    iperf_set_test_udp_counters_64bit(test, 1);
1559 #if defined(HAVE_SSL)
1560 	if ((j_p = cJSON_GetObjectItem(j, "authtoken")) != NULL)
1561         test->settings->authtoken = strdup(j_p->valuestring);
1562 #endif //HAVE_SSL
1563 	if (test->sender && test->protocol->id == Ptcp && has_tcpinfo_retransmits())
1564 	    test->sender_has_retransmits = 1;
1565 	cJSON_Delete(j);
1566     }
1567     return r;
1568 }
1569 
1570 /*************************************************************/
1571 
1572 static int
1573 send_results(struct iperf_test *test)
1574 {
1575     int r = 0;
1576     cJSON *j;
1577     cJSON *j_streams;
1578     struct iperf_stream *sp;
1579     cJSON *j_stream;
1580     int sender_has_retransmits;
1581     iperf_size_t bytes_transferred;
1582     int retransmits;
1583 
1584     j = cJSON_CreateObject();
1585     if (j == NULL) {
1586 	i_errno = IEPACKAGERESULTS;
1587 	r = -1;
1588     } else {
1589 	cJSON_AddNumberToObject(j, "cpu_util_total", test->cpu_util[0]);
1590 	cJSON_AddNumberToObject(j, "cpu_util_user", test->cpu_util[1]);
1591 	cJSON_AddNumberToObject(j, "cpu_util_system", test->cpu_util[2]);
1592 	if ( ! test->sender )
1593 	    sender_has_retransmits = -1;
1594 	else
1595 	    sender_has_retransmits = test->sender_has_retransmits;
1596 	cJSON_AddNumberToObject(j, "sender_has_retransmits", sender_has_retransmits);
1597 	if ( test->congestion_used ) {
1598 	    cJSON_AddStringToObject(j, "congestion_used", test->congestion_used);
1599 	}
1600 
1601 	/* If on the server and sending server output, then do this */
1602 	if (test->role == 's' && test->get_server_output) {
1603 	    if (test->json_output) {
1604 		/* Add JSON output */
1605 		cJSON_AddItemReferenceToObject(j, "server_output_json", test->json_top);
1606 	    }
1607 	    else {
1608 		/* Add textual output */
1609 		size_t buflen = 0;
1610 
1611 		/* Figure out how much room we need to hold the complete output string */
1612 		struct iperf_textline *t;
1613 		TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
1614 		    buflen += strlen(t->line);
1615 		}
1616 
1617 		/* Allocate and build it up from the component lines */
1618 		char *output = calloc(buflen + 1, 1);
1619 		TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) {
1620 		    strncat(output, t->line, buflen);
1621 		    buflen -= strlen(t->line);
1622 		}
1623 
1624 		cJSON_AddStringToObject(j, "server_output_text", output);
1625 	    }
1626 	}
1627 
1628 	j_streams = cJSON_CreateArray();
1629 	if (j_streams == NULL) {
1630 	    i_errno = IEPACKAGERESULTS;
1631 	    r = -1;
1632 	} else {
1633 	    cJSON_AddItemToObject(j, "streams", j_streams);
1634 	    SLIST_FOREACH(sp, &test->streams, streams) {
1635 		j_stream = cJSON_CreateObject();
1636 		if (j_stream == NULL) {
1637 		    i_errno = IEPACKAGERESULTS;
1638 		    r = -1;
1639 		} else {
1640 		    cJSON_AddItemToArray(j_streams, j_stream);
1641 		    bytes_transferred = test->sender ? (sp->result->bytes_sent - sp->result->bytes_sent_omit) : sp->result->bytes_received;
1642 		    retransmits = (test->sender && test->sender_has_retransmits) ? sp->result->stream_retrans : -1;
1643 		    cJSON_AddNumberToObject(j_stream, "id", sp->id);
1644 		    cJSON_AddNumberToObject(j_stream, "bytes", bytes_transferred);
1645 		    cJSON_AddNumberToObject(j_stream, "retransmits", retransmits);
1646 		    cJSON_AddNumberToObject(j_stream, "jitter", sp->jitter);
1647 		    cJSON_AddNumberToObject(j_stream, "errors", sp->cnt_error);
1648 		    cJSON_AddNumberToObject(j_stream, "packets", sp->packet_count);
1649 		}
1650 	    }
1651 	    if (r == 0 && test->debug) {
1652 		printf("send_results\n%s\n", cJSON_Print(j));
1653 	    }
1654 	    if (r == 0 && JSON_write(test->ctrl_sck, j) < 0) {
1655 		i_errno = IESENDRESULTS;
1656 		r = -1;
1657 	    }
1658 	}
1659 	cJSON_Delete(j);
1660     }
1661     return r;
1662 }
1663 
1664 /*************************************************************/
1665 
1666 static int
1667 get_results(struct iperf_test *test)
1668 {
1669     int r = 0;
1670     cJSON *j;
1671     cJSON *j_cpu_util_total;
1672     cJSON *j_cpu_util_user;
1673     cJSON *j_cpu_util_system;
1674     cJSON *j_remote_congestion_used;
1675     cJSON *j_sender_has_retransmits;
1676     int result_has_retransmits;
1677     cJSON *j_streams;
1678     int n, i;
1679     cJSON *j_stream;
1680     cJSON *j_id;
1681     cJSON *j_bytes;
1682     cJSON *j_retransmits;
1683     cJSON *j_jitter;
1684     cJSON *j_errors;
1685     cJSON *j_packets;
1686     cJSON *j_server_output;
1687     int sid, cerror, pcount;
1688     double jitter;
1689     iperf_size_t bytes_transferred;
1690     int retransmits;
1691     struct iperf_stream *sp;
1692 
1693     j = JSON_read(test->ctrl_sck);
1694     if (j == NULL) {
1695 	i_errno = IERECVRESULTS;
1696         r = -1;
1697     } else {
1698 	j_cpu_util_total = cJSON_GetObjectItem(j, "cpu_util_total");
1699 	j_cpu_util_user = cJSON_GetObjectItem(j, "cpu_util_user");
1700 	j_cpu_util_system = cJSON_GetObjectItem(j, "cpu_util_system");
1701 	j_sender_has_retransmits = cJSON_GetObjectItem(j, "sender_has_retransmits");
1702 	if (j_cpu_util_total == NULL || j_cpu_util_user == NULL || j_cpu_util_system == NULL || j_sender_has_retransmits == NULL) {
1703 	    i_errno = IERECVRESULTS;
1704 	    r = -1;
1705 	} else {
1706 	    if (test->debug) {
1707 		printf("get_results\n%s\n", cJSON_Print(j));
1708 	    }
1709 
1710 	    test->remote_cpu_util[0] = j_cpu_util_total->valuedouble;
1711 	    test->remote_cpu_util[1] = j_cpu_util_user->valuedouble;
1712 	    test->remote_cpu_util[2] = j_cpu_util_system->valuedouble;
1713 	    result_has_retransmits = j_sender_has_retransmits->valueint;
1714 	    if (! test->sender)
1715 		test->sender_has_retransmits = result_has_retransmits;
1716 	    j_streams = cJSON_GetObjectItem(j, "streams");
1717 	    if (j_streams == NULL) {
1718 		i_errno = IERECVRESULTS;
1719 		r = -1;
1720 	    } else {
1721 	        n = cJSON_GetArraySize(j_streams);
1722 		for (i=0; i<n; ++i) {
1723 		    j_stream = cJSON_GetArrayItem(j_streams, i);
1724 		    if (j_stream == NULL) {
1725 			i_errno = IERECVRESULTS;
1726 			r = -1;
1727 		    } else {
1728 			j_id = cJSON_GetObjectItem(j_stream, "id");
1729 			j_bytes = cJSON_GetObjectItem(j_stream, "bytes");
1730 			j_retransmits = cJSON_GetObjectItem(j_stream, "retransmits");
1731 			j_jitter = cJSON_GetObjectItem(j_stream, "jitter");
1732 			j_errors = cJSON_GetObjectItem(j_stream, "errors");
1733 			j_packets = cJSON_GetObjectItem(j_stream, "packets");
1734 			if (j_id == NULL || j_bytes == NULL || j_retransmits == NULL || j_jitter == NULL || j_errors == NULL || j_packets == NULL) {
1735 			    i_errno = IERECVRESULTS;
1736 			    r = -1;
1737 			} else {
1738 			    sid = j_id->valueint;
1739 			    bytes_transferred = j_bytes->valueint;
1740 			    retransmits = j_retransmits->valueint;
1741 			    jitter = j_jitter->valuedouble;
1742 			    cerror = j_errors->valueint;
1743 			    pcount = j_packets->valueint;
1744 			    SLIST_FOREACH(sp, &test->streams, streams)
1745 				if (sp->id == sid) break;
1746 			    if (sp == NULL) {
1747 				i_errno = IESTREAMID;
1748 				r = -1;
1749 			    } else {
1750 				if (test->sender) {
1751 				    sp->jitter = jitter;
1752 				    sp->cnt_error = cerror;
1753 				    sp->packet_count = pcount;
1754 				    sp->result->bytes_received = bytes_transferred;
1755 				} else {
1756 				    sp->result->bytes_sent = bytes_transferred;
1757 				    sp->result->stream_retrans = retransmits;
1758 				}
1759 			    }
1760 			}
1761 		    }
1762 		}
1763 		/*
1764 		 * If we're the client and we're supposed to get remote results,
1765 		 * look them up and process accordingly.
1766 		 */
1767 		if (test->role == 'c' && iperf_get_test_get_server_output(test)) {
1768 		    /* Look for JSON.  If we find it, grab the object so it doesn't get deleted. */
1769 		    j_server_output = cJSON_DetachItemFromObject(j, "server_output_json");
1770 		    if (j_server_output != NULL) {
1771 			test->json_server_output = j_server_output;
1772 		    }
1773 		    else {
1774 			/* No JSON, look for textual output.  Make a copy of the text for later. */
1775 			j_server_output = cJSON_GetObjectItem(j, "server_output_text");
1776 			if (j_server_output != NULL) {
1777 			    test->server_output_text = strdup(j_server_output->valuestring);
1778 			}
1779 		    }
1780 		}
1781 	    }
1782 	}
1783 
1784 	j_remote_congestion_used = cJSON_GetObjectItem(j, "congestion_used");
1785 	if (j_remote_congestion_used != NULL) {
1786 	    test->remote_congestion_used = strdup(j_remote_congestion_used->valuestring);
1787 	}
1788 
1789 	cJSON_Delete(j);
1790     }
1791     return r;
1792 }
1793 
1794 /*************************************************************/
1795 
1796 static int
1797 JSON_write(int fd, cJSON *json)
1798 {
1799     uint32_t hsize, nsize;
1800     char *str;
1801     int r = 0;
1802 
1803     str = cJSON_PrintUnformatted(json);
1804     if (str == NULL)
1805 	r = -1;
1806     else {
1807 	hsize = strlen(str);
1808 	nsize = htonl(hsize);
1809 	if (Nwrite(fd, (char*) &nsize, sizeof(nsize), Ptcp) < 0)
1810 	    r = -1;
1811 	else {
1812 	    if (Nwrite(fd, str, hsize, Ptcp) < 0)
1813 		r = -1;
1814 	}
1815 	free(str);
1816     }
1817     return r;
1818 }
1819 
1820 /*************************************************************/
1821 
1822 static cJSON *
1823 JSON_read(int fd)
1824 {
1825     uint32_t hsize, nsize;
1826     char *str;
1827     cJSON *json = NULL;
1828     int rc;
1829 
1830     /*
1831      * Read a four-byte integer, which is the length of the JSON to follow.
1832      * Then read the JSON into a buffer and parse it.  Return a parsed JSON
1833      * structure, NULL if there was an error.
1834      */
1835     if (Nread(fd, (char*) &nsize, sizeof(nsize), Ptcp) >= 0) {
1836 	hsize = ntohl(nsize);
1837 	/* Allocate a buffer to hold the JSON */
1838 	str = (char *) calloc(sizeof(char), hsize+1);	/* +1 for trailing null */
1839 	if (str != NULL) {
1840 	    rc = Nread(fd, str, hsize, Ptcp);
1841 	    if (rc >= 0) {
1842 		/*
1843 		 * We should be reading in the number of bytes corresponding to the
1844 		 * length in that 4-byte integer.  If we don't the socket might have
1845 		 * prematurely closed.  Only do the JSON parsing if we got the
1846 		 * correct number of bytes.
1847 		 */
1848 		if (rc == hsize) {
1849 		    json = cJSON_Parse(str);
1850 		}
1851 		else {
1852 		    printf("WARNING:  Size of data read does not correspond to offered length\n");
1853 		}
1854 	    }
1855 	}
1856 	free(str);
1857     }
1858     return json;
1859 }
1860 
1861 /*************************************************************/
1862 /**
1863  * add_to_interval_list -- adds new interval to the interval_list
1864  */
1865 
1866 void
1867 add_to_interval_list(struct iperf_stream_result * rp, struct iperf_interval_results * new)
1868 {
1869     struct iperf_interval_results *irp;
1870 
1871     irp = (struct iperf_interval_results *) malloc(sizeof(struct iperf_interval_results));
1872     memcpy(irp, new, sizeof(struct iperf_interval_results));
1873     TAILQ_INSERT_TAIL(&rp->interval_results, irp, irlistentries);
1874 }
1875 
1876 
1877 /************************************************************/
1878 
1879 /**
1880  * connect_msg -- displays connection message
1881  * denoting sender/receiver details
1882  *
1883  */
1884 
1885 void
1886 connect_msg(struct iperf_stream *sp)
1887 {
1888     char ipl[INET6_ADDRSTRLEN], ipr[INET6_ADDRSTRLEN];
1889     int lport, rport;
1890 
1891     if (getsockdomain(sp->socket) == AF_INET) {
1892         inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->local_addr)->sin_addr, ipl, sizeof(ipl));
1893 	mapped_v4_to_regular_v4(ipl);
1894         inet_ntop(AF_INET, (void *) &((struct sockaddr_in *) &sp->remote_addr)->sin_addr, ipr, sizeof(ipr));
1895 	mapped_v4_to_regular_v4(ipr);
1896         lport = ntohs(((struct sockaddr_in *) &sp->local_addr)->sin_port);
1897         rport = ntohs(((struct sockaddr_in *) &sp->remote_addr)->sin_port);
1898     } else {
1899         inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->local_addr)->sin6_addr, ipl, sizeof(ipl));
1900 	mapped_v4_to_regular_v4(ipl);
1901         inet_ntop(AF_INET6, (void *) &((struct sockaddr_in6 *) &sp->remote_addr)->sin6_addr, ipr, sizeof(ipr));
1902 	mapped_v4_to_regular_v4(ipr);
1903         lport = ntohs(((struct sockaddr_in6 *) &sp->local_addr)->sin6_port);
1904         rport = ntohs(((struct sockaddr_in6 *) &sp->remote_addr)->sin6_port);
1905     }
1906 
1907     if (sp->test->json_output)
1908         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));
1909     else
1910 	iperf_printf(sp->test, report_connected, sp->socket, ipl, lport, ipr, rport);
1911 }
1912 
1913 
1914 /**************************************************************************/
1915 
1916 struct iperf_test *
1917 iperf_new_test()
1918 {
1919     struct iperf_test *test;
1920 
1921     test = (struct iperf_test *) malloc(sizeof(struct iperf_test));
1922     if (!test) {
1923         i_errno = IENEWTEST;
1924         return NULL;
1925     }
1926     /* initialize everything to zero */
1927     memset(test, 0, sizeof(struct iperf_test));
1928 
1929     test->settings = (struct iperf_settings *) malloc(sizeof(struct iperf_settings));
1930     if (!test->settings) {
1931         free(test);
1932 	i_errno = IENEWTEST;
1933 	return NULL;
1934     }
1935     memset(test->settings, 0, sizeof(struct iperf_settings));
1936 
1937     /* By default all output goes to stdout */
1938     test->outfile = stdout;
1939 
1940     return test;
1941 }
1942 
1943 /**************************************************************************/
1944 
1945 struct protocol *
1946 protocol_new(void)
1947 {
1948     struct protocol *proto;
1949 
1950     proto = malloc(sizeof(struct protocol));
1951     if(!proto) {
1952         return NULL;
1953     }
1954     memset(proto, 0, sizeof(struct protocol));
1955 
1956     return proto;
1957 }
1958 
1959 void
1960 protocol_free(struct protocol *proto)
1961 {
1962     free(proto);
1963 }
1964 
1965 /**************************************************************************/
1966 int
1967 iperf_defaults(struct iperf_test *testp)
1968 {
1969     struct protocol *tcp, *udp;
1970 #if defined(HAVE_SCTP)
1971     struct protocol *sctp;
1972 #endif /* HAVE_SCTP */
1973 
1974     testp->omit = OMIT;
1975     testp->duration = DURATION;
1976     testp->diskfile_name = (char*) 0;
1977     testp->affinity = -1;
1978     testp->server_affinity = -1;
1979     TAILQ_INIT(&testp->xbind_addrs);
1980 #if defined(HAVE_CPUSET_SETAFFINITY)
1981     CPU_ZERO(&testp->cpumask);
1982 #endif /* HAVE_CPUSET_SETAFFINITY */
1983     testp->title = NULL;
1984     testp->congestion = NULL;
1985     testp->congestion_used = NULL;
1986     testp->remote_congestion_used = NULL;
1987     testp->server_port = PORT;
1988     testp->ctrl_sck = -1;
1989     testp->prot_listener = -1;
1990 
1991     testp->stats_callback = iperf_stats_callback;
1992     testp->reporter_callback = iperf_reporter_callback;
1993 
1994     testp->stats_interval = testp->reporter_interval = 1;
1995     testp->num_streams = 1;
1996 
1997     testp->settings->domain = AF_UNSPEC;
1998     testp->settings->unit_format = 'a';
1999     testp->settings->socket_bufsize = 0;    /* use autotuning */
2000     testp->settings->blksize = DEFAULT_TCP_BLKSIZE;
2001     testp->settings->rate = 0;
2002     testp->settings->fqrate = 0;
2003     testp->settings->burst = 0;
2004     testp->settings->mss = 0;
2005     testp->settings->bytes = 0;
2006     testp->settings->blocks = 0;
2007     memset(testp->cookie, 0, COOKIE_SIZE);
2008 
2009     testp->multisend = 10;	/* arbitrary */
2010 
2011     /* Set up protocol list */
2012     SLIST_INIT(&testp->streams);
2013     SLIST_INIT(&testp->protocols);
2014 
2015     tcp = protocol_new();
2016     if (!tcp)
2017         return -1;
2018 
2019     tcp->id = Ptcp;
2020     tcp->name = "TCP";
2021     tcp->accept = iperf_tcp_accept;
2022     tcp->listen = iperf_tcp_listen;
2023     tcp->connect = iperf_tcp_connect;
2024     tcp->send = iperf_tcp_send;
2025     tcp->recv = iperf_tcp_recv;
2026     tcp->init = NULL;
2027     SLIST_INSERT_HEAD(&testp->protocols, tcp, protocols);
2028 
2029     udp = protocol_new();
2030     if (!udp) {
2031         protocol_free(tcp);
2032         return -1;
2033     }
2034 
2035     udp->id = Pudp;
2036     udp->name = "UDP";
2037     udp->accept = iperf_udp_accept;
2038     udp->listen = iperf_udp_listen;
2039     udp->connect = iperf_udp_connect;
2040     udp->send = iperf_udp_send;
2041     udp->recv = iperf_udp_recv;
2042     udp->init = iperf_udp_init;
2043     SLIST_INSERT_AFTER(tcp, udp, protocols);
2044 
2045     set_protocol(testp, Ptcp);
2046 
2047 #if defined(HAVE_SCTP)
2048     sctp = protocol_new();
2049     if (!sctp) {
2050         protocol_free(tcp);
2051         protocol_free(udp);
2052         return -1;
2053     }
2054 
2055     sctp->id = Psctp;
2056     sctp->name = "SCTP";
2057     sctp->accept = iperf_sctp_accept;
2058     sctp->listen = iperf_sctp_listen;
2059     sctp->connect = iperf_sctp_connect;
2060     sctp->send = iperf_sctp_send;
2061     sctp->recv = iperf_sctp_recv;
2062     sctp->init = iperf_sctp_init;
2063 
2064     SLIST_INSERT_AFTER(udp, sctp, protocols);
2065 #endif /* HAVE_SCTP */
2066 
2067     testp->on_new_stream = iperf_on_new_stream;
2068     testp->on_test_start = iperf_on_test_start;
2069     testp->on_connect = iperf_on_connect;
2070     testp->on_test_finish = iperf_on_test_finish;
2071 
2072     TAILQ_INIT(&testp->server_output_list);
2073 
2074     return 0;
2075 }
2076 
2077 
2078 /**************************************************************************/
2079 void
2080 iperf_free_test(struct iperf_test *test)
2081 {
2082     struct protocol *prot;
2083     struct iperf_stream *sp;
2084 
2085     /* Free streams */
2086     while (!SLIST_EMPTY(&test->streams)) {
2087         sp = SLIST_FIRST(&test->streams);
2088         SLIST_REMOVE_HEAD(&test->streams, streams);
2089         iperf_free_stream(sp);
2090     }
2091 
2092     if (test->server_hostname)
2093 	free(test->server_hostname);
2094     if (test->tmp_template)
2095 	free(test->tmp_template);
2096     if (test->bind_address)
2097 	free(test->bind_address);
2098     if (!TAILQ_EMPTY(&test->xbind_addrs)) {
2099         struct xbind_entry *xbe;
2100 
2101         while (!TAILQ_EMPTY(&test->xbind_addrs)) {
2102             xbe = TAILQ_FIRST(&test->xbind_addrs);
2103             TAILQ_REMOVE(&test->xbind_addrs, xbe, link);
2104             if (xbe->ai)
2105                 freeaddrinfo(xbe->ai);
2106             free(xbe->name);
2107             free(xbe);
2108         }
2109     }
2110     if (test->settings)
2111     free(test->settings);
2112     if (test->title)
2113 	free(test->title);
2114     if (test->congestion)
2115 	free(test->congestion);
2116     if (test->congestion_used)
2117 	free(test->congestion_used);
2118     if (test->remote_congestion_used)
2119 	free(test->remote_congestion_used);
2120     if (test->omit_timer != NULL)
2121 	tmr_cancel(test->omit_timer);
2122     if (test->timer != NULL)
2123 	tmr_cancel(test->timer);
2124     if (test->stats_timer != NULL)
2125 	tmr_cancel(test->stats_timer);
2126     if (test->reporter_timer != NULL)
2127 	tmr_cancel(test->reporter_timer);
2128 
2129     /* Free protocol list */
2130     while (!SLIST_EMPTY(&test->protocols)) {
2131         prot = SLIST_FIRST(&test->protocols);
2132         SLIST_REMOVE_HEAD(&test->protocols, protocols);
2133         free(prot);
2134     }
2135 
2136     if (test->server_output_text) {
2137 	free(test->server_output_text);
2138 	test->server_output_text = NULL;
2139     }
2140 
2141     if (test->json_output_string) {
2142 	free(test->json_output_string);
2143 	test->json_output_string = NULL;
2144     }
2145 
2146     /* Free output line buffers, if any (on the server only) */
2147     struct iperf_textline *t;
2148     while (!TAILQ_EMPTY(&test->server_output_list)) {
2149 	t = TAILQ_FIRST(&test->server_output_list);
2150 	TAILQ_REMOVE(&test->server_output_list, t, textlineentries);
2151 	free(t->line);
2152 	free(t);
2153     }
2154 
2155     /* sctp_bindx: do not free the arguments, only the resolver results */
2156     if (!TAILQ_EMPTY(&test->xbind_addrs)) {
2157         struct xbind_entry *xbe;
2158 
2159         TAILQ_FOREACH(xbe, &test->xbind_addrs, link) {
2160             if (xbe->ai) {
2161                 freeaddrinfo(xbe->ai);
2162                 xbe->ai = NULL;
2163             }
2164         }
2165     }
2166 
2167     /* XXX: Why are we setting these values to NULL? */
2168     // test->streams = NULL;
2169     test->stats_callback = NULL;
2170     test->reporter_callback = NULL;
2171     free(test);
2172 }
2173 
2174 
2175 void
2176 iperf_reset_test(struct iperf_test *test)
2177 {
2178     struct iperf_stream *sp;
2179 
2180     /* Free streams */
2181     while (!SLIST_EMPTY(&test->streams)) {
2182         sp = SLIST_FIRST(&test->streams);
2183         SLIST_REMOVE_HEAD(&test->streams, streams);
2184         iperf_free_stream(sp);
2185     }
2186     if (test->omit_timer != NULL) {
2187 	tmr_cancel(test->omit_timer);
2188 	test->omit_timer = NULL;
2189     }
2190     if (test->timer != NULL) {
2191 	tmr_cancel(test->timer);
2192 	test->timer = NULL;
2193     }
2194     if (test->stats_timer != NULL) {
2195 	tmr_cancel(test->stats_timer);
2196 	test->stats_timer = NULL;
2197     }
2198     if (test->reporter_timer != NULL) {
2199 	tmr_cancel(test->reporter_timer);
2200 	test->reporter_timer = NULL;
2201     }
2202     test->done = 0;
2203 
2204     SLIST_INIT(&test->streams);
2205 
2206     test->role = 's';
2207     test->sender = 0;
2208     test->sender_has_retransmits = 0;
2209     set_protocol(test, Ptcp);
2210     test->omit = OMIT;
2211     test->duration = DURATION;
2212     test->server_affinity = -1;
2213 #if defined(HAVE_CPUSET_SETAFFINITY)
2214     CPU_ZERO(&test->cpumask);
2215 #endif /* HAVE_CPUSET_SETAFFINITY */
2216     test->state = 0;
2217 
2218     test->ctrl_sck = -1;
2219     test->prot_listener = -1;
2220 
2221     test->bytes_sent = 0;
2222     test->blocks_sent = 0;
2223 
2224     test->reverse = 0;
2225     test->no_delay = 0;
2226 
2227     FD_ZERO(&test->read_set);
2228     FD_ZERO(&test->write_set);
2229 
2230     test->num_streams = 1;
2231     test->settings->socket_bufsize = 0;
2232     test->settings->blksize = DEFAULT_TCP_BLKSIZE;
2233     test->settings->rate = 0;
2234     test->settings->burst = 0;
2235     test->settings->mss = 0;
2236     memset(test->cookie, 0, COOKIE_SIZE);
2237     test->multisend = 10;	/* arbitrary */
2238     test->udp_counters_64bit = 0;
2239     if (test->title) {
2240 	free(test->title);
2241 	test->title = NULL;
2242     }
2243 
2244     /* Free output line buffers, if any (on the server only) */
2245     struct iperf_textline *t;
2246     while (!TAILQ_EMPTY(&test->server_output_list)) {
2247 	t = TAILQ_FIRST(&test->server_output_list);
2248 	TAILQ_REMOVE(&test->server_output_list, t, textlineentries);
2249 	free(t->line);
2250 	free(t);
2251     }
2252 }
2253 
2254 
2255 /* Reset all of a test's stats back to zero.  Called when the omitting
2256 ** period is over.
2257 */
2258 void
2259 iperf_reset_stats(struct iperf_test *test)
2260 {
2261     struct timeval now;
2262     struct iperf_stream *sp;
2263     struct iperf_stream_result *rp;
2264 
2265     test->bytes_sent = 0;
2266     test->blocks_sent = 0;
2267     gettimeofday(&now, NULL);
2268     SLIST_FOREACH(sp, &test->streams, streams) {
2269 	sp->omitted_packet_count = sp->packet_count;
2270         sp->omitted_cnt_error = sp->cnt_error;
2271         sp->omitted_outoforder_packets = sp->outoforder_packets;
2272 	sp->jitter = 0;
2273 	rp = sp->result;
2274         rp->bytes_sent_omit = rp->bytes_sent;
2275         rp->bytes_received = 0;
2276         rp->bytes_sent_this_interval = rp->bytes_received_this_interval = 0;
2277 	if (test->sender && test->sender_has_retransmits) {
2278 	    struct iperf_interval_results ir; /* temporary results structure */
2279 	    save_tcpinfo(sp, &ir);
2280 	    rp->stream_prev_total_retrans = get_total_retransmits(&ir);
2281 	}
2282 	rp->stream_retrans = 0;
2283 	rp->start_time = now;
2284     }
2285 }
2286 
2287 
2288 /**************************************************************************/
2289 
2290 /**
2291  * Gather statistics during a test.
2292  * This function works for both the client and server side.
2293  */
2294 void
2295 iperf_stats_callback(struct iperf_test *test)
2296 {
2297     struct iperf_stream *sp;
2298     struct iperf_stream_result *rp = NULL;
2299     struct iperf_interval_results *irp, temp;
2300 
2301     temp.omitted = test->omitting;
2302     SLIST_FOREACH(sp, &test->streams, streams) {
2303         rp = sp->result;
2304 
2305 	temp.bytes_transferred = test->sender ? rp->bytes_sent_this_interval : rp->bytes_received_this_interval;
2306 
2307 	irp = TAILQ_LAST(&rp->interval_results, irlisthead);
2308         /* result->end_time contains timestamp of previous interval */
2309         if ( irp != NULL ) /* not the 1st interval */
2310             memcpy(&temp.interval_start_time, &rp->end_time, sizeof(struct timeval));
2311         else /* or use timestamp from beginning */
2312             memcpy(&temp.interval_start_time, &rp->start_time, sizeof(struct timeval));
2313         /* now save time of end of this interval */
2314         gettimeofday(&rp->end_time, NULL);
2315         memcpy(&temp.interval_end_time, &rp->end_time, sizeof(struct timeval));
2316         temp.interval_duration = timeval_diff(&temp.interval_start_time, &temp.interval_end_time);
2317         //temp.interval_duration = timeval_diff(&temp.interval_start_time, &temp.interval_end_time);
2318 	if (test->protocol->id == Ptcp) {
2319 	    if ( has_tcpinfo()) {
2320 		save_tcpinfo(sp, &temp);
2321 		if (test->sender && test->sender_has_retransmits) {
2322 		    long total_retrans = get_total_retransmits(&temp);
2323 		    temp.interval_retrans = total_retrans - rp->stream_prev_total_retrans;
2324 		    rp->stream_retrans += temp.interval_retrans;
2325 		    rp->stream_prev_total_retrans = total_retrans;
2326 
2327 		    temp.snd_cwnd = get_snd_cwnd(&temp);
2328 		    if (temp.snd_cwnd > rp->stream_max_snd_cwnd) {
2329 			rp->stream_max_snd_cwnd = temp.snd_cwnd;
2330 		    }
2331 
2332 		    temp.rtt = get_rtt(&temp);
2333 		    if (temp.rtt > rp->stream_max_rtt) {
2334 			rp->stream_max_rtt = temp.rtt;
2335 		    }
2336 		    if (rp->stream_min_rtt == 0 ||
2337 			temp.rtt < rp->stream_min_rtt) {
2338 			rp->stream_min_rtt = temp.rtt;
2339 		    }
2340 		    rp->stream_sum_rtt += temp.rtt;
2341 		    rp->stream_count_rtt++;
2342 
2343 		    temp.rttvar = get_rttvar(&temp);
2344 		}
2345 	    }
2346 	} else {
2347 	    if (irp == NULL) {
2348 		temp.interval_packet_count = sp->packet_count;
2349 		temp.interval_outoforder_packets = sp->outoforder_packets;
2350 		temp.interval_cnt_error = sp->cnt_error;
2351 	    } else {
2352 		temp.interval_packet_count = sp->packet_count - irp->packet_count;
2353 		temp.interval_outoforder_packets = sp->outoforder_packets - irp->outoforder_packets;
2354 		temp.interval_cnt_error = sp->cnt_error - irp->cnt_error;
2355 	    }
2356 	    temp.packet_count = sp->packet_count;
2357 	    temp.jitter = sp->jitter;
2358 	    temp.outoforder_packets = sp->outoforder_packets;
2359 	    temp.cnt_error = sp->cnt_error;
2360 	}
2361         add_to_interval_list(rp, &temp);
2362         rp->bytes_sent_this_interval = rp->bytes_received_this_interval = 0;
2363     }
2364 }
2365 
2366 /**
2367  * Print intermediate results during a test (interval report).
2368  * Uses print_interval_results to print the results for each stream,
2369  * then prints an interval summary for all streams in this
2370  * interval.
2371  */
2372 static void
2373 iperf_print_intermediate(struct iperf_test *test)
2374 {
2375     char ubuf[UNIT_LEN];
2376     char nbuf[UNIT_LEN];
2377     struct iperf_stream *sp = NULL;
2378     struct iperf_interval_results *irp;
2379     iperf_size_t bytes = 0;
2380     double bandwidth;
2381     int retransmits = 0;
2382     double start_time, end_time;
2383     cJSON *json_interval;
2384     cJSON *json_interval_streams;
2385     int total_packets = 0, lost_packets = 0;
2386     double avg_jitter = 0.0, lost_percent;
2387 
2388     if (test->json_output) {
2389         json_interval = cJSON_CreateObject();
2390 	if (json_interval == NULL)
2391 	    return;
2392 	cJSON_AddItemToArray(test->json_intervals, json_interval);
2393         json_interval_streams = cJSON_CreateArray();
2394 	if (json_interval_streams == NULL)
2395 	    return;
2396 	cJSON_AddItemToObject(json_interval, "streams", json_interval_streams);
2397     } else {
2398         json_interval = NULL;
2399         json_interval_streams = NULL;
2400     }
2401 
2402     SLIST_FOREACH(sp, &test->streams, streams) {
2403         print_interval_results(test, sp, json_interval_streams);
2404 	/* sum up all streams */
2405 	irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);
2406 	if (irp == NULL) {
2407 	    iperf_err(test, "iperf_print_intermediate error: interval_results is NULL");
2408 	    return;
2409 	}
2410         bytes += irp->bytes_transferred;
2411 	if (test->protocol->id == Ptcp) {
2412 	    if (test->sender && test->sender_has_retransmits) {
2413 		retransmits += irp->interval_retrans;
2414 	    }
2415 	} else {
2416             total_packets += irp->interval_packet_count;
2417             lost_packets += irp->interval_cnt_error;
2418             avg_jitter += irp->jitter;
2419 	}
2420     }
2421 
2422     /* next build string with sum of all streams */
2423     if (test->num_streams > 1 || test->json_output) {
2424         sp = SLIST_FIRST(&test->streams); /* reset back to 1st stream */
2425 	/* Only do this of course if there was a first stream */
2426 	if (sp) {
2427         irp = TAILQ_LAST(&sp->result->interval_results, irlisthead);    /* use 1st stream for timing info */
2428 
2429         unit_snprintf(ubuf, UNIT_LEN, (double) bytes, 'A');
2430 	bandwidth = (double) bytes / (double) irp->interval_duration;
2431         unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2432 
2433         start_time = timeval_diff(&sp->result->start_time,&irp->interval_start_time);
2434         end_time = timeval_diff(&sp->result->start_time,&irp->interval_end_time);
2435 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2436 	    if (test->sender && test->sender_has_retransmits) {
2437 		/* Interval sum, TCP with retransmits. */
2438 		if (test->json_output)
2439 		    cJSON_AddItemToObject(json_interval, "sum", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  retransmits: %d  omitted: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, (int64_t) retransmits, irp->omitted)); /* XXX irp->omitted or test->omitting? */
2440 		else
2441 		    iperf_printf(test, report_sum_bw_retrans_format, start_time, end_time, ubuf, nbuf, retransmits, irp->omitted?report_omitted:""); /* XXX irp->omitted or test->omitting? */
2442 	    } else {
2443 		/* Interval sum, TCP without retransmits. */
2444 		if (test->json_output)
2445 		    cJSON_AddItemToObject(json_interval, "sum", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  omitted: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, test->omitting));
2446 		else
2447 		    iperf_printf(test, report_sum_bw_format, start_time, end_time, ubuf, nbuf, test->omitting?report_omitted:"");
2448 	    }
2449 	} else {
2450 	    /* Interval sum, UDP. */
2451 	    if (test->sender) {
2452 		if (test->json_output)
2453 		    cJSON_AddItemToObject(json_interval, "sum", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  packets: %d  omitted: %b", (double) start_time, (double) end_time, (double) irp->interval_duration, (int64_t) bytes, bandwidth * 8, (int64_t) total_packets, test->omitting));
2454 		else
2455 		    iperf_printf(test, report_sum_bw_udp_sender_format, start_time, end_time, ubuf, nbuf, total_packets, test->omitting?report_omitted:"");
2456 	    } else {
2457 		avg_jitter /= test->num_streams;
2458 		if (total_packets > 0) {
2459 		    lost_percent = 100.0 * lost_packets / total_packets;
2460 		}
2461 		else {
2462 		    lost_percent = 0.0;
2463 		}
2464 		if (test->json_output)
2465 		    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", (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));
2466 		else
2467 		    iperf_printf(test, report_sum_bw_udp_format, start_time, end_time, ubuf, nbuf, avg_jitter * 1000.0, lost_packets, total_packets, lost_percent, test->omitting?report_omitted:"");
2468 	    }
2469 	}
2470 	}
2471     }
2472 }
2473 
2474 /**
2475  * Print overall summary statistics at the end of a test.
2476  */
2477 static void
2478 iperf_print_results(struct iperf_test *test)
2479 {
2480 
2481     cJSON *json_summary_streams = NULL;
2482     cJSON *json_summary_stream = NULL;
2483     int total_retransmits = 0;
2484     int total_packets = 0, lost_packets = 0;
2485     char ubuf[UNIT_LEN];
2486     char nbuf[UNIT_LEN];
2487     struct stat sb;
2488     char sbuf[UNIT_LEN];
2489     struct iperf_stream *sp = NULL;
2490     iperf_size_t bytes_sent, total_sent = 0;
2491     iperf_size_t bytes_received, total_received = 0;
2492     double start_time, end_time, avg_jitter = 0.0, lost_percent;
2493     double bandwidth;
2494 
2495     /* print final summary for all intervals */
2496 
2497     if (test->json_output) {
2498         json_summary_streams = cJSON_CreateArray();
2499 	if (json_summary_streams == NULL)
2500 	    return;
2501 	cJSON_AddItemToObject(test->json_end, "streams", json_summary_streams);
2502     } else {
2503 	iperf_printf(test, "%s", report_bw_separator);
2504 	if (test->verbose)
2505 	    iperf_printf(test, "%s", report_summary);
2506 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2507 	    if (test->sender_has_retransmits)
2508 		iperf_printf(test, "%s", report_bw_retrans_header);
2509 	    else
2510 		iperf_printf(test, "%s", report_bw_header);
2511 	} else
2512 	    iperf_printf(test, "%s", report_bw_udp_header);
2513     }
2514 
2515     start_time = 0.;
2516     sp = SLIST_FIRST(&test->streams);
2517     /*
2518      * If there is at least one stream, then figure out the length of time
2519      * we were running the tests and print out some statistics about
2520      * the streams.  It's possible to not have any streams at all
2521      * if the client got interrupted before it got to do anything.
2522      */
2523     if (sp) {
2524     end_time = timeval_diff(&sp->result->start_time, &sp->result->end_time);
2525     SLIST_FOREACH(sp, &test->streams, streams) {
2526 	if (test->json_output) {
2527 	    json_summary_stream = cJSON_CreateObject();
2528 	    if (json_summary_stream == NULL)
2529 		return;
2530 	    cJSON_AddItemToArray(json_summary_streams, json_summary_stream);
2531 	}
2532 
2533         bytes_sent = sp->result->bytes_sent - sp->result->bytes_sent_omit;
2534         bytes_received = sp->result->bytes_received;
2535         total_sent += bytes_sent;
2536         total_received += bytes_received;
2537 
2538         if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2539 	    if (test->sender_has_retransmits) {
2540 		total_retransmits += sp->result->stream_retrans;
2541 	    }
2542 	} else {
2543             total_packets += (sp->packet_count - sp->omitted_packet_count);
2544             lost_packets += (sp->cnt_error - sp->omitted_cnt_error);
2545             avg_jitter += sp->jitter;
2546         }
2547 
2548 	unit_snprintf(ubuf, UNIT_LEN, (double) bytes_sent, 'A');
2549 	bandwidth = (double) bytes_sent / (double) end_time;
2550 	unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2551 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2552 	    if (test->sender_has_retransmits) {
2553 		/* Summary, TCP with retransmits. */
2554 		if (test->json_output)
2555 		    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_rtt:  %d  min_rtt:  %d  mean_rtt:  %d", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_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_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)));
2556 		else
2557 		    iperf_printf(test, report_bw_retrans_format, sp->socket, start_time, end_time, ubuf, nbuf, sp->result->stream_retrans, report_sender);
2558 	    } else {
2559 		/* Summary, TCP without retransmits. */
2560 		if (test->json_output)
2561 		    cJSON_AddItemToObject(json_summary_stream, "sender", iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_sent, bandwidth * 8));
2562 		else
2563 		    iperf_printf(test, report_bw_format, sp->socket, start_time, end_time, ubuf, nbuf, report_sender);
2564 	    }
2565 	} else {
2566 	    /* Summary, UDP. */
2567 	    if (sp->packet_count - sp->omitted_packet_count > 0) {
2568               lost_percent = 100.0 * (sp->cnt_error - sp->omitted_cnt_error) / (sp->packet_count - sp->omitted_packet_count);
2569 	    }
2570 	    else {
2571 		lost_percent = 0.0;
2572 	    }
2573 	    if (test->json_output)
2574               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", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_sent, bandwidth * 8, (double) sp->jitter * 1000.0, (int64_t) (sp->cnt_error - sp->omitted_cnt_error), (int64_t) (sp->packet_count - sp->omitted_packet_count), (double) lost_percent, (int64_t) (sp->outoforder_packets - sp->omitted_outoforder_packets)));
2575 	    else {
2576               iperf_printf(test, report_bw_udp_format, sp->socket, start_time, end_time, ubuf, nbuf, sp->jitter * 1000.0, (sp->cnt_error - sp->omitted_cnt_error), (sp->packet_count - sp->omitted_packet_count), lost_percent, "");
2577 		if (test->role == 'c')
2578 		    iperf_printf(test, report_datagrams, sp->socket, (sp->packet_count - sp->omitted_packet_count));
2579 		if ((sp->outoforder_packets - sp->omitted_outoforder_packets) > 0)
2580                   iperf_printf(test, report_sum_outoforder, start_time, end_time, (sp->outoforder_packets - sp->omitted_outoforder_packets));
2581 	    }
2582 	}
2583 
2584 	if (sp->diskfile_fd >= 0) {
2585 	    if (fstat(sp->diskfile_fd, &sb) == 0) {
2586 		/* In the odd case that it's a zero-sized file, say it was all transferred. */
2587 		int percent = 100;
2588 		if (sb.st_size > 0) {
2589 		    percent = (int) ( ( (double) bytes_sent / (double) sb.st_size ) * 100.0 );
2590 		}
2591 		unit_snprintf(sbuf, UNIT_LEN, (double) sb.st_size, 'A');
2592 		if (test->json_output)
2593 		    cJSON_AddItemToObject(json_summary_stream, "diskfile", iperf_json_printf("sent: %d  size: %d  percent: %d  filename: %s", (int64_t) bytes_sent, (int64_t) sb.st_size, (int64_t) percent, test->diskfile_name));
2594 		else
2595 		    iperf_printf(test, report_diskfile, ubuf, sbuf, percent, test->diskfile_name);
2596 	    }
2597 	}
2598 
2599 	unit_snprintf(ubuf, UNIT_LEN, (double) bytes_received, 'A');
2600 	bandwidth = (double) bytes_received / (double) end_time;
2601 	unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2602 	if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2603 	    if (test->json_output)
2604 		cJSON_AddItemToObject(json_summary_stream, "receiver", iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f", (int64_t) sp->socket, (double) start_time, (double) end_time, (double) end_time, (int64_t) bytes_received, bandwidth * 8));
2605 	    else
2606 		iperf_printf(test, report_bw_format, sp->socket, start_time, end_time, ubuf, nbuf, report_receiver);
2607 	}
2608     }
2609     }
2610 
2611     if (test->num_streams > 1 || test->json_output) {
2612         unit_snprintf(ubuf, UNIT_LEN, (double) total_sent, 'A');
2613 	/* If no tests were run, arbitrariliy set bandwidth to 0. */
2614 	if (end_time > 0.0) {
2615 	    bandwidth = (double) total_sent / (double) end_time;
2616 	}
2617 	else {
2618 	    bandwidth = 0.0;
2619 	}
2620         unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2621         if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2622 	    if (test->sender_has_retransmits) {
2623 		/* Summary sum, TCP with retransmits. */
2624 		if (test->json_output)
2625 		    cJSON_AddItemToObject(test->json_end, "sum_sent", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  retransmits: %d", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_sent, bandwidth * 8, (int64_t) total_retransmits));
2626 		else
2627 		    iperf_printf(test, report_sum_bw_retrans_format, start_time, end_time, ubuf, nbuf, total_retransmits, report_sender);
2628 	    } else {
2629 		/* Summary sum, TCP without retransmits. */
2630 		if (test->json_output)
2631 		    cJSON_AddItemToObject(test->json_end, "sum_sent", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_sent, bandwidth * 8));
2632 		else
2633 		    iperf_printf(test, report_sum_bw_format, start_time, end_time, ubuf, nbuf, report_sender);
2634 	    }
2635             unit_snprintf(ubuf, UNIT_LEN, (double) total_received, 'A');
2636 	    /* If no tests were run, set received bandwidth to 0 */
2637 	    if (end_time > 0.0) {
2638 		bandwidth = (double) total_received / (double) end_time;
2639 	    }
2640 	    else {
2641 		bandwidth = 0.0;
2642 	    }
2643             unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2644 	    if (test->json_output)
2645 		cJSON_AddItemToObject(test->json_end, "sum_received", iperf_json_printf("start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_received, bandwidth * 8));
2646 	    else
2647 		iperf_printf(test, report_sum_bw_format, start_time, end_time, ubuf, nbuf, report_receiver);
2648         } else {
2649 	    /* Summary sum, UDP. */
2650             avg_jitter /= test->num_streams;
2651 	    /* If no packets were sent, arbitrarily set loss percentage to 0. */
2652 	    if (total_packets > 0) {
2653 		lost_percent = 100.0 * lost_packets / total_packets;
2654 	    }
2655 	    else {
2656 		lost_percent = 0.0;
2657 	    }
2658 	    if (test->json_output)
2659 		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", (double) start_time, (double) end_time, (double) end_time, (int64_t) total_sent, bandwidth * 8, (double) avg_jitter * 1000.0, (int64_t) lost_packets, (int64_t) total_packets, (double) lost_percent));
2660 	    else
2661 		iperf_printf(test, report_sum_bw_udp_format, start_time, end_time, ubuf, nbuf, avg_jitter * 1000.0, lost_packets, total_packets, lost_percent, "");
2662         }
2663     }
2664 
2665     if (test->json_output) {
2666 	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]));
2667 	if (test->protocol->id == Ptcp) {
2668 	    char *snd_congestion = NULL, *rcv_congestion = NULL;
2669 	    if (test->sender) {
2670 		snd_congestion = test->congestion_used;
2671 		rcv_congestion = test->remote_congestion_used;
2672 	    }
2673 	    else {
2674 		snd_congestion = test->remote_congestion_used;
2675 		rcv_congestion = test->congestion_used;
2676 	    }
2677 	    if (snd_congestion) {
2678 		cJSON_AddStringToObject(test->json_end, "sender_tcp_congestion", snd_congestion);
2679 	    }
2680 	    if (rcv_congestion) {
2681 		cJSON_AddStringToObject(test->json_end, "receiver_tcp_congestion", rcv_congestion);
2682 	    }
2683 	}
2684     }
2685     else {
2686 	if (test->verbose) {
2687 	    iperf_printf(test, report_cpu, report_local, test->sender?report_sender:report_receiver, test->cpu_util[0], test->cpu_util[1], test->cpu_util[2], report_remote, test->sender?report_receiver:report_sender, test->remote_cpu_util[0], test->remote_cpu_util[1], test->remote_cpu_util[2]);
2688 
2689 	    if (test->protocol->id == Ptcp) {
2690 		char *snd_congestion = NULL, *rcv_congestion = NULL;
2691 		if (test->sender) {
2692 		    snd_congestion = test->congestion_used;
2693 		    rcv_congestion = test->remote_congestion_used;
2694 		}
2695 		else {
2696 		    snd_congestion = test->remote_congestion_used;
2697 		    rcv_congestion = test->congestion_used;
2698 		}
2699 		if (snd_congestion) {
2700 		    iperf_printf(test, "snd_tcp_congestion %s\n", snd_congestion);
2701 		}
2702 		if (rcv_congestion) {
2703 		    iperf_printf(test, "rcv_tcp_congestion %s\n", rcv_congestion);
2704 		}
2705 	    }
2706 	}
2707 
2708 	/* Print server output if we're on the client and it was requested/provided */
2709 	if (test->role == 'c' && iperf_get_test_get_server_output(test)) {
2710 	    if (test->json_server_output) {
2711 		iperf_printf(test, "\nServer JSON output:\n%s\n", cJSON_Print(test->json_server_output));
2712 		cJSON_Delete(test->json_server_output);
2713 		test->json_server_output = NULL;
2714 	    }
2715 	    if (test->server_output_text) {
2716 		iperf_printf(test, "\nServer output:\n%s\n", test->server_output_text);
2717 		test->server_output_text = NULL;
2718 	    }
2719 	}
2720     }
2721 }
2722 
2723 /**************************************************************************/
2724 
2725 /**
2726  * Main report-printing callback.
2727  * Prints results either during a test (interval report only) or
2728  * after the entire test has been run (last interval report plus
2729  * overall summary).
2730  */
2731 void
2732 iperf_reporter_callback(struct iperf_test *test)
2733 {
2734     switch (test->state) {
2735         case TEST_RUNNING:
2736         case STREAM_RUNNING:
2737             /* print interval results for each stream */
2738             iperf_print_intermediate(test);
2739             break;
2740         case TEST_END:
2741         case DISPLAY_RESULTS:
2742             iperf_print_intermediate(test);
2743             iperf_print_results(test);
2744             break;
2745     }
2746 
2747 }
2748 
2749 /**
2750  * Print the interval results for one stream.
2751  * This function needs to know about the overall test so it can determine the
2752  * context for printing headers, separators, etc.
2753  */
2754 static void
2755 print_interval_results(struct iperf_test *test, struct iperf_stream *sp, cJSON *json_interval_streams)
2756 {
2757     char ubuf[UNIT_LEN];
2758     char nbuf[UNIT_LEN];
2759     char cbuf[UNIT_LEN];
2760     double st = 0., et = 0.;
2761     struct iperf_interval_results *irp = NULL;
2762     double bandwidth, lost_percent;
2763 
2764     irp = TAILQ_LAST(&sp->result->interval_results, irlisthead); /* get last entry in linked list */
2765     if (irp == NULL) {
2766 	iperf_err(test, "print_interval_results error: interval_results is NULL");
2767         return;
2768     }
2769     if (!test->json_output) {
2770 	/* First stream? */
2771 	if (sp == SLIST_FIRST(&test->streams)) {
2772 	    /* It it's the first interval, print the header;
2773 	    ** else if there's more than one stream, print the separator;
2774 	    ** else nothing.
2775 	    */
2776 	    if (timeval_equals(&sp->result->start_time, &irp->interval_start_time)) {
2777 		if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2778 		    if (test->sender && test->sender_has_retransmits)
2779 			iperf_printf(test, "%s", report_bw_retrans_cwnd_header);
2780 		    else
2781 			iperf_printf(test, "%s", report_bw_header);
2782 		} else {
2783 		    if (test->sender)
2784 			iperf_printf(test, "%s", report_bw_udp_sender_header);
2785 		    else
2786 			iperf_printf(test, "%s", report_bw_udp_header);
2787 		}
2788 	    } else if (test->num_streams > 1)
2789 		iperf_printf(test, "%s", report_bw_separator);
2790 	}
2791     }
2792 
2793     unit_snprintf(ubuf, UNIT_LEN, (double) (irp->bytes_transferred), 'A');
2794     if (irp->interval_duration > 0.0) {
2795 	bandwidth = (double) irp->bytes_transferred / (double) irp->interval_duration;
2796     }
2797     else {
2798 	bandwidth = 0.0;
2799     }
2800     unit_snprintf(nbuf, UNIT_LEN, bandwidth, test->settings->unit_format);
2801 
2802     st = timeval_diff(&sp->result->start_time, &irp->interval_start_time);
2803     et = timeval_diff(&sp->result->start_time, &irp->interval_end_time);
2804 
2805     if (test->protocol->id == Ptcp || test->protocol->id == Psctp) {
2806 	if (test->sender && test->sender_has_retransmits) {
2807 	    /* Interval, TCP with retransmits. */
2808 	    if (test->json_output)
2809 		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  rtt:  %d  rttvar: %d  omitted: %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->rtt, (int64_t) irp->rttvar, irp->omitted));
2810 	    else {
2811 		unit_snprintf(cbuf, UNIT_LEN, irp->snd_cwnd, 'A');
2812 		iperf_printf(test, report_bw_retrans_cwnd_format, sp->socket, st, et, ubuf, nbuf, irp->interval_retrans, cbuf, irp->omitted?report_omitted:"");
2813 	    }
2814 	} else {
2815 	    /* Interval, TCP without retransmits. */
2816 	    if (test->json_output)
2817 		cJSON_AddItemToArray(json_interval_streams, iperf_json_printf("socket: %d  start: %f  end: %f  seconds: %f  bytes: %d  bits_per_second: %f  omitted: %b", (int64_t) sp->socket, (double) st, (double) et, (double) irp->interval_duration, (int64_t) irp->bytes_transferred, bandwidth * 8, irp->omitted));
2818 	    else
2819 		iperf_printf(test, report_bw_format, sp->socket, st, et, ubuf, nbuf, irp->omitted?report_omitted:"");
2820 	}
2821     } else {
2822 	/* Interval, UDP. */
2823 	if (test->sender) {
2824 	    if (test->json_output)
2825 		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", (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));
2826 	    else
2827 		iperf_printf(test, report_bw_udp_sender_format, sp->socket, st, et, ubuf, nbuf, irp->interval_packet_count, irp->omitted?report_omitted:"");
2828 	} else {
2829 	    if (irp->interval_packet_count > 0) {
2830 		lost_percent = 100.0 * irp->interval_cnt_error / irp->interval_packet_count;
2831 	    }
2832 	    else {
2833 		lost_percent = 0.0;
2834 	    }
2835 	    if (test->json_output)
2836 		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", (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));
2837 	    else
2838 		iperf_printf(test, report_bw_udp_format, sp->socket, st, et, ubuf, nbuf, irp->jitter * 1000.0, irp->interval_cnt_error, irp->interval_packet_count, lost_percent, irp->omitted?report_omitted:"");
2839 	}
2840     }
2841 
2842     if (test->logfile || test->forceflush)
2843         iflush(test);
2844 }
2845 
2846 /**************************************************************************/
2847 void
2848 iperf_free_stream(struct iperf_stream *sp)
2849 {
2850     struct iperf_interval_results *irp, *nirp;
2851 
2852     /* XXX: need to free interval list too! */
2853     munmap(sp->buffer, sp->test->settings->blksize);
2854     close(sp->buffer_fd);
2855     if (sp->diskfile_fd >= 0)
2856 	close(sp->diskfile_fd);
2857     for (irp = TAILQ_FIRST(&sp->result->interval_results); irp != NULL; irp = nirp) {
2858         nirp = TAILQ_NEXT(irp, irlistentries);
2859         free(irp);
2860     }
2861     free(sp->result);
2862     if (sp->send_timer != NULL)
2863 	tmr_cancel(sp->send_timer);
2864     free(sp);
2865 }
2866 
2867 /**************************************************************************/
2868 struct iperf_stream *
2869 iperf_new_stream(struct iperf_test *test, int s)
2870 {
2871     int i;
2872     struct iperf_stream *sp;
2873 
2874     char template[1024];
2875     if (test->tmp_template) {
2876         snprintf(template, sizeof(template) / sizeof(char), "%s", test->tmp_template);
2877     } else {
2878         //find the system temporary dir *unix, windows, cygwin support
2879         char* tempdir = getenv("TMPDIR");
2880         if (tempdir == 0){
2881             tempdir = getenv("TEMP");
2882         }
2883         if (tempdir == 0){
2884             tempdir = getenv("TMP");
2885         }
2886         if (tempdir == 0){
2887             tempdir = "/tmp";
2888         }
2889         snprintf(template, sizeof(template) / sizeof(char), "%s/iperf3.XXXXXX", tempdir);
2890     }
2891 
2892     sp = (struct iperf_stream *) malloc(sizeof(struct iperf_stream));
2893     if (!sp) {
2894         i_errno = IECREATESTREAM;
2895         return NULL;
2896     }
2897 
2898     memset(sp, 0, sizeof(struct iperf_stream));
2899 
2900     sp->test = test;
2901     sp->settings = test->settings;
2902     sp->result = (struct iperf_stream_result *) malloc(sizeof(struct iperf_stream_result));
2903     if (!sp->result) {
2904         free(sp);
2905         i_errno = IECREATESTREAM;
2906         return NULL;
2907     }
2908 
2909     memset(sp->result, 0, sizeof(struct iperf_stream_result));
2910     TAILQ_INIT(&sp->result->interval_results);
2911 
2912     /* Create and randomize the buffer */
2913     sp->buffer_fd = mkstemp(template);
2914     if (sp->buffer_fd == -1) {
2915         i_errno = IECREATESTREAM;
2916         free(sp->result);
2917         free(sp);
2918         return NULL;
2919     }
2920     if (unlink(template) < 0) {
2921         i_errno = IECREATESTREAM;
2922         free(sp->result);
2923         free(sp);
2924         return NULL;
2925     }
2926     if (ftruncate(sp->buffer_fd, test->settings->blksize) < 0) {
2927         i_errno = IECREATESTREAM;
2928         free(sp->result);
2929         free(sp);
2930         return NULL;
2931     }
2932     sp->buffer = (char *) mmap(NULL, test->settings->blksize, PROT_READ|PROT_WRITE, MAP_PRIVATE, sp->buffer_fd, 0);
2933     if (sp->buffer == MAP_FAILED) {
2934         i_errno = IECREATESTREAM;
2935         free(sp->result);
2936         free(sp);
2937         return NULL;
2938     }
2939     srandom(time(NULL));
2940     for (i = 0; i < test->settings->blksize; ++i)
2941         sp->buffer[i] = random();
2942 
2943     /* Set socket */
2944     sp->socket = s;
2945 
2946     sp->snd = test->protocol->send;
2947     sp->rcv = test->protocol->recv;
2948 
2949     if (test->diskfile_name != (char*) 0) {
2950 	sp->diskfile_fd = open(test->diskfile_name, test->sender ? O_RDONLY : (O_WRONLY|O_CREAT|O_TRUNC), S_IRUSR|S_IWUSR);
2951 	if (sp->diskfile_fd == -1) {
2952 	    i_errno = IEFILE;
2953             munmap(sp->buffer, sp->test->settings->blksize);
2954             free(sp->result);
2955             free(sp);
2956 	    return NULL;
2957 	}
2958         sp->snd2 = sp->snd;
2959 	sp->snd = diskfile_send;
2960 	sp->rcv2 = sp->rcv;
2961 	sp->rcv = diskfile_recv;
2962     } else
2963         sp->diskfile_fd = -1;
2964 
2965     /* Initialize stream */
2966     if (iperf_init_stream(sp, test) < 0) {
2967         close(sp->buffer_fd);
2968         munmap(sp->buffer, sp->test->settings->blksize);
2969         free(sp->result);
2970         free(sp);
2971         return NULL;
2972     }
2973     iperf_add_stream(test, sp);
2974 
2975     return sp;
2976 }
2977 
2978 /**************************************************************************/
2979 int
2980 iperf_init_stream(struct iperf_stream *sp, struct iperf_test *test)
2981 {
2982     socklen_t len;
2983     int opt;
2984 
2985     len = sizeof(struct sockaddr_storage);
2986     if (getsockname(sp->socket, (struct sockaddr *) &sp->local_addr, &len) < 0) {
2987         i_errno = IEINITSTREAM;
2988         return -1;
2989     }
2990     len = sizeof(struct sockaddr_storage);
2991     if (getpeername(sp->socket, (struct sockaddr *) &sp->remote_addr, &len) < 0) {
2992         i_errno = IEINITSTREAM;
2993         return -1;
2994     }
2995 
2996     /* Set IP TOS */
2997     if ((opt = test->settings->tos)) {
2998         if (getsockdomain(sp->socket) == AF_INET6) {
2999 #ifdef IPV6_TCLASS
3000             if (setsockopt(sp->socket, IPPROTO_IPV6, IPV6_TCLASS, &opt, sizeof(opt)) < 0) {
3001                 i_errno = IESETCOS;
3002                 return -1;
3003             }
3004 #else
3005             i_errno = IESETCOS;
3006             return -1;
3007 #endif
3008         } else {
3009             if (setsockopt(sp->socket, IPPROTO_IP, IP_TOS, &opt, sizeof(opt)) < 0) {
3010                 i_errno = IESETTOS;
3011                 return -1;
3012             }
3013         }
3014     }
3015 
3016     return 0;
3017 }
3018 
3019 /**************************************************************************/
3020 void
3021 iperf_add_stream(struct iperf_test *test, struct iperf_stream *sp)
3022 {
3023     int i;
3024     struct iperf_stream *n, *prev;
3025 
3026     if (SLIST_EMPTY(&test->streams)) {
3027         SLIST_INSERT_HEAD(&test->streams, sp, streams);
3028         sp->id = 1;
3029     } else {
3030         // for (n = test->streams, i = 2; n->next; n = n->next, ++i);
3031         i = 2;
3032         SLIST_FOREACH(n, &test->streams, streams) {
3033             prev = n;
3034             ++i;
3035         }
3036         SLIST_INSERT_AFTER(prev, sp, streams);
3037         sp->id = i;
3038     }
3039 }
3040 
3041 /* This pair of routines gets inserted into the snd/rcv function pointers
3042 ** when there's a -F flag. They handle the file stuff and call the real
3043 ** snd/rcv functions, which have been saved in snd2/rcv2.
3044 **
3045 ** The advantage of doing it this way is that in the much more common
3046 ** case of no -F flag, there is zero extra overhead.
3047 */
3048 
3049 static int
3050 diskfile_send(struct iperf_stream *sp)
3051 {
3052     int r;
3053 
3054     r = read(sp->diskfile_fd, sp->buffer, sp->test->settings->blksize);
3055     if (r == 0)
3056         sp->test->done = 1;
3057     else
3058 	r = sp->snd2(sp);
3059     return r;
3060 }
3061 
3062 static int
3063 diskfile_recv(struct iperf_stream *sp)
3064 {
3065     int r;
3066 
3067     r = sp->rcv2(sp);
3068     if (r > 0) {
3069 	(void) write(sp->diskfile_fd, sp->buffer, r);
3070 	(void) fsync(sp->diskfile_fd);
3071     }
3072     return r;
3073 }
3074 
3075 
3076 void
3077 iperf_catch_sigend(void (*handler)(int))
3078 {
3079     signal(SIGINT, handler);
3080     signal(SIGTERM, handler);
3081     signal(SIGHUP, handler);
3082 }
3083 
3084 /**
3085  * Called as a result of getting a signal.
3086  * Depending on the current state of the test (and the role of this
3087  * process) compute and report one more set of ending statistics
3088  * before cleaning up and exiting.
3089  */
3090 void
3091 iperf_got_sigend(struct iperf_test *test)
3092 {
3093     /*
3094      * If we're the client, or if we're a server and running a test,
3095      * then dump out the accumulated stats so far.
3096      */
3097     if (test->role == 'c' ||
3098       (test->role == 's' && test->state == TEST_RUNNING)) {
3099 
3100 	test->done = 1;
3101 	cpu_util(test->cpu_util);
3102 	test->stats_callback(test);
3103 	test->state = DISPLAY_RESULTS; /* change local state only */
3104 	if (test->on_test_finish)
3105 	    test->on_test_finish(test);
3106 	test->reporter_callback(test);
3107     }
3108 
3109     if (test->ctrl_sck >= 0) {
3110 	test->state = (test->role == 'c') ? CLIENT_TERMINATE : SERVER_TERMINATE;
3111 	(void) Nwrite(test->ctrl_sck, (char*) &test->state, sizeof(signed char), Ptcp);
3112     }
3113     i_errno = (test->role == 'c') ? IECLIENTTERM : IESERVERTERM;
3114     iperf_errexit(test, "interrupt - %s", iperf_strerror(i_errno));
3115 }
3116 
3117 /* Try to write a PID file if requested, return -1 on an error. */
3118 int
3119 iperf_create_pidfile(struct iperf_test *test)
3120 {
3121     if (test->pidfile) {
3122 	int fd;
3123 	char buf[8];
3124 	fd = open(test->pidfile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR|S_IWUSR);
3125 	if (fd < 0) {
3126 	    return -1;
3127 	}
3128 	snprintf(buf, sizeof(buf), "%d", getpid()); /* no trailing newline */
3129 	if (write(fd, buf, strlen(buf) + 1) < 0) {
3130 	    return -1;
3131 	}
3132 	if (close(fd) < 0) {
3133 	    return -1;
3134 	};
3135     }
3136     return 0;
3137 }
3138 
3139 /* Get rid of a PID file, return -1 on error. */
3140 int
3141 iperf_delete_pidfile(struct iperf_test *test)
3142 {
3143     if (test->pidfile) {
3144 	if (unlink(test->pidfile) < 0) {
3145 	    return -1;
3146 	}
3147     }
3148     return 0;
3149 }
3150 
3151 int
3152 iperf_json_start(struct iperf_test *test)
3153 {
3154     test->json_top = cJSON_CreateObject();
3155     if (test->json_top == NULL)
3156         return -1;
3157     test->json_start = cJSON_CreateObject();
3158     if (test->json_start == NULL)
3159         return -1;
3160     cJSON_AddItemToObject(test->json_top, "start", test->json_start);
3161     test->json_connected = cJSON_CreateArray();
3162     if (test->json_connected == NULL)
3163         return -1;
3164     cJSON_AddItemToObject(test->json_start, "connected", test->json_connected);
3165     test->json_intervals = cJSON_CreateArray();
3166     if (test->json_intervals == NULL)
3167         return -1;
3168     cJSON_AddItemToObject(test->json_top, "intervals", test->json_intervals);
3169     test->json_end = cJSON_CreateObject();
3170     if (test->json_end == NULL)
3171         return -1;
3172     cJSON_AddItemToObject(test->json_top, "end", test->json_end);
3173     return 0;
3174 }
3175 
3176 int
3177 iperf_json_finish(struct iperf_test *test)
3178 {
3179     if (test->title)
3180 	cJSON_AddStringToObject(test->json_top, "title", test->title);
3181     /* Include server output */
3182     if (test->json_server_output) {
3183 	cJSON_AddItemToObject(test->json_top, "server_output_json", test->json_server_output);
3184     }
3185     if (test->server_output_text) {
3186 	cJSON_AddStringToObject(test->json_top, "server_output_text", test->server_output_text);
3187     }
3188     test->json_output_string = cJSON_Print(test->json_top);
3189     if (test->json_output_string == NULL)
3190         return -1;
3191     fprintf(test->outfile, "%s\n", test->json_output_string);
3192     iflush(test);
3193     cJSON_Delete(test->json_top);
3194     test->json_top = test->json_start = test->json_connected = test->json_intervals = test->json_server_output = test->json_end = NULL;
3195     return 0;
3196 }
3197 
3198 
3199 /* CPU affinity stuff - Linux and FreeBSD only. */
3200 
3201 int
3202 iperf_setaffinity(struct iperf_test *test, int affinity)
3203 {
3204 #if defined(HAVE_SCHED_SETAFFINITY)
3205     cpu_set_t cpu_set;
3206 
3207     CPU_ZERO(&cpu_set);
3208     CPU_SET(affinity, &cpu_set);
3209     if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0) {
3210 	i_errno = IEAFFINITY;
3211         return -1;
3212     }
3213     return 0;
3214 #elif defined(HAVE_CPUSET_SETAFFINITY)
3215     cpuset_t cpumask;
3216 
3217     if(cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1,
3218                           sizeof(cpuset_t), &test->cpumask) != 0) {
3219         i_errno = IEAFFINITY;
3220         return -1;
3221     }
3222 
3223     CPU_ZERO(&cpumask);
3224     CPU_SET(affinity, &cpumask);
3225 
3226     if(cpuset_setaffinity(CPU_LEVEL_WHICH,CPU_WHICH_PID, -1,
3227                           sizeof(cpuset_t), &cpumask) != 0) {
3228         i_errno = IEAFFINITY;
3229         return -1;
3230     }
3231     return 0;
3232 #else /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY */
3233     i_errno = IEAFFINITY;
3234     return -1;
3235 #endif /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY */
3236 }
3237 
3238 int
3239 iperf_clearaffinity(struct iperf_test *test)
3240 {
3241 #if defined(HAVE_SCHED_SETAFFINITY)
3242     cpu_set_t cpu_set;
3243     int i;
3244 
3245     CPU_ZERO(&cpu_set);
3246     for (i = 0; i < CPU_SETSIZE; ++i)
3247 	CPU_SET(i, &cpu_set);
3248     if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0) {
3249 	i_errno = IEAFFINITY;
3250         return -1;
3251     }
3252     return 0;
3253 #elif defined(HAVE_CPUSET_SETAFFINITY)
3254     if(cpuset_setaffinity(CPU_LEVEL_WHICH,CPU_WHICH_PID, -1,
3255                           sizeof(cpuset_t), &test->cpumask) != 0) {
3256         i_errno = IEAFFINITY;
3257         return -1;
3258     }
3259     return 0;
3260 #else /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY */
3261     i_errno = IEAFFINITY;
3262     return -1;
3263 #endif /* neither HAVE_SCHED_SETAFFINITY nor HAVE_CPUSET_SETAFFINITY */
3264 }
3265 
3266 int
3267 iperf_printf(struct iperf_test *test, const char* format, ...)
3268 {
3269     va_list argp;
3270     int r = -1;
3271 
3272     /*
3273      * There are roughly two use cases here.  If we're the client,
3274      * want to print stuff directly to the output stream.
3275      * If we're the sender we might need to buffer up output to send
3276      * to the client.
3277      *
3278      * This doesn't make a whole lot of difference except there are
3279      * some chunks of output on the client (on particular the whole
3280      * of the server output with --get-server-output) that could
3281      * easily exceed the size of the line buffer, but which don't need
3282      * to be buffered up anyway.
3283      */
3284     if (test->role == 'c') {
3285 	if (test->title)
3286 	    fprintf(test->outfile, "%s:  ", test->title);
3287 	va_start(argp, format);
3288 	r = vfprintf(test->outfile, format, argp);
3289 	va_end(argp);
3290     }
3291     else if (test->role == 's') {
3292 	char linebuffer[1024];
3293 	va_start(argp, format);
3294 	r = vsnprintf(linebuffer, sizeof(linebuffer), format, argp);
3295 	va_end(argp);
3296 	fprintf(test->outfile, "%s", linebuffer);
3297 
3298 	if (test->role == 's' && iperf_get_test_get_server_output(test)) {
3299 	    struct iperf_textline *l = (struct iperf_textline *) malloc(sizeof(struct iperf_textline));
3300 	    l->line = strdup(linebuffer);
3301 	    TAILQ_INSERT_TAIL(&(test->server_output_list), l, textlineentries);
3302 	}
3303     }
3304     return r;
3305 }
3306 
3307 int
3308 iflush(struct iperf_test *test)
3309 {
3310     return fflush(test->outfile);
3311 }
3312