stubd.c 28.5 KB
Newer Older
Junxing Zhang's avatar
Junxing Zhang committed
1
2
3
4
5
6
7
8
/****************************************************************************
 *  stubd.c: PlanetLab emulator stub program
 *  Copyright (C) 2005-2006
 *  Junxing Zhang
 *  Flux research group, University of Utah
 *
 ****************************************************************************/

9

Junxing Zhang's avatar
Junxing Zhang committed
10
11
#include "stub.h"

12
13
14
15
16
17
18
19
20
21
/*
 * For getopt()
 */
#include <unistd.h>
extern char *optarg;
extern int optind;
extern int optopt;
extern int opterr;
extern int optreset;

22
23
24
void clean_exit(int);
void append_delay_sample(int path_id, long sample_value);

Junxing Zhang's avatar
Junxing Zhang committed
25
//Global  
26
short  flag_debug, flag_standalone;
27
char sniff_interface[128];
Junxing Zhang's avatar
Junxing Zhang committed
28
connection rcvdb[CONCURRENT_RECEIVERS];
29
30
unsigned long delays[CONCURRENT_RECEIVERS]; //delay is calculated at the sender side
unsigned long last_delays[CONCURRENT_RECEIVERS];
31
delay_record delay_records[CONCURRENT_RECEIVERS]; //delay list is calculated at the sender side
32
33
loss_record loss_records[CONCURRENT_RECEIVERS]; //loss is calculated at the sender side
unsigned long last_loss_rates[CONCURRENT_RECEIVERS]; //loss per billion
34
35
36
37
int last_through[CONCURRENT_RECEIVERS]; 
int flag_testmode=0;
enum {TEST_NOTTESTING, TEST_NOTSTARTED, TEST_RUNNING, TEST_DONE } test_state;
unsigned long long total_bytes = 0;
38

39
connection snddb[CONCURRENT_SENDERS];
Junxing Zhang's avatar
Junxing Zhang committed
40
41
fd_set read_fds,write_fds;

42

43
44
45
46
int maxfd;

char random_buffer[MAX_PAYLOAD_SIZE];

47
48
int total_size = 0;

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
typedef struct packet_buffer_node_tag
{
  struct packet_buffer_node_tag * next;
  char * buffer;
  int size;
} packet_buffer_node;

typedef struct
{
  unsigned long ip;
  long delta;
  long size;
} packet_info;

packet_buffer_node * packet_buffer_head;
packet_buffer_node * packet_buffer_tail;
int packet_buffer_index;

void packet_buffer_init(void)
{
  packet_buffer_head = NULL;
  packet_buffer_tail = NULL;
  packet_buffer_index = 0;
}

void packet_buffer_cleanup(void)
{
  packet_buffer_node * old_head;
  while (packet_buffer_head != NULL)
  {
    old_head = packet_buffer_head;
    packet_buffer_head = old_head->next;
    free(old_head->buffer);
    free(old_head);
  }
  packet_buffer_tail = NULL;
  packet_buffer_index = 0;
}

// Add a buffer with data about packets to send to the end of the list.
void packet_buffer_add(char * buffer, int size)
{
  packet_buffer_node * newbuf = malloc(sizeof(packet_buffer_node));
  if (newbuf == NULL)
  {
    perror("allocate");
    clean_exit(1);
  }
  newbuf->next = NULL;
  newbuf->buffer = buffer;
  newbuf->size = size;
  if (packet_buffer_tail == NULL)
  {
    packet_buffer_head = newbuf;
    packet_buffer_tail = newbuf;
    packet_buffer_index = 0;
  }
  else
  {
    packet_buffer_tail->next = newbuf;
    packet_buffer_tail = newbuf;
  }
}

// Get info about the next packet to send
packet_info packet_buffer_front(void)
{
  packet_info result;
  if (packet_buffer_head == NULL)
  {
    printf("packet_buffer_head == NULL in front\n");
    clean_exit(1);
  }
  else
  {
    char * base = packet_buffer_head->buffer + packet_buffer_index;
    memcpy(&result.ip, base, SIZEOF_LONG);
126
    memcpy(&result.delta, base + SIZEOF_LONG, SIZEOF_LONG);
127
    result.delta = ntohl(result.delta);
128
    memcpy(&result.size, base + SIZEOF_LONG + SIZEOF_LONG, SIZEOF_LONG);
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    result.size = ntohl(result.size);
  }
  return result;
}

// Are there any packets to get info about?
int packet_buffer_more(void)
{
  return packet_buffer_head != NULL;
}

// Move to the next packet, cleaning up as we go.
void packet_buffer_advance(void)
{
143
  packet_buffer_index += 3*SIZEOF_LONG;
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
  if (packet_buffer_index >= packet_buffer_head->size)
  {
    packet_buffer_node * old_head = packet_buffer_head;
    packet_buffer_head = old_head->next;
    packet_buffer_index = 0;
    free(old_head->buffer);
    free(old_head);
    if (packet_buffer_head == NULL)
    {
      packet_buffer_tail = NULL;
    }
  }
}

void init_random_buffer(void)
{
  int i = 0;
  srandom(getpid());
  for (i=0; i<MAX_PAYLOAD_SIZE; i++)
  {
    random_buffer[i]=(char)(random()&0x000000ff);
  }
}
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

void copy_ulong(char **buf_ptr, ulong value, int flag_hton) {
  ulong tmpulong;

  if (flag_hton) {
    tmpulong = htonl(value);
  } else {
    tmpulong = value;
  }
  memcpy(*buf_ptr, &tmpulong, SIZEOF_LONG);
  (*buf_ptr) += SIZEOF_LONG;
}  

//Append a delay sample to the tail of the ith delay-record queue.
void append_delay_sample(int path_id, long sample_value) {
  delay_sample *sample = malloc(sizeof(delay_sample));
  if (sample == NULL) {
    perror("allocate");
    clean_exit(1);
  }
  sample->next  = NULL;
  sample->value = sample_value;
  gettimeofday(&(sample->time), NULL);
  if (delay_records[path_id].tail == NULL) {
    delay_records[path_id].head = sample;
    delay_records[path_id].tail = sample;
  } else {
    delay_records[path_id].tail->next = sample;
    delay_records[path_id].tail = sample;
  }
  delay_records[path_id].sample_number++;
}

//Remove and return the delay samples.
//Input: path_id.
//Output: size.
//Return: sample_buffer
char *remove_delay_samples(int path_id, int *size) {
  int i, number, msecs;
  unsigned long interval;
  char *sample_buffer, *buf_ptr;
  struct timeval *last_tvp, *this_tvp;
  delay_sample *samp_ptr;

  number = delay_records[path_id].sample_number;
  if (number == 0) return NULL;

  *size = 3 * SIZEOF_LONG * (number+1);
  sample_buffer = (char *) malloc(*size);
  if (sample_buffer == NULL) {
    perror("allocate");
    clean_exit(1);
  }
  buf_ptr = sample_buffer;

  //copy list size into the buffer
  //format: ip, type, value
  copy_ulong(&buf_ptr, rcvdb[path_id].ip, 0); //the receiver ip
  copy_ulong(&buf_ptr, CODE_LIST_SIZE, 1);
  copy_ulong(&buf_ptr, number, 1);

  //copy the first delay into the buffer
  //format: interval, type, value
  samp_ptr = delay_records[path_id].head;
  copy_ulong(&buf_ptr, 0L, 1); //zero interval
  copy_ulong(&buf_ptr, CODE_LIST_DELAY, 1);
  copy_ulong(&buf_ptr, samp_ptr->value, 1);
  last_tvp = &(samp_ptr->time);

  //copy the following delays
  for (i=1; i<number; i++) {
    samp_ptr = samp_ptr->next;
    this_tvp = &(samp_ptr->time);
    msecs = floor((this_tvp->tv_usec-last_tvp->tv_usec)/1000.0+0.5);
    interval = (this_tvp->tv_sec-last_tvp->tv_sec)*1000 + msecs;
    copy_ulong(&buf_ptr, interval, 1); //interval in msecs
    copy_ulong(&buf_ptr, CODE_LIST_DELAY, 1);
    copy_ulong(&buf_ptr, samp_ptr->value, 1);
    last_tvp = &(samp_ptr->time);
    free(delay_records[path_id].head); //release the i-1 delay_sample
    delay_records[path_id].head = samp_ptr; //use head as the pre_ptr
  }
  free(delay_records[path_id].head); //release the last delay_sample
  delay_records[path_id].head = NULL;
  delay_records[path_id].tail = NULL;
  delay_records[path_id].sample_number = 0;
  return sample_buffer;
}

256
257
258
259
260
261
262
263
264
//Initialize or reset state varialbes related to a receiver connection
void reset_rcv_entry(int i) {
  rcvdb[i].valid = 0;
  loss_records[i].loss_counter=0;
  loss_records[i].total_counter=0;
  last_loss_rates[i]=0;
  delays[i]=0;
  last_delays[i]=0;
}
265

266
void init(void) {
Junxing Zhang's avatar
Junxing Zhang committed
267
268
  int i;
  
269
  for (i=0; i<CONCURRENT_RECEIVERS; i++){
270
    reset_rcv_entry(i);
Junxing Zhang's avatar
Junxing Zhang committed
271
272
273
274
275
276
  }
  for (i=0; i<CONCURRENT_SENDERS; i++){
    snddb[i].valid = 0;
  }
}

277
int insert_db(unsigned long ip, int sockfd, int dbtype) {
278
  int i, record_number, next = -1;
Junxing Zhang's avatar
Junxing Zhang committed
279
280
281
282
283
284
  time_t now  = time(NULL); 
  double thisdiff, maxdiff = 0;
  connection *db;
  
  if (dbtype == 0 ) {
    db = rcvdb;
285
    record_number = CONCURRENT_RECEIVERS;
Junxing Zhang's avatar
Junxing Zhang committed
286
287
  } else {
    db = snddb;
288
    record_number = CONCURRENT_SENDERS;
Junxing Zhang's avatar
Junxing Zhang committed
289
290
291
  }

  //find an unused entry or LRU entry
292
  for (i=0; i<record_number; i++){
Junxing Zhang's avatar
Junxing Zhang committed
293
294
295
296
297
298
299
300
301
302
303
304
305
    if (db[i].valid == 0) {
      next = i;
      break;
    } else {
      thisdiff = difftime(now, db[i].last_usetime);
      if (thisdiff > maxdiff) {
        maxdiff = thisdiff;
        next    = i;
      }
    }
  }
  if (db[next].valid == 1) {
    close(db[next].sockfd);
306
307
308
309
310
311
312
313
314
315
316

    if (dbtype == 0 ) { //if rcvdb
      //reset related state variables
      sniff_rcvdb[next].start = 0;
      sniff_rcvdb[next].end   = 0;
      throughput[next].isValid   = 0;
      FD_CLR(db[next].sockfd, &write_fds);
      reset_rcv_entry(next);
    } else { //if snddb
      FD_CLR(db[next].sockfd, &read_fds);
    }
Junxing Zhang's avatar
Junxing Zhang committed
317
318
319
320
321
  }
  db[next].valid = 1;
  db[next].ip    = ip;
  db[next].sockfd= sockfd;
  db[next].last_usetime = now;
322
  db[next].pending = 0;
Junxing Zhang's avatar
Junxing Zhang committed
323
324
325
  return next;
}

326
int search_rcvdb(unsigned long indexip){
Junxing Zhang's avatar
Junxing Zhang committed
327
328
329
  int i;

  for (i=0; i<CONCURRENT_RECEIVERS; i++){
330
    if (rcvdb[i].valid==1 && rcvdb[i].ip == indexip) {
Junxing Zhang's avatar
Junxing Zhang committed
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
      rcvdb[i].last_usetime = time(NULL);
      return i;
    } 
  }
  return -1; //no sockfd is -1
}

void clean_exit(int code){
  int i;

  for (i=0; i<CONCURRENT_RECEIVERS; i++){
    if (rcvdb[i].valid == 1){
      close(rcvdb[i].sockfd); 
    } 
  }
  for (i=0; i<CONCURRENT_SENDERS; i++){
    if (snddb[i].valid == 1){
      close(snddb[i].sockfd); 
    } 
  }
351
  packet_buffer_cleanup();
Junxing Zhang's avatar
Junxing Zhang committed
352
353
354
  exit(code);
}

355
int get_rcvdb_index(unsigned long destaddr){
Junxing Zhang's avatar
Junxing Zhang committed
356
357
358
  int dbindex, sockfd;
  struct sockaddr_in their_addr;  // connector's address information 

359
  if ((dbindex=search_rcvdb(destaddr)) == -1) {
Junxing Zhang's avatar
Junxing Zhang committed
360
361
362
363
364
365
366
367
368
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
      perror("socket");
      clean_exit(1);
    }

    their_addr.sin_family = AF_INET;    // host byte order 
    their_addr.sin_port = htons(SENDER_PORT);  // short, network byte order 
    their_addr.sin_addr.s_addr = destaddr;
    memset(&(their_addr.sin_zero), '\0', 8);  // zero the rest of the struct 
369
    if (flag_debug) printf("Try to connect to %s \n", inet_ntoa(their_addr.sin_addr));
Junxing Zhang's avatar
Junxing Zhang committed
370
371
372
373
374

    if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
      perror("connect");
      clean_exit(1);
    }
375

376
377
378
    if (sockfd > maxfd) {
      maxfd = sockfd;
    }
379
    dbindex=insert_db(destaddr, sockfd, 0); //insert rcvdb
Junxing Zhang's avatar
Junxing Zhang committed
380
381
382
383
  }
  return dbindex;
}

384
385
386
387
void remove_pending(int index)
{
    if (rcvdb[index].pending == 0)
    {
388
	FD_CLR(rcvdb[index].sockfd, &write_fds);
389
390
391
392
393
394
395
    }
}

void add_pending(int index, int size)
{
    if (rcvdb[index].pending == 0 && size > 0)
    {
396
	FD_SET(rcvdb[index].sockfd, &write_fds);
397
398
399
400
    }
    rcvdb[index].pending += size;
}

401
void try_pending(int index, fd_set * write_fds_copy)
402
{
403
404
    if (rcvdb[index].pending > 0 && FD_ISSET(rcvdb[index].sockfd,
					     write_fds_copy))
405
    {
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
	int size = 0;
	int error = 0;
	if (rcvdb[index].pending > LOW_WATER_MARK)
	{
	    size = LOW_WATER_MARK;
	}
	else
	{
	    size = rcvdb[index].pending;
	}
	error = send(rcvdb[index].sockfd, random_buffer, size, 0);
	if (error == -1)
	{
	    perror("try_pending");
	    clean_exit(1);
	}
	rcvdb[index].pending -= error;
	total_size += error;
//	printf("Total: %d, Pending: %d\n", total_size, rcvdb[index].pending);
	remove_pending(index);
426
    }
427
428
}

Junxing Zhang's avatar
Junxing Zhang committed
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
void print_header(char *buf){
  int i, j, len=14;

  printf("Buffer header len: %d \n", len);
  for (i=0; i<len; i++){
    j = buf[i] & 0x000000ff;
    printf("%d: %u \n", i, buf[i]);
  }
}

int recv_all(int sockfd, char *buf, int size){
  int numbytes, nleft;
  char *next;

  next = buf;
  nleft= size;
  while (nleft > 0) {
    if ((numbytes=recv(sockfd, next, nleft, 0)) == -1) {
      perror("recv_all(): recv");
      clean_exit(1);
    }      
    if ( numbytes == 0) return 0;
    nleft -= numbytes;
    next  += numbytes;
  }
454
  if (flag_debug) printf("recv_all(): from sockfd %d \n", sockfd);
Junxing Zhang's avatar
Junxing Zhang committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
  return size;
}

int send_all(int sockfd, char *buf, int size) { 
  int total = 0; // how many bytes we have sent 
  int bytesleft = size; // how many we have left to send 
  int n; 

  while(total < size) { 
    if ((n = send(sockfd, buf+total, bytesleft, 0)) == -1) {   
      if (errno == ECONNRESET) { //receivor closed the connection
	return 0;
      }
      perror("send_all(): send");
      clean_exit(1);      
    } 
    total += n; 
    bytesleft -= n; 
  } 
474
  if (flag_debug) printf("send_all(): to sockfd %d \n", sockfd);
Junxing Zhang's avatar
Junxing Zhang committed
475
476
477
478
479
480
  return size; 
}

void receive_sender(int i) {
  char inbuf[MAX_PAYLOAD_SIZE];

481
482
483
  if (recv(snddb[i].sockfd, inbuf, MAX_PAYLOAD_SIZE, 0)== 0) { //connection closed
    snddb[i].valid = 0; //no additional clean-up because no other state varialbe is related
    FD_CLR(snddb[i].sockfd, &read_fds);
Junxing Zhang's avatar
Junxing Zhang committed
484
485
486
  }
}

487

488
void send_receiver(unsigned long destaddr, long size, fd_set * write_fds_copy){
489
  int index;
Junxing Zhang's avatar
Junxing Zhang committed
490
  int sockfd;
491
492
  int error = 1, retry=0;
  struct in_addr addr;
Junxing Zhang's avatar
Junxing Zhang committed
493

494
  index = get_rcvdb_index(destaddr);
495
496
  sockfd= rcvdb[index].sockfd;

497
498
  if (size <= 0) {
    size = 1;
499
500
  }
  if (rcvdb[index].pending > 0) {
501
    add_pending(index, size);
502
503
    return;
  }
504
505
506
  if (size > MAX_PAYLOAD_SIZE){
    add_pending(index, size - MAX_PAYLOAD_SIZE);
    size = MAX_PAYLOAD_SIZE;
507
  }
Junxing Zhang's avatar
Junxing Zhang committed
508

509
  error = send(sockfd, random_buffer, size, MSG_DONTWAIT);
510
511
  // Handle failed connection
  while (error == -1 && errno == ECONNRESET && retry < 3) {
512
513
514
    // TODO: Think hard about what resetting a connection means for sniffing
    // traffic.

515
516
517
518
519
520
521
    //reset the related state variables
    int pending = rcvdb[index].pending;
    sniff_rcvdb[index].start = 0;
    sniff_rcvdb[index].end   = 0;
    throughput[index].isValid   = 0;
    FD_CLR(rcvdb[index].sockfd, &write_fds);
    reset_rcv_entry(index);
522
    //try again
523
    index = get_rcvdb_index(destaddr);
524
    rcvdb[index].pending = pending;
Junxing Zhang's avatar
Junxing Zhang committed
525
    sockfd= rcvdb[index].sockfd;
526
    error = send(sockfd, random_buffer, size, MSG_DONTWAIT);
527
    retry++;
528
529
530
  }
  //if still disconnected, reset
  if (error == -1 && errno == ECONNRESET) {
531
532
    rcvdb[index].valid = 0;
    addr.s_addr = destaddr;
533
    printf("Error: send_receiver() - failed send to %s three times. \n", inet_ntoa(addr)); 
534
535
  }
  else if (error == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
536
    add_pending(index, size);
537
538
539
540
541
542
543
  }
  else if (error == -1) {
    perror("send_receiver: send");
    clean_exit(1);
  }
  else {
    total_size += error;
544
545
//    printf("Total: %d, Pending: %d\n", total_size, rcvdb[index].pending);
    add_pending(index, size - error);
Junxing Zhang's avatar
Junxing Zhang committed
546
547
548
  }
}

549
int receive_monitor(int sockfd, struct timeval * deadline) {
550
551
552
  char buf[MAX_PAYLOAD_SIZE];
  char *nextptr;
  unsigned long tmpulong, destnum;
553
  char * packet_buffer = NULL;
Junxing Zhang's avatar
Junxing Zhang committed
554
555
556
557
558

  //receive first two longs
  if (recv_all(sockfd, buf, 2*SIZEOF_LONG)==0) {
    return 0;
  }
559
560
561
562
563
  nextptr = buf+SIZEOF_LONG;
  memcpy(&tmpulong, nextptr, SIZEOF_LONG);
  destnum = ntohl(tmpulong);
  packet_buffer = malloc(destnum*3*SIZEOF_LONG);

Junxing Zhang's avatar
Junxing Zhang committed
564
565
566
567
568
  //return success if no dest addr is given
  if (destnum == 0){
    return 1;
  }
  //otherwise, receive dest addrs
569
  if (recv_all(sockfd, packet_buffer, destnum*3*SIZEOF_LONG)==0) {
570
    free(packet_buffer);
Junxing Zhang's avatar
Junxing Zhang committed
571
572
    return 0;
  }
573
574
575
576
  if (!packet_buffer_more())
  {
    gettimeofday(deadline, NULL);
  }
577
  packet_buffer_add(packet_buffer, destnum*3*SIZEOF_LONG);
578

579
580
581
582
583
584
585
//  nextptr=buf;
//  for (i=0; i<destnum; i++){
//    memcpy(&tmpulong, nextptr, SIZEOF_LONG);
//    destaddr = tmpulong; //address should stay in Network Order!
//    nextptr += SIZEOF_LONG;
//    send_receiver(destaddr, buf);
//  } //for
586

Junxing Zhang's avatar
Junxing Zhang committed
587
588
589
  return 1;
}

590
591
592
int send_monitor(int sockfd) {
  char outbuf_delay[3*SIZEOF_LONG], outbuf_loss[3*SIZEOF_LONG], outbuf_bandwidth[3*SIZEOF_LONG];
  char *outbuf_delaylist;
593
  unsigned long tmpulong, loss_rate;
594
595
  int i, delaylist_size;
  unsigned int through;
Junxing Zhang's avatar
Junxing Zhang committed
596

597
598
599
600
601
602
  tmpulong = htonl(CODE_DELAY);
  memcpy(outbuf_delay+SIZEOF_LONG, &tmpulong, SIZEOF_LONG);
  tmpulong = htonl(CODE_LOSS);
  memcpy(outbuf_loss+SIZEOF_LONG, &tmpulong, SIZEOF_LONG);
  tmpulong = htonl(CODE_BANDWIDTH);
  memcpy(outbuf_bandwidth+SIZEOF_LONG, &tmpulong, SIZEOF_LONG);
Junxing Zhang's avatar
Junxing Zhang committed
603

604
605
606
607
608
609
610
611
612
613
614
615
616
617
  for (i=0; i<CONCURRENT_RECEIVERS; i++){
    if (rcvdb[i].valid == 1) {
      //send available bandwidth
      through = throughputTick(&throughput[i]);
      if (through != last_through[i]) {
	memcpy(outbuf_bandwidth, &(rcvdb[i].ip), SIZEOF_LONG); //the receiver ip
	tmpulong = htonl(through); //convert through
	memcpy(outbuf_bandwidth+SIZEOF_LONG+SIZEOF_LONG, &tmpulong, SIZEOF_LONG);
	if (send_all(sockfd, outbuf_bandwidth, 3*SIZEOF_LONG) == 0){
	  return 0;
	}
	last_through[i] = through;	
	printf("Sent throughput(kbps): %u\n", through);
      } //if measurement changed since last send
618

619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
      //send delay
      //printf("delays: %ld last: %ld\n", delays[i], last_delays[i]);     
      if (delays[i] != last_delays[i]) {
	memcpy(outbuf_delay, &(rcvdb[i].ip), SIZEOF_LONG); //the receiver ip
	tmpulong = htonl(delays[i]);
	memcpy(outbuf_delay+SIZEOF_LONG+SIZEOF_LONG, &tmpulong, SIZEOF_LONG);
	if (send_all(sockfd, outbuf_delay, 3*SIZEOF_LONG) == 0){
	  return 0;
	}
	last_delays[i] = delays[i];	
	printf("Sent delay(ms): %ld\n", delays[i]);	
      } //if measurement changed since last send

      //send delay list
      outbuf_delaylist = remove_delay_samples(i, &delaylist_size);
      if (outbuf_delaylist != NULL) {
	if (send_all(sockfd, outbuf_delaylist, delaylist_size) == 0){
	  return 0;
	}
	printf("Sent a delay list.\n");	
      } //if there are new delay samples measured in this quantum

      //send loss
      if (loss_records[i].total_counter == 0){
	loss_rate = 0;
      } else {
	loss_rate = floor(loss_records[i].loss_counter*1000000000.0f/loss_records[i].total_counter+0.5f); //loss per billion
      }
      if (loss_rate != last_loss_rates[i]) {
	memcpy(outbuf_loss, &(rcvdb[i].ip), SIZEOF_LONG); //the receiver ip
	tmpulong = htonl(loss_rate);
	memcpy(outbuf_loss+SIZEOF_LONG+SIZEOF_LONG, &tmpulong, SIZEOF_LONG);
	if (send_all(sockfd, outbuf_loss, 3*SIZEOF_LONG) == 0){
	  return 0;
	}
	last_loss_rates[i] = loss_rate;	
	printf("Sent loss: %d/%d=%ld \n", loss_records[i].loss_counter, loss_records[i].total_counter, loss_rate);	
      } //if measurement changed since last send
      loss_records[i].loss_counter=0;
      loss_records[i].total_counter=0;
      

    } //if connection is valid
  } //for 
  return 1;
664
665
}

666
667
668
669
670
671
void print_measurements(void) {
  float loss_rate;
  int i;

  for (i=0; i<CONCURRENT_RECEIVERS; i++){
    if (rcvdb[i].valid == 1) {     
672
673
674
      // Note, this has to be done before throughputTick, since that
      // obliterates the byte count
      unsigned int bytes = bytesThisTick(&throughput[i]);
675
      unsigned int through = throughputTick(&throughput[i]);
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
      if (flag_testmode) {
          // We might need to do a state transition
          if (test_state == TEST_NOTSTARTED && bytes > 0) {
              test_state = TEST_RUNNING;
          } else if (test_state == TEST_RUNNING && bytes == 0) {
              test_state = TEST_DONE;
          }
      }

      // Decide if we're going to print this quanta
      short print;
      if (flag_testmode && test_state != TEST_RUNNING) {
          print = 0;
      } else {
          print = 1;
      }

      if (print) printf("Throughput(kbps) = %u\n", through);
      if (print) printf("Bytecount = %u\n", bytes);
      total_bytes += bytes;
696
697
698
699

      //print delay
      if (delays[i] != last_delays[i]) {
	last_delays[i] = delays[i];	
700
	if (print) printf("New delay: %ld\n", delays[i]);	
701
702
703
704
705
706
707
708
709
710
711
712
      } else {
	if (flag_debug) printf("Unchanged delay: %ld\n", delays[i]);	
      }

      //print loss
      if (loss_records[i].total_counter == 0){
	loss_rate = 0;
      } else {
	loss_rate = (float)loss_records[i].loss_counter/loss_records[i].total_counter; //float loss
      }
      if (loss_rate != last_loss_rates[i]) {
	last_loss_rates[i] = loss_rate;	
713
	if (print) printf("New loss: %d/%d=%f \n", loss_records[i].loss_counter, loss_records[i].total_counter, loss_rate);	
714
715
716
717
718
719
720
721
722
723
      } else {
	if (flag_debug) printf("Unchanged loss: %f \n", loss_rate);     
      }
      loss_records[i].loss_counter=0;
      loss_records[i].total_counter=0;      

    } //if connection is valid
  } //for 
}

724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
void handle_packet_buffer(struct timeval * deadline, fd_set * write_fds_copy)
{
  struct timeval now;
  packet_info packet;
  gettimeofday(&now, NULL);

  if (packet_buffer_more())
  {
    packet = packet_buffer_front();
  }
  while (packet_buffer_more() && (deadline->tv_sec < now.tv_sec ||
        (deadline->tv_sec == now.tv_sec && deadline->tv_usec < now.tv_usec)))
  {
//    struct in_addr debug_temp;
//    debug_temp.s_addr = packet.ip;
//    printf("Sending packet to %s of size %ld\n", inet_ntoa(debug_temp),
//           packet.size);

742
    send_receiver(packet.ip, packet.size, write_fds_copy);
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757

    packet_buffer_advance();
    if (packet_buffer_more())
    {
      packet = packet_buffer_front(); 
      deadline->tv_usec += packet.delta * 1000;
      if (deadline->tv_usec > 1000000)
      { 
        deadline->tv_sec += deadline->tv_usec / 1000000;
        deadline->tv_usec = deadline->tv_usec % 1000000; 
      } 
    }
  }
}

Junxing Zhang's avatar
Junxing Zhang committed
758
759
int have_time(struct timeval *start_tvp, struct timeval *left_tvp){
  struct timeval current_tv;
Junxing Zhang's avatar
Junxing Zhang committed
760
  long long   left_usec, past_usec; //64-bit integer
Junxing Zhang's avatar
Junxing Zhang committed
761
762

  gettimeofday(&current_tv, NULL);
Junxing Zhang's avatar
Junxing Zhang committed
763
  past_usec = ((long long)(current_tv.tv_sec-start_tvp->tv_sec))*1000000+
Junxing Zhang's avatar
Junxing Zhang committed
764
    (current_tv.tv_usec-start_tvp->tv_usec);
Junxing Zhang's avatar
Junxing Zhang committed
765
  left_usec = QUANTA*1000-past_usec; //QUANTA is in msec
Junxing Zhang's avatar
Junxing Zhang committed
766
767
768
769
770
771
772
773
  if (left_usec > 0) {
    left_tvp->tv_sec = left_usec/1000000;
    left_tvp->tv_usec= left_usec%1000000;
    return 1;
  }
  return 0;
}

774
void usage() {
775
  fprintf(stderr,"Usage: stubd [-t] [-d] [-s] <sniff-interface> [remote_IPaddr]\n");
776
777
  fprintf(stderr,"       -d:  Enable debugging mode\n");
  fprintf(stderr,"       -s:  Enable standalone mode\n");
778
  fprintf(stderr,"       -t:  Enable testing mode\n");
779
780
781
  fprintf(stderr," remote_IPaddr is mandatory when using -s\n");
}

782
int main(int argc, char *argv[]) {
Junxing Zhang's avatar
Junxing Zhang committed
783
784
785
786
787
788
  int sockfd_snd, sockfd_rcv_sender, sockfd_rcv_monitor, sockfd_monitor=-1;  
  struct sockaddr_in my_addr;	// my address information
  struct sockaddr_in their_addr; // connector's address information
  fd_set read_fds_copy, write_fds_copy;
  socklen_t sin_size;
  struct timeval start_tv, left_tv;
789
  int yes=1, i, flag_send_monitor=0;
790
  struct timeval packet_deadline;
791
792
793
  struct in_addr addr;
  int flag_measure=0;
  char ch;
794
  unsigned long quantum_no=0;
795
796

  gettimeofday(&packet_deadline, NULL);
797
  init();
798
799
800
801
802
803

  //set up debug flag
  if (getenv("Debug")!=NULL) 
    flag_debug=1;
  else 
    flag_debug=0;
804
805
806
807
808
  flag_standalone = 0;

  /*
   * Process command-line arguments
   */
809
  while ((ch = getopt(argc,argv,"dst")) != -1) {
810
811
812
813
814
    switch (ch) {
      case 'd':
        flag_debug = 1; break;
      case 's':
        flag_standalone = 1; break;
815
816
      case 't':
        flag_testmode = 1; break;
817
818
819
820
821
822
823
      default:
        fprintf(stderr,"Unknown option %c\n",ch);
        usage(); exit(1);
    }
  }
  argc -= optind;
  argv += optind;
Junxing Zhang's avatar
Junxing Zhang committed
824

825
826
827
828
829
830
831
832
833
834
835
836
837
  if (flag_standalone) {
    if (argc != 2) {
      fprintf(stderr,"Wrong number of options for standalone: %i\n",argc);
      usage();
      exit(1);
    } else {
      flag_measure = 1;
      rcvdb[0].valid = 1;
      inet_aton(argv[1], &addr);
      rcvdb[0].ip    =  addr.s_addr;
      rcvdb[0].sockfd= -1; //show error if used
      rcvdb[0].last_usetime = time(NULL);
    }
838
    printf("Running in standalone mode\n");
839
840
841
842
843
844
  } else {
    if (argc != 1) {
      fprintf(stderr,"Wrong number of options: %i\n",argc);
      usage();
      exit(1);
    }
845
  }
846
847
848
849
850
851

  if (flag_testmode) {
      printf("Running in testmode\n");
      test_state = TEST_NOTSTARTED;
  }

852
  if (strlen(argv[0]) > 127) {
853
854
855
856
    fprintf(stderr,"Error: the <sniff-interface> name must be less than 127 characters \n");
    exit(1);
  }

857
  strcpy(sniff_interface, argv[0]);
858
859


Junxing Zhang's avatar
Junxing Zhang committed
860
861
862
863
864
865
866
867
868
869
870
871
872
  //set up the sender connection listener
  if ((sockfd_rcv_sender = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1);
  }
  if (setsockopt(sockfd_rcv_sender, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
    perror("setsockopt");
    exit(1);
  }  
  my_addr.sin_family = AF_INET;		  // host byte order
  my_addr.sin_port = htons(SENDER_PORT);  // short, network byte order
  my_addr.sin_addr.s_addr = INADDR_ANY;   // automatically fill with my IP
  memset(&(my_addr.sin_zero), '\0', 8);   // zero the rest of the struct
873
  if (flag_debug) printf("Listen on %s\n",inet_ntoa(my_addr.sin_addr));  
Junxing Zhang's avatar
Junxing Zhang committed
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
  if (bind(sockfd_rcv_sender, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
    perror("bind");
    exit(1);
  }  
  if (listen(sockfd_rcv_sender, PENDING_CONNECTIONS) == -1) {
    perror("listen");
    exit(1);
  }

  //set up the monitor connection listener
  if ((sockfd_rcv_monitor = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1);
  }
  if (setsockopt(sockfd_rcv_monitor, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
    perror("setsockopt");
    exit(1);
  }  
  my_addr.sin_family = AF_INET;		  // host byte order
  my_addr.sin_port = htons(MONITOR_PORT); // short, network byte order
  my_addr.sin_addr.s_addr = INADDR_ANY;   // automatically fill with my IP
  memset(&(my_addr.sin_zero), '\0', 8);   // zero the rest of the struct
896
  if (flag_debug) printf("Listen on %s\n",inet_ntoa(my_addr.sin_addr));  
Junxing Zhang's avatar
Junxing Zhang committed
897
898
899
900
901
902
903
904
905
906
  if (bind(sockfd_rcv_monitor, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
    perror("bind");
    exit(1);
  }  
  if (listen(sockfd_rcv_monitor, 1) == -1) {
    perror("listen");
    exit(1);
  }

  //initialization
907
908
  packet_buffer_init();
  init_random_buffer();
Junxing Zhang's avatar
Junxing Zhang committed
909
  init_pcap(SNIFF_TIMEOUT);
Junxing Zhang's avatar
Junxing Zhang committed
910
911
912
913
  FD_ZERO(&read_fds);
  FD_ZERO(&read_fds_copy);
  FD_ZERO(&write_fds);
  FD_ZERO(&write_fds_copy);
Junxing Zhang's avatar
Junxing Zhang committed
914
  FD_SET(pcapfd,  &read_fds);
Junxing Zhang's avatar
Junxing Zhang committed
915
916
  FD_SET(sockfd_rcv_sender,  &read_fds);
  FD_SET(sockfd_rcv_monitor, &read_fds);
Junxing Zhang's avatar
Junxing Zhang committed
917
  maxfd = pcapfd; //socket order
Junxing Zhang's avatar
Junxing Zhang committed
918
919
920
921
922
923
924
  sin_size = sizeof(struct sockaddr_in);

  //main loop - the stubd runs forever
  while (1) {
    flag_send_monitor=0; //reset flag for each quanta
    gettimeofday(&start_tv, NULL); //reset start time for each quanta

925
926
927
928
    printf("Total: %d\n", total_size);
    printf("========== Quantum %lu ==========\n", quantum_no);
    quantum_no++;

Junxing Zhang's avatar
Junxing Zhang committed
929
930
931
932
933
934
935
936
937
    //while in a quanta
    while(have_time(&start_tv, &left_tv)) {  
      read_fds_copy  = read_fds;
      write_fds_copy = write_fds;

      if (select(maxfd+1, &read_fds_copy, &write_fds_copy, NULL, &left_tv) == -1) { 
	perror("select"); 
	clean_exit(1); 
      }
938
939
940

      // Send out packets to our peers if the deadline has passed.
      handle_packet_buffer(&packet_deadline, &write_fds_copy);
941
      
942
      //receive from existent senders
Junxing Zhang's avatar
Junxing Zhang committed
943
      for (i=0; i<CONCURRENT_SENDERS; i++){
944
	// Send pending data if it exists.
945
        try_pending(i, &write_fds_copy);
Junxing Zhang's avatar
Junxing Zhang committed
946
947
948
949
	if (snddb[i].valid==1 && FD_ISSET(snddb[i].sockfd, &read_fds_copy)) {	
	  receive_sender(i);
	} 
      }
950
      
Junxing Zhang's avatar
Junxing Zhang committed
951
952
953
954
955
956
      //handle new senders 
      if (FD_ISSET(sockfd_rcv_sender, &read_fds_copy)) { 
	if ((sockfd_snd = accept(sockfd_rcv_sender, (struct sockaddr *)&their_addr, &sin_size)) == -1) { 
	  perror("accept"); 
	  continue;
	} else {
957
958
959
960
961
	  insert_db(their_addr.sin_addr.s_addr, sockfd_snd, 1); //insert snddb
	  FD_SET(sockfd_snd, &read_fds); // add to master set 
	  if (sockfd_snd > maxfd) { // keep track of the maximum 
	    maxfd = sockfd_snd; 
	  } 
962
	  if (flag_debug) printf("server: got connection from %s\n",inet_ntoa(their_addr.sin_addr));
Junxing Zhang's avatar
Junxing Zhang committed
963
964
	} 
      }
965
      
Junxing Zhang's avatar
Junxing Zhang committed
966
967
968
969
970
971
972
973
974
975
976
977
      //handle the new monitor
      if (FD_ISSET(sockfd_rcv_monitor, &read_fds_copy)) {  
	if ((sockfd_monitor = accept(sockfd_rcv_monitor, (struct sockaddr *)&their_addr, &sin_size)) == -1) { 
	  perror("accept"); 
	  continue;
	} else {
	  FD_CLR(sockfd_rcv_monitor, &read_fds);  //allow only one monitor connection	  
	  FD_SET(sockfd_monitor, &read_fds);  //check the monitor connection for read
	  FD_SET(sockfd_monitor, &write_fds); //check the monitor connection for write
	  if (sockfd_monitor > maxfd) { //keep track of the maximum 
	    maxfd = sockfd_monitor; 
	  } 
978
	  if (flag_debug) printf("server: got connection from %s\n",inet_ntoa(their_addr.sin_addr));
Junxing Zhang's avatar
Junxing Zhang committed
979
980
981
982
983
	} 
      }

      //receive from the monitor
      if (sockfd_monitor!=-1 && FD_ISSET(sockfd_monitor, &read_fds_copy)) { 
984
	if (receive_monitor(sockfd_monitor, &packet_deadline) == 0) { //socket_monitor closed by peer
Junxing Zhang's avatar
Junxing Zhang committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
	  FD_CLR(sockfd_monitor, &read_fds); //stop checking the monitor socket
	  FD_CLR(sockfd_monitor, &write_fds);
	  sockfd_monitor = -1;
	  FD_SET(sockfd_rcv_monitor, &read_fds); //start checking the receiver control socket
	  if (sockfd_rcv_monitor > maxfd) { // keep track of the maximum 
	    maxfd = sockfd_rcv_monitor; 
	  } 	 	  
	} 
      }

      //send measurements to the monitor once in each quanta
      if (sockfd_monitor!=-1 && flag_send_monitor==0 && FD_ISSET(sockfd_monitor, &write_fds_copy)) {  	
	if (send_monitor(sockfd_monitor) == 0) { //socket_monitor closed by peer
	  FD_CLR(sockfd_monitor, &read_fds); //stop checking the monitor socket
	  FD_CLR(sockfd_monitor, &write_fds);
	  sockfd_monitor = -1;
	  FD_SET(sockfd_rcv_monitor, &read_fds); //start checking the receiver control socket
	  if (sockfd_rcv_monitor > maxfd) { // keep track of the maximum 
	    maxfd = sockfd_rcv_monitor; 
	  } 	 	  
	} else {
	  flag_send_monitor=1;
	}
      }
1009
         
1010
      //sniff packets
Junxing Zhang's avatar
Junxing Zhang committed
1011
1012
      if (FD_ISSET(pcapfd, &read_fds_copy)) { 
	sniff();     
Junxing Zhang's avatar
Junxing Zhang committed
1013
      }
1014

Junxing Zhang's avatar
Junxing Zhang committed
1015
    } //while in quanta
1016
1017

    // In testmode, we only start printing in the quanta we first see a packet
1018
1019
1020
    if (flag_standalone) {
      print_measurements();
    }
1021
1022
1023
1024
1025
1026
1027
    
    // If running in testmode, and the test is over, exit!
    if (flag_testmode && test_state == TEST_DONE) {
      printf("Test done - total bytes transmitted: %llu\n",total_bytes);
      break;
    }
     
Junxing Zhang's avatar
Junxing Zhang committed
1028
  } //while forever
1029
1030
1031

  packet_buffer_cleanup(); 

Junxing Zhang's avatar
Junxing Zhang committed
1032
1033
1034
  return 0;
}