Palacios Public Git Repository

To checkout Palacios execute

  git clone http://v3vee.org/palacios/palacios.web/palacios.git
This will give you the master branch. You probably want the devel branch or one of the release branches. To switch to the devel branch, simply execute
  cd palacios
  git checkout --track -b devel origin/devel
The other branches are similar.


Checked in Vnet code
[palacios.git] / palacios / src / devices / vnet.c
1 /* 
2  * This file is part of the Palacios Virtual Machine Monitor developed
3  * by the V3VEE Project with funding from the United States National 
4  * Science Foundation and the Department of Energy.  
5  *
6  * The V3VEE Project is a joint project between Northwestern University
7  * and the University of New Mexico.  You can find out more at 
8  * http://www.v3vee.org
9  *
10  * Copyright (c) 2009, Lei Xia <lxia@northwestern.edu> 
11  * Copyright (c) 2009, Yuan Tang <ytang@northwestern.edu> 
12  * Copyright (c) 2009, Jack Lange <jarusl@cs.northwestern.edu> 
13  * Copyright (c) 2009, Peter Dinda <pdinda@northwestern.edu
14  * Copyright (c) 2009, The V3VEE Project <http://www.v3vee.org> 
15  * All rights reserved.
16  *
17  * Author: Lei Xia <lxia@northwestern.edu>
18  *            Yuan Tang <ytang@northwestern.edu>
19  *                Jack Lange <jarusl@cs.northwestern.edu> 
20  *                Peter Dinda <pdinda@northwestern.edu
21  *
22  * This is free software.  You are permitted to use,
23  * redistribute, and modify it as specified in the file "V3VEE_LICENSE".
24  */
25
26 #include <devices/vnet.h>
27
28 #define MAX_ADDRESS 10
29 typedef enum {LOCAL,REMOTE} ctype;
30
31 struct handler{
32   int    fd;
33   int local_address;
34   short  local_port;
35   struct vnet_device *local_device;
36   int remote_address;
37   short  remote_port;
38   struct vnet_device *remote_device;
39   struct ethAddr addresses[MAX_ADDRESS];
40   ctype local_config;
41   ctype remote_config; 
42 };
43
44
45 typedef struct {
46   int  size;
47   char  data[ETHERNET_PACKET_LEN];
48   int index;
49 }RawEthernetPacket;
50
51
52 #define NUM_DEVICES 1
53 #define NUM_HANDLERS 1
54
55 static struct vnet_device *available_devices[NUM_DEVICES];
56
57 struct handler *active_handlers[NUM_HANDLERS];
58
59 static int bind_address = 0;
60 static short  bind_port = 22;
61 //static char *vnet_version = "0.9";
62 static int vnet_server = 0;
63 static bool use_tcp = false;
64
65
66
67 static void print_packet(char *pkt, int size)
68 {
69       int i;
70            
71         PrintDebug("Vnet: packet: size: %d\n", size);
72         for (i = 0; i < size; i ++)
73                 PrintDebug("%x ", pkt[i]);
74         PrintDebug("\n");
75 }
76
77
78 #if !(ROUTE)
79 static struct vnet_device *get_device(RawEthernetPacket *pt)
80 {
81         return available_devices[0];
82 }
83 #endif
84
85 static struct handler * get_handler()
86 {
87         
88         return active_handlers[0];
89 }
90
91 static inline bool add_handler(struct handler *hd)
92 {
93        int num = 0;
94            
95         while (active_handlers[num] != NULL) num ++;
96
97         if (num >= NUM_HANDLERS)
98                 return false;
99
100         active_handlers[num] = hd;
101
102         return true;
103 }
104
105 static inline bool add_device(struct vnet_device *dev)
106 {
107        int num = 0;
108            
109         while (available_devices[num] != NULL) num ++;
110
111         if (num >= NUM_DEVICES)
112                 return false;
113
114         available_devices[num] = dev;
115
116         return true;
117 }
118
119
120 int CreateAndSetupTcpSocket(const int bufsize, const bool nodelay, const bool nonblocking)
121 {
122   int mysocket;
123
124   // create socket for connections
125   if ((mysocket = V3_Create_TCP_Socket()) < 0) {
126     return -1;
127   }
128
129   return mysocket;
130 }
131
132 int BindSocketwPort(const int mysocket, const int myport)
133 {
134    if (V3_Bind_Socket(mysocket, myport) < 0) {
135     return -1;
136   }
137   
138   return 0;
139 }  
140
141 int ListenSocket(const int mysocket, const int maxc)
142 {
143   return V3_Listen_Socket(mysocket, maxc);
144 }
145
146 int ConnectToHost(const int mysocket, const int hostip, const int port)
147 {
148   return V3_Connect_To_IP(mysocket, hostip, port);
149 }
150
151 /*
152 void close(int mysocket)
153 {
154   V3_Close_Socket(mysocket);
155 }
156 */
157
158 #if 0 //May be needed later
159 int SendTo(int const mysocket, 
160            const unsigned ip, const int port, 
161            const char *buf, const int len, const bool sendall)
162 {
163   int left;
164   int sent;
165
166   if (!sendall) {
167     return V3_SendTo_IP(mysocket, ip, port, buf, len);
168   } else {
169     left = len;
170
171     while (left>0) {
172       sent = V3_SendTo_IP(mysocket, ip, port, buf, len);
173       if (sent < 0) {   
174           return -1;
175       } else {
176         left-=sent;
177       }
178     }
179     return len;
180   }
181 }
182
183
184 int ReceiveFrom(const int mysocket, 
185                 const unsigned ip, const int port, 
186                 char *buf, const int len,
187                 const bool recvall)
188 {
189     int left;   
190     int received;
191   
192     if (!recvall) {
193        return V3_RecvFrom_IP(mysocket, ip, port, buf, len);
194     } else {
195        left = len;      
196
197        while (left > 0) {
198                 received = V3_RecvFrom_IP(mysocket, ip, port, buf, len);
199                 if (received < 0) {
200                         return -1;
201                 } else if (received == 0) {
202                         break;
203                 } else {        
204                         left -= received;
205                 }
206         }
207         
208         return len-left;
209     }
210 }
211
212
213 int Send(int socketfd, const char *buf, const int len, const bool sendall)
214 {
215   int left;
216   int sent;
217
218   if (!sendall) {
219       return V3_Send(socketfd, buf, len);
220   } else  {
221       left = len;
222          
223       while (left>0) {
224           sent = V3_Send(socketfd, &(buf[len-left]), left);
225
226           if (sent < 0) {
227               return -1;
228           } else if (sent == 0) {
229               break;
230           } else {
231               left -= sent;
232           }
233       }
234           
235       return len-left;
236   }
237 }
238
239 int GetLine(int fd, char *buf, int size)
240 {
241   int rc;
242   int received = 0;
243   char c;
244   
245   while (1) { 
246     rc = Receive(fd, &c, 1, true);
247     
248     if (rc < 0) { 
249       return rc;
250     } 
251         
252     if (rc == 0 || c == '\n') {
253       return received;
254     }
255         
256     buf[received] = c;
257     received += rc;
258
259     if (received >= size)
260         break;
261   }
262
263   return received;
264 }
265
266
267 int PutLine(int mysocket, char *buf, int size)
268 {
269   buf[size] = '\n';
270   return (Send(mysocket, buf, size+1, true) - 1);
271 }
272 #endif
273
274
275 static int readall(const int fd, char *buf, const int len, const int oneshot, const int awaitblock)
276 {
277   int rc;
278   int left;
279
280   left = len;
281   
282   while (left > 0) {
283     rc = V3_Recv(fd, &(buf[len-left]), left);
284         
285     if (oneshot) { 
286       return rc;
287     }
288         
289     if (rc <= 0) { 
290       return rc;
291     } else {
292       left -= rc;
293     }
294   }
295   
296   return len;
297 }
298
299 static int writeall(const int fd, const char *buf, const int len, const int oneshot, const int awaitblock)
300 {
301   int rc;
302   int left;
303
304   left = len;
305   
306   while (left > 0) {
307     rc = V3_Send(fd, &(buf[len-left]), left);
308
309     if (oneshot) { 
310       return rc;
311     }
312         
313     if (rc <= 0) { 
314       return rc;
315     } else {
316       left -= rc;
317     }
318   }
319   return len;
320 }
321
322 static void RawEthernetPacketInit(RawEthernetPacket *pt, const char *data, const size_t size)
323 {
324   pt->size = size;
325   memcpy(pt->data, data, size);
326 }
327
328 static bool RawEthernetPacketSerialize(RawEthernetPacket *pt, const int fd)
329 {
330   if (writeall(fd,(char*)&(pt->size),sizeof(pt->size),0,1)!=sizeof(pt->size)) 
331     {
332       PrintError("Vnet: Serialization Exception\n");
333       return false;
334     }
335   if (writeall(fd,pt->data,pt->size,0,1)!=(int)(pt->size))
336     {
337       PrintError("Vnet: Serialization Exception\n");
338       return false;
339     }
340
341   return true;
342 }
343
344 static bool RawEthernetPacketUnserialize(RawEthernetPacket *pt, const int fd)
345 {
346   if (readall(fd,(char*)&(pt->size),sizeof(pt->size),0,1) != sizeof(pt->size))
347     {
348       PrintError("Vnet: Unserialization Exception\n");
349       return false;
350     }
351   if (readall(fd,pt->data,pt->size,0,1) != pt->size)
352     {
353       PrintError("Vnet: Unserialization Exception\n");
354       return false;
355     }
356
357   return true;
358 }
359
360 static bool RawEthernetPacketSendUdp(RawEthernetPacket *pt, int sock_fd, int ip, short port)
361 {
362   int size;
363
364   PrintDebug("Vnet: sending by UDP socket %d  ip: %x,  port: %d\n", sock_fd, ip, port);
365   
366   if ((size = V3_SendTo_IP(sock_fd, ip, port, pt->data, pt->size)) != pt->size) 
367     {
368       PrintError("Vnet: sending by UDP Exception, %x\n", size);
369       return false;
370     }
371  
372   return true;
373 }
374
375
376 #if 0
377 static void print_packet_addr(char *pkt)
378 {
379        int i;
380            
381         PrintDebug("Vnet: print_packet_destination_addr: ");
382         for (i = 8; i < 14; i ++)
383                 PrintDebug("%x ", pkt[i]);
384         PrintDebug("\n");
385         
386         PrintDebug("Vnet: print_packet_source_addr: ");
387         for (i = 14; i < 20; i ++)
388                 PrintDebug("%x ", pkt[i]);
389         PrintDebug("\n");
390 }
391
392 /*
393 static void print_device_addr(char *ethaddr)
394 {
395       int i;
396            
397         PrintDebug("Vnet: print_device_addr: ");
398         for (i = 0; i < 6; i ++)
399                 PrintDebug("%x ", ethaddr[i]);
400         PrintDebug("\n");
401 }
402 */
403 #endif
404
405
406 #if ROUTE  //new routing accrding to VNET-VTL, no hash --TY
407
408 struct topology g_links[MAX_LINKS];
409 int g_num_links; //The current number of links
410 int g_first_link;
411 int g_last_link;
412
413 struct routing g_routes[MAX_ROUTES];
414 int g_num_routes; //The current number of routes
415 int g_first_route;
416 int g_last_route;
417
418 struct device_list g_devices[MAX_DEVICES];
419 int g_num_devices;
420 int g_first_device;
421 int g_last_device;
422
423 #define in_range(c, lo, up)  ((char)c >= lo && (char)c <= up)
424 #define islower(c)           in_range(c, 'a', 'z')
425
426 //------------------hash function begin-------------------
427
428 #define HASH_KEY_SIZE 16
429 /* Hash key format:
430  * 0-5:     src_eth_addr
431  * 6-11:    dest_eth_addr
432  * 12:      src type
433  * 13-16:   src index
434  */
435  struct hash_key
436 {
437         char *key_from_addr;
438 };
439
440 struct hash_value  // This is the hash value, defined as a dynamic array. Format: 0: num_matched_routes, 1...n: matches[] -- TY
441 {
442         int num_matched_routes;
443         int *matches; 
444 };
445 /*
446     static int insert_some (struct hashtable * htable, struct hash_key *key, struct hash_value *value) { 
447         return hashtable_insert(htable, (addr_t)key, (addr_t)value);    
448     }
449 */
450
451 DEFINE_HASHTABLE_INSERT(insert_some, struct hash_key *, struct hash_value *);
452 DEFINE_HASHTABLE_SEARCH(search_some, struct hash_key *, struct hash_value);
453 //DEFINE_HASHTABLE_REMOVE(remove_some, struct hash_key *, struct hash_value, 1);
454 //DEFINE_HASHTABLE_ITERATOR_SEARCH(search_itr_some, struct key);
455
456 struct hash_key *cache_key;   //maybe these three variables should be defined as local variable. -- TY
457 struct hash_value *cache_entry;
458 struct hashtable *hash_route;
459
460 /*
461 malloc_key_value()
462 {
463 cache_key = (hash_key *)V3_Malloc(sizeof(hash_key));
464 addr_t key = *cache_key;
465 }
466 */
467  // This is the hash algorithm used for UNIX ELF object files
468 inline size_t hash_from_key(const char * arg) 
469 {
470     size_t hash = 0;
471     size_t temp = 0;
472
473     int i;
474     for(i = 0; i < HASH_KEY_SIZE; i++) {
475       hash = (hash << 4) + *(arg + i) + i;
476       if ((temp = (hash & 0xF0000000))) {
477         hash ^= (temp >> 24);
478       }
479       hash &= ~temp;
480     }
481     PrintDebug("Hash Value: %lu\n", (unsigned long)hash);
482     return hash;
483 }
484
485 inline bool hash_key_equal(const char * left, const char * right)
486 {
487       int i;
488       for(i = 0; i < HASH_KEY_SIZE; i++) {
489       if (left[i] != right[i]) {
490         PrintDebug("HASHes not equal\n");
491         return false;
492       }
493     }
494     return true;
495 }
496
497 void make_hash_key(char * hash_key, char src_addr[6], char dest_addr[6], char src_type, int src_index) {
498   int j;
499
500   for(j = 0; j < 6; j++) {
501     hash_key[j] = src_addr[j];
502     hash_key[j + 6] = dest_addr[j] + 1;
503   }
504
505   hash_key[12] = src_type;
506
507   *(int *)(hash_key + 12) = src_index;
508 }
509
510 int AddMatchedRoutesToCache(int num_matched_r, int * matches)
511 {
512         cache_entry->num_matched_routes = num_matched_r;
513         int i;
514         for(i = 0; i < num_matched_r; i++) {
515                 cache_entry->matches = (int *)V3_Malloc(sizeof(int));
516                 *(cache_entry->matches) = matches[i];
517         }
518         if (!insert_some(hash_route, cache_key, cache_entry)) return -1; /*oom*/
519         return 0;
520 }
521
522 void clear_hash_cache() 
523 {
524     hashtable_destroy(hash_route, 1, 1);  //maybe there are some problems.
525 /*       hashtable_destroy(hash_route, 1, 1);
526          hash_route = NULL;
527          V3_Free(cache_key);
528          V3_Free(cache_entry);
529          cache_key = NULL;
530          cache_entry = NULL;
531 */
532 }
533
534 //int LookIntoCache(char compare_address[HASH_KEY_SIZE], int * do_we_analyze, int * matches) {
535 int LookIntoCache(char compare_address[HASH_KEY_SIZE], int * matches) 
536 {
537   int n_matches = 0;
538   int i;
539   struct hash_value *found;
540
541   cache_key->key_from_addr = compare_address;
542   if (NULL != (found = search_some(hash_route, cache_key))) {
543     n_matches = found->num_matched_routes;
544     for (i = 0; i < found->num_matched_routes; i++) {
545       //*(matches+i) = *(found->matches+i);
546       matches[i] = found->matches[i];
547     }
548     return n_matches;
549   } else {
550     PrintDebug("VNET: LookIntoCache, hash key not found\n");
551     return -1;
552   }
553 }
554
555
556 //------------------hash function end-------------------
557
558 char vnet_toupper(char c)
559 {
560         if (islower(c))
561                 c -= 'a'-'A';
562         return c;
563 }
564
565 char hexnybbletonybble(const char hexnybble) {
566   char x = vnet_toupper(hexnybble);
567   if ((x >= '0') && (x <= '9')) {
568     return x - '0';
569   } else {
570     return 10 + (x - 'A');
571   }
572 }
573
574 void hexbytetobyte(const char hexbyte[2], char *byte) {
575   *byte = ((hexnybbletonybble(hexbyte[0]) << 4) + 
576            (hexnybbletonybble(hexbyte[1]) & 0xf));
577 }
578
579 char nybbletohexnybble(const char nybble) {
580   return (nybble >= 10) ? (nybble - 10 + 'A') : (nybble + '0');
581 }
582
583 void bytetohexbyte(const char byte, char hexbyte[2]) {
584   hexbyte[0] = nybbletohexnybble((byte >> 4) & 0xf);
585   hexbyte[1] = nybbletohexnybble(byte & 0xf);
586 }
587
588 void string_to_mac(const char * str, char mac[6]) {
589   int k;
590   for(k = 0; k < 6; k++) {
591     hexbytetobyte(&(str[(2 * k) + k]), mac + k);
592   }
593 }
594
595 void mac_to_string(char address[6], char * buf) {
596   int i;
597   for (i = 0; i < 6; i++) {
598     bytetohexbyte(address[i], &(buf[3 * i]));
599     buf[(3 * i) + 2] = ':';
600   }
601   buf[17] = 0;
602 }
603 /*
604 void ip_to_string(ulong_t addr, char * buf) {
605   struct in_addr addr_st;
606   char * tmp_str;
607
608   addr_st.s_addr = htonl(addr);
609   tmp_str = inet_ntoa(addr_st);
610
611   memcpy(buf, tmp_str, strlen(tmp_str));
612 }
613 */
614 int find_link_by_fd(SOCK sock) {
615   int i;
616
617   FOREACH_LINK(i, g_links, g_first_link) {
618     if (g_links[i].link_sock == sock) {
619       return i;
620     }
621   }
622
623   return -1;
624 }
625
626 int if_write_pkt(iface_t *iface, RawEthernetPacket *pkt)
627 {
628    iface->input((uchar_t *)pkt->data, pkt->size);
629    return 0;
630 }
631
632
633
634 //int add_link_entry(unsigned long dest, int type, int link_class, int data_port, int authenticated, SOCK fd) {
635 int add_link_entry(unsigned long dest, int type, int data_port,  SOCK fd) {
636   int i;
637
638   for(i = 0; i < MAX_LINKS; i++) {
639     if (g_links[i].use == 0) {
640       g_links[i].dest = dest;
641  //     g_links[i].authenticated = authenticated;
642       g_links[i].type = type;
643       g_links[i].link_sock = fd;
644       g_links[i].remote_port = data_port;
645       g_links[i].use = 1;
646  //     g_links[i].link_class = link_class;
647
648       if (g_first_link == -1) 
649         g_first_link = i;
650
651       g_links[i].prev = g_last_link;
652       g_links[i].next = -1;
653       
654       if (g_last_link != -1) {
655         g_links[g_last_link].next = i;
656       }
657
658       g_last_link = i;
659
660       g_num_links++;
661       return i;
662     }
663   }
664   return -1;
665 }
666
667
668
669
670 int add_sock(struct sock_list * socks, int  len, int * first_sock, int * last_sock, SOCK fd) {
671   int i;
672
673   for (i = 0; i < len; i++) {
674     if (socks[i].sock == -1) {
675       socks[i].sock = fd;
676
677       if (*first_sock == -1) 
678         *first_sock = i;
679
680       socks[i].prev = *last_sock;
681       socks[i].next = -1;
682
683       if (*last_sock != -1) 
684         socks[*last_sock].next = i;
685
686       *last_sock = i;
687
688       return i;
689     }
690   }
691   return -1;
692 }
693
694
695
696
697 int add_route_entry(char src_mac[6], char dest_mac[6], int src_mac_qual, int dest_mac_qual, int dest, int type, int src, int src_type) {
698   int i;
699
700   for(i = 0; i < MAX_ROUTES; i++) {
701     if (g_routes[i].use == 0) {
702      
703       if ((src_mac_qual != ANY_TYPE) && (src_mac_qual != NONE_TYPE)) {
704         memcpy(g_routes[i].src_mac, src_mac, 6);
705       } else {
706         memset(g_routes[i].src_mac, 0, 6);
707       }
708       
709       if ((dest_mac_qual != ANY_TYPE) && (dest_mac_qual != NONE_TYPE)) {
710         memcpy(g_routes[i].dest_mac, dest_mac, 6);
711       } else {
712         memset(g_routes[i].dest_mac, 0, 6);
713       }
714
715       g_routes[i].src_mac_qual = src_mac_qual;
716       g_routes[i].dest_mac_qual = dest_mac_qual;
717       g_routes[i].dest = dest;
718       g_routes[i].type = type;
719       g_routes[i].src = src;
720       g_routes[i].src_type = src_type;
721       
722       g_routes[i].use = 1;
723
724       if (g_first_route == -1) 
725         g_first_route = i;
726
727       g_routes[i].prev = g_last_route;
728       g_routes[i].next = -1;
729
730       if (g_last_route != -1) {
731         g_routes[g_last_route].next = i;
732       }
733
734       g_last_route = i;
735
736       g_num_routes++;
737       return i;
738     }
739   }
740   return -1;
741 }
742
743
744 /*
745  * This returns an integer, if the interger is negative then AddLink failed, else it was
746  * successful and returns the socket descriptor
747  */
748
749 #if 0
750 int AddLink(string input, SOCK * link_sock, string * ret_str) {
751   string output;
752   string hello, password, version, command;
753   string remote_address, type, remote_password;
754   int ctrl_port = 0;
755   int data_port = 0;
756   char buf[128];
757   
758   struct hostent * remote_he;
759   struct in_addr dest_addr;
760   unsigned long dest;
761
762   SOCK data_sock;
763   con_t ctrl_con;
764   int link_index;
765   int ret = CTRL_DO_NOTHING;
766
767   struct sockaddr_in local_address;
768   int local_port;
769
770   *link_sock = 0;
771
772   {
773           istringstream is(input,istringstream::in);
774     is >> hello >> password >> version >> command >> remote_address >> ctrl_port >> data_port >> remote_password >> type;
775   }
776
777
778   if ((remote_address.empty()) || (remote_password.empty()) ||  (type.empty()) || (ctrl_port == 0) || (data_port == 0)) {
779     *ret_str = "Invalid Addlink command";
780     return CTRL_ERROR;
781   }
782
783   if (get_tunnel_type(type) == -1) {
784     *ret_str = "Invalid link type";
785     return CTRL_ERROR;
786   }
787
788   if ((remote_he = gethostbyname(remote_address.c_str())) == NULL) {
789     *ret_str = "Could not lookup address of " + remote_address;
790     return CTRL_ERROR;
791   }
792
793   dest_addr = *((struct in_addr *)remote_he->h_addr);
794   dest = dest_addr.s_addr;
795   
796   link_index = find_link_entry(dest, get_tunnel_type(type));
797
798   if (link_index != -1) {
799     JRLDBG("Link already exists\n");
800     *ret_str = "Link already Exists";
801     return CTRL_ERROR;
802   }
803
804
805   if(type == TCP_STR) {
806     struct sockaddr_in serv_addr;
807
808     if ((data_sock = CreateAndSetupTcpSocket()) < 0) {
809       cerr << "the client descriptor could not be opened" << endl;
810       *ret_str = "Could not establish link";
811       return CTRL_ERROR;
812     }
813     
814     serv_addr.sin_family = AF_INET;
815     serv_addr.sin_port = htons(data_port);
816     serv_addr.sin_addr = dest_addr;
817     memset(&(serv_addr.sin_zero), 0, 8);
818     
819     JRLDBG("Connecting TCP Data link\n");
820     /*we establish a connection with the server */
821     if (connect(data_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
822       cerr << "the connection could not be established : " << endl;
823       *ret_str = "Could not establish link";
824       return CTRL_ERROR;
825     }
826
827
828     local_port = data_port;
829
830     *ret_str = "Successfully added a TCP link to " + remote_address;
831     ret = CTRL_ADD_TCP_SOCK;
832
833   } else if(type == UDP_STR) {
834     
835     if (GetLocalSockAddress(g_udp_sockfd, (struct sockaddr *)&local_address) == -1) {
836       JRLDBG("Could not get local address\n");
837       return CTRL_ERROR;
838     }
839     local_port = ntohs(local_address.sin_port);
840
841     data_sock = g_udp_sockfd;
842     *ret_str = "Successfully added a virtual UDP link to " + remote_address;
843
844   } 
845
846   *link_sock = data_sock;
847
848   if (create_ctrl_connection(&ctrl_con, remote_address, ctrl_port) == -1) {
849     JRLDBG("Could not establish control connection\n");
850     *ret_str = "Could not register new link";
851     if (type == TCP_STR) {
852       CLOSE_SSL(use_ssl_data, ssl);
853       CLOSE(*link_sock);
854     }
855     return CTRL_ERROR;
856   }
857
858   JRLDBG("ctrl session established\n");
859
860   snprintf(buf, 128, "%s %d", "myself", local_port);
861   output = "REGISTERLINK ";
862   output = output + buf + " " + type;
863
864   if (send_ctrl_msg(ctrl_con, output, remote_password) == -1) {
865     JRLDBG("Could not send the control message\n");
866     *ret_str = "Could not register new link";
867     if (type == TCP_STR) {
868       CLOSE_SSL(use_ssl_data, ssl);
869       CLOSE(*link_sock);
870     }
871     return CTRL_ERROR;
872   }
873
874   JRLDBG("Ctrl message sent\n");
875   if (close_ctrl_connection(ctrl_con, remote_password) == -1) {
876     JRLDBG("Could not close control connection\n");
877   }
878
879   link_index = add_link_entry(dest, get_tunnel_type(type), LINK, data_port, 1, data_sock);
880   
881   if (link_index == -1) {
882     *ret_str = "Could not add link entry";
883     if (type == TCP_STR) {
884       CLOSE_SSL(use_ssl_data, ssl);
885       CLOSE(*link_sock);
886     }
887     return CTRL_ERROR;
888   }
889
890   JRLDBG("Addlink Created link: FD=%d\n", g_links[link_index].link_sock);
891
892   return ret;
893 }
894
895
896
897 int AddRoute(string input, string * ret_str) {
898   int src_mac_qual;
899   int dest_mac_qual;
900
901   int dest;
902   int src;
903
904   int route_index;
905
906   int route_type;
907   int src_route_type;
908
909   char src_mac[6];
910   char dest_mac[6];
911
912   string hello, version, password, command;
913   string src_str, dest_str, src_mac_str, dest_mac_str, src_type, type;
914   
915
916   {
917     istringstream is(input,istringstream::in);
918     is >> hello >> password >> version >> command >> src_mac_str >> dest_mac_str >>  type >> dest_str >> src_type >> src_str;
919   }
920
921   if ((src_mac_str.empty()) || (dest_mac_str.empty()) || 
922       (dest_str.empty()) || (type.empty())) {
923     *ret_str = "Invalid AddRoute command";
924     return CTRL_ERROR;
925   }
926
927
928   if (get_route_type(type) == -1) {
929     *ret_str = "Invalid route type";
930     return CTRL_ERROR;
931   }
932
933
934   if (!(src_type.empty()) && (get_route_src_type(src_type) == -1)) {
935     *ret_str = "Invalid route source type";
936     return CTRL_ERROR;
937   }
938
939
940   //We will first do some parsing to obtain correct the qualifier for source and destination address
941   if (src_mac_str.find(":",0) == string::npos) {
942     src_mac_qual = get_qual_type(src_mac_str);
943
944     if (src_mac_qual == -1) {
945       *ret_str = "Invalid Qual Type";
946       return CTRL_ERROR;
947     }
948
949     memset(src_mac, 0, 6);
950   } else {
951     if(src_mac_str.substr(0,3) == NOT) {
952       src_mac_qual = NOT_TYPE;
953       src_mac_str = src_mac_str.substr(4);
954     } else {
955       src_mac_qual = EMPTY_TYPE;
956     }
957     
958     src_mac_str = src_mac_str.substr(0,2) + src_mac_str.substr(3,2) + src_mac_str.substr(6,2) + src_mac_str.substr(9,2) + src_mac_str.substr(12,2) + src_mac_str.substr(15,2);
959   
960     ConvertHexEthernetAddressToBinary(src_mac_str.c_str(), src_mac);
961   }
962   
963
964   if (dest_mac_str.find (":",0) == string::npos) {
965     dest_mac_qual = get_qual_type(dest_mac_str);
966
967     if (dest_mac_qual == -1) {
968           ret_str->assign("Invalid Qual Type");
969       return CTRL_ERROR;
970     }
971
972     memset(dest_mac, 0, 6);
973   } else {
974     if(dest_mac_str.substr(0,3) == NOT) {
975       dest_mac_qual = NOT_TYPE;
976       dest_mac_str = dest_mac_str.substr(4);
977     } else {
978       dest_mac_qual = EMPTY_TYPE;
979     }
980     
981     dest_mac_str = dest_mac_str.substr(0,2) + dest_mac_str.substr(3,2) + dest_mac_str.substr(6,2) + dest_mac_str.substr(9,2) + dest_mac_str.substr(12,2) + dest_mac_str.substr(15,2);
982     
983     ConvertHexEthernetAddressToBinary(dest_mac_str.c_str(), dest_mac);  
984   }
985   
986   if (type == INTERFACE) {
987     int dest_dev;
988     
989     dest_dev = get_device(dest_str);
990
991     if (dest_dev == -1) {
992           ret_str->assign("Could not find Destination Interface");
993       return CTRL_ERROR;
994     }
995
996     dest = dest_dev;
997     
998     route_type = INTERFACE_TYPE;
999   } else if (type == EDGE) {
1000     hostent * remote_he;
1001
1002     if ((remote_he = gethostbyname(dest_str.c_str())) == NULL) {
1003       ret_str->assign("Could not lookup address for " + dest_str);
1004       return CTRL_ERROR;
1005     }
1006
1007     dest = find_link_entry((*((struct in_addr *)remote_he->h_addr)).s_addr, -1);
1008     if (dest == -1) {
1009       JRLDBG("AddRoute: Invalid Destination: %s\n", inet_ntoa((*((struct in_addr *)remote_he->h_addr))));
1010       ret_str->assign("Addroute requested for invalid destination");
1011       return CTRL_ERROR;
1012     }
1013      
1014     route_type = EDGE_TYPE;
1015   } 
1016
1017
1018   if (src_type.empty() || (src_type == ANY_SRC)) {
1019     src = -1;
1020     src_route_type = ANY_SRC_TYPE;
1021   } else if (src_type == INTERFACE) {
1022
1023     if (src_str.empty()) {
1024                 ret_str->assign("Missing Source INTERFACE");
1025       return CTRL_ERROR;
1026     }
1027
1028     if (src_str == ANY_SRC) {
1029       src = -1;
1030     } else {
1031       int src_dev;
1032       src_dev = get_device(src_str);
1033       
1034       if (src_dev == -1) {
1035                   ret_str->assign("Could not find Source Interface");
1036         return CTRL_ERROR;
1037       }
1038       
1039       src = src_dev;
1040     }
1041     src_route_type = INTERFACE_TYPE;
1042
1043   } else if (src_type == EDGE) {
1044
1045     if (src_str == ANY_SRC) {
1046       src = -1;
1047     } else {
1048       hostent * src_he;
1049
1050       if (src_str.empty()) {
1051                   ret_str->assign("Missing Source EDGE Address");
1052         return CTRL_ERROR;
1053       }
1054       
1055       if ((src_he = gethostbyname(src_str.c_str())) == NULL) {
1056                   ret_str->assign("Could not lookup address for " + src_str);
1057         return CTRL_ERROR;
1058       }
1059
1060       src = find_link_entry((*((struct in_addr *)src_he->h_addr)).s_addr, -1);
1061   
1062       if (src == -1) {
1063         JRLDBG("AddRoute: Invalid Destination: %s\n", inet_ntoa((*((struct in_addr *)src_he->h_addr))));
1064                 ret_str->assign("Addroute requested for invalid destination");
1065         return CTRL_ERROR;
1066       }
1067     }
1068
1069     src_route_type = EDGE_TYPE;
1070
1071   }
1072
1073
1074   JRLDBG("Route Def: %d:%d:%d:%d:%d:%d  %d:%d:%d:%d:%d:%d src_qual=%d, dest_qual=%d, dest=%d, type=%d src=%d, src_type=%d\n",  src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5], dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5], src_mac_qual, dest_mac_qual, dest, route_type, src, src_route_type);
1075
1076   route_index = find_route_entry(src_mac, dest_mac, src_mac_qual, dest_mac_qual, dest, route_type, src, src_route_type);
1077
1078   if (route_index != -1) {
1079     JRLDBG("Route Already Exists, Index: %d\n", route_index);
1080         ret_str->assign("Route alredy Exists");
1081     return CTRL_ERROR;
1082   }
1083
1084   route_index = add_route_entry(src_mac, dest_mac, src_mac_qual, dest_mac_qual, dest, get_route_type(type), src, src_route_type);
1085     
1086   if (route_index >= 0) {
1087           ret_str->assign("Successfully added the route for " +src_mac_str+ " and "+dest_mac_str);
1088   } else {
1089           ret_str->assign("Could not add route for " + src_mac_str + " and " + dest_mac_str);
1090     return CTRL_ERROR;
1091   }
1092
1093   return route_index;  
1094 }
1095
1096 #endif
1097
1098 int add_device_to_table(char *device_name, int type) {
1099   int i;
1100
1101   for (i = 0; i < MAX_DEVICES; i++) {
1102     if (g_devices[i].use == 0) {
1103  //     g_devices[i].device_name = device_name;
1104       strcpy(g_devices[i].device_name, device_name);
1105       g_devices[i].type = type;
1106       g_devices[i].use = 1;
1107
1108       if (g_first_device == -1) 
1109         g_first_device = i;
1110
1111       g_devices[i].prev = g_last_device;
1112       g_devices[i].next = -1;
1113
1114       if (g_last_device != -1) 
1115         g_devices[g_last_device].next = i;
1116
1117       g_last_device = i;
1118
1119       g_num_devices++;
1120       return i;
1121     }
1122   }
1123   return -1;
1124 }
1125
1126
1127 int find_link_entry(unsigned long dest, int type) {
1128   int i;
1129
1130   //  PringDebug("Src: %lu, Dst: %lu\n", src, dest);
1131
1132   FOREACH_LINK(i, g_links, g_first_link) {
1133     if ( (g_links[i].dest == dest) && 
1134          ((type == -1) || (g_links[i].type == type)) ) {
1135       return i;
1136     }
1137   } 
1138
1139   return -1;
1140 }
1141
1142 int delete_link_entry(int index) {
1143   int next_i;
1144   int prev_i;
1145
1146   if (g_links[index].use == 0) {
1147     return -1;
1148   }
1149
1150   g_links[index].dest = 0;
1151 //  g_links[index].authenticated = 0;
1152   g_links[index].type = 0;
1153   g_links[index].link_sock = -1;
1154   g_links[index].use = 0;
1155
1156   prev_i = g_links[index].prev;
1157   next_i = g_links[index].next;
1158
1159   if (prev_i != -1)
1160     g_links[prev_i].next = g_links[index].next;
1161
1162
1163   if (next_i != -1) 
1164     g_links[next_i].prev = g_links[index].prev;
1165
1166   if (g_first_link == index)
1167     g_first_link = g_links[index].next;
1168
1169   if (g_last_link == index) 
1170     g_last_link = g_links[index].prev;
1171
1172   g_links[index].next = -1;
1173   g_links[index].prev = -1;
1174
1175   g_num_links--;
1176
1177   return 0;
1178 }
1179
1180 int delete_link_entry_by_addr(unsigned long dest, int type) {
1181   int index = find_link_entry(dest, type);
1182   
1183   if (index == -1) {
1184     return -1;
1185   }
1186
1187   return delete_link_entry(index);
1188 }
1189
1190 #if 0
1191 int delete_device(string device_name) {
1192   int index = get_device(device_name);
1193   
1194   if (index == -1) {
1195     return -1;
1196   }
1197
1198   delete_device(index);
1199
1200   return 0;
1201 }
1202
1203 #endif
1204
1205 int delete_device(int index) {
1206   int next_i;
1207   int prev_i;
1208
1209   g_devices[index].device_name = "";
1210   g_devices[index].use = 0;
1211
1212
1213   prev_i = g_devices[index].prev;
1214   next_i = g_devices[index].next;
1215
1216   if (prev_i != -1)
1217     g_devices[prev_i].next = g_devices[index].next;
1218
1219
1220   if (next_i != -1) 
1221     g_devices[next_i].prev = g_devices[index].prev;
1222
1223   if (g_first_device == index)
1224     g_first_device = g_devices[index].next;
1225
1226   if (g_last_device == index) 
1227     g_last_device = g_devices[index].prev;
1228
1229   g_devices[index].next = -1;
1230   g_devices[index].prev = -1;
1231
1232   g_num_devices--;
1233
1234   return 0;
1235 }
1236
1237 int find_route_entry(char src_mac[6], char dest_mac[6], int src_mac_qual, int dest_mac_qual, int dest, int type, int src, int src_type) {
1238   int i;
1239   char temp_src_mac[6];
1240   char temp_dest_mac[6];
1241   
1242   if ((src_mac_qual != ANY_TYPE) && (src_mac_qual != NONE_TYPE)) {
1243     memcpy(temp_src_mac, src_mac, 6);
1244   } else {
1245     memset(temp_src_mac, 0, 6);
1246   }
1247   
1248   if ((dest_mac_qual != ANY_TYPE) && (dest_mac_qual != NONE_TYPE)) {
1249     memcpy(temp_dest_mac, dest_mac, 6);
1250   } else {
1251     memset(temp_dest_mac, 0, 6);
1252   }
1253
1254   FOREACH_LINK(i, g_routes, g_first_route) {
1255     if ( (memcmp(temp_src_mac, g_routes[i].src_mac, 6) == 0) && 
1256          (memcmp(temp_dest_mac, g_routes[i].dest_mac, 6) == 0) &&
1257          (g_routes[i].src_mac_qual == src_mac_qual) &&
1258          (g_routes[i].dest_mac_qual == dest_mac_qual)  &&
1259          ( (type == -1) || 
1260            ((type == g_routes[i].type) && (g_routes[i].dest == dest))) &&
1261          ( (src_type == -1) || 
1262            ((src_type == g_routes[i].src_type) && (g_routes[i].src == src))) ) {
1263       return i;
1264     }
1265   } 
1266
1267   return -1;
1268 }
1269
1270 int delete_route_entry(int index) {
1271   
1272   int next_i;
1273   int prev_i;
1274
1275   memset(g_routes[index].src_mac, 0, 6);
1276   memset(g_routes[index].dest_mac, 0, 6);
1277
1278   g_routes[index].dest = 0;
1279   g_routes[index].src = 0;
1280   g_routes[index].src_mac_qual = 0;
1281   g_routes[index].dest_mac_qual = 0;
1282   g_routes[index].type = -1;
1283   g_routes[index].src_type = -1;
1284   g_routes[index].use = 0;
1285   
1286
1287   prev_i = g_routes[index].prev;
1288   next_i = g_routes[index].next;
1289
1290   if (prev_i != -1)
1291     g_routes[prev_i].next = g_routes[index].next;
1292
1293
1294   if (next_i != -1) 
1295     g_routes[next_i].prev = g_routes[index].prev;
1296
1297   if (g_first_route == index)
1298     g_first_route = g_routes[index].next;
1299
1300   if (g_last_route == index) 
1301     g_last_route = g_routes[index].prev;
1302
1303   g_routes[index].next = -1;
1304   g_routes[index].prev = -1;
1305
1306   g_num_routes--;
1307
1308   return 0;
1309 }
1310
1311 int delete_route_entry_by_addr(char src_mac[6], char dest_mac[6], int src_mac_qual, int dest_mac_qual, int dest, int type, int src, int src_type) {
1312   int index = find_route_entry(src_mac, dest_mac, src_mac_qual, dest_mac_qual, dest, type, src, src_type);
1313   
1314   if (index == -1) {
1315     return -1;
1316   }
1317
1318   delete_route_entry(index);
1319
1320   return 0;
1321 }
1322
1323
1324 #if 0
1325 int DeleteLink(string input, SOCK * link_sock, string * ret_str) {
1326   string output;
1327   string hello,password, version, command;
1328   string remote_address, type, remote_password;
1329   int ctrl_port = 0;
1330
1331   struct hostent * remote_he;
1332   unsigned long dest_addr;
1333
1334   int link_index;
1335   int ret = CTRL_DO_NOTHING;
1336
1337   con_t ctrl_con;
1338   struct sockaddr_in local_address;
1339   char buf[128];
1340
1341   *link_sock = 0;
1342
1343   {
1344     istringstream is(input,istringstream::in);
1345     is >> hello >> password >> version >> command >> remote_address >> ctrl_port >> remote_password >> type ;
1346   }
1347
1348   if ((remote_address.empty()) || (remote_password.empty()) || 
1349       (type.empty()) || (ctrl_port == 0)) {
1350     *ret_str = "Invalid Deletelink command";
1351     return CTRL_ERROR;
1352   }
1353
1354   if (get_tunnel_type(type) == -1) {
1355     *ret_str = "Invalid link type";
1356     return CTRL_ERROR;
1357   }
1358
1359   if ((remote_he = gethostbyname(remote_address.c_str())) == NULL) {
1360     *ret_str = "could not lookup address of " + remote_address;
1361     return CTRL_ERROR;
1362   }
1363
1364   dest_addr = (*((struct in_addr *)remote_he->h_addr)).s_addr; 
1365
1366   JRLDBG("Deleting  Dst: %lu\n", dest_addr);
1367
1368   link_index = find_link_entry(dest_addr, get_tunnel_type(type));
1369
1370
1371   if (link_index == -1) {
1372  
1373     JRLDBG("Link Does Not Exist\n");
1374     *ret_str = "Link Does not exist";
1375     return CTRL_ERROR;
1376   }
1377
1378   if (type == TCP_STR) {
1379     *link_sock = g_links[link_index].link_sock;
1380     *ret_str = "Successfully deleted a TCP link to " + remote_address;
1381     ret = CTRL_DELETE_TCP_SOCK;
1382
1383   } else if (type == UDP_STR) {
1384     *ret_str = "Successfully deleted a virtual UDP link to " + remote_address;
1385   } else if (type == VTP_STR) {
1386     *ret_str = "Successfully deleted a VTP link to " + remote_address;
1387     // TODO: Send delete control message
1388   }
1389
1390
1391
1392   if (create_ctrl_connection(&ctrl_con, remote_address, ctrl_port) == -1) {
1393     JRLDBG("Could not establish control connection\n");
1394     *ret_str = "Could not deregister link";
1395     CLOSE(*link_sock);
1396     return CTRL_ERROR;
1397   }
1398
1399
1400   /*
1401     if (GetLocalSockAddress(ctrl_con.sock, (struct sockaddr *)&local_address) == -1) {
1402     JRLDBG("Could not get local address\n");
1403     *ret_str = "Could not deregister link";
1404     CLOSE(*link_sock);
1405     return CTRL_ERROR;
1406     }
1407     
1408     snprintf(buf, 128, "%s", inet_ntoa(local_address.sin_addr));
1409   */
1410   output = "DEREGISTERLINK ";
1411   output = output + "myself" + " " + type;
1412
1413   if (send_ctrl_msg(ctrl_con, output, remote_password) == -1) {
1414     // Could not register on the remote host, 
1415     CLOSE(*link_sock);
1416     *ret_str = "Could not deregister link on remote host";
1417     return CTRL_ERROR;
1418   }
1419
1420   if (close_ctrl_connection(ctrl_con, remote_password) == -1) {
1421     JRLDBG("Could not close control connection\n");
1422   }
1423
1424   if (close_link(link_index) == -1) {
1425     *ret_str = "Could not delete link";
1426     return CTRL_ERROR;
1427   }
1428
1429   return ret;
1430 }
1431
1432
1433 int DeleteRoute(string input, string * ret_str) {
1434   int src_mac_qual;
1435   int dest_mac_qual;
1436
1437   int dest;
1438   int src;
1439
1440   int ret = 0;
1441   char src_mac[6];
1442   char dest_mac[6];
1443
1444   int route_type;
1445   int src_route_type;
1446
1447   string hello, version, password, command;
1448   string src_str, dest_str, src_mac_str, dest_mac_str, type, src_type;
1449   
1450   {
1451     istringstream is(input,istringstream::in);
1452     is >> hello >> password >> version >> command >> src_mac_str >> dest_mac_str >> type >> dest_str >> src_type >> src_str ;
1453   }
1454
1455   if ((src_mac_str.empty()) || (dest_mac_str.empty()) || 
1456       (dest_str.empty()) || (type.empty())) {
1457                   ret_str->assign("Invalid Deleteroute command");
1458     return CTRL_ERROR;
1459   }
1460
1461
1462   if (get_route_type(type) == -1) {
1463           ret_str->assign("Invalid route type");
1464     return CTRL_ERROR;
1465   }
1466
1467   if (!(src_type.empty()) && (get_route_src_type(src_type) == -1)) {
1468     ret_str->assign("Invalid route source type");
1469     return CTRL_ERROR;
1470   }
1471
1472   //We will first do some parsing to obtain correct the qualifier for source and destination address
1473   if (src_mac_str.find(":",0) == string::npos) {
1474     src_mac_qual = get_qual_type(src_mac_str);
1475
1476     if (src_mac_qual == -1) {
1477       ret_str->assign("Invalid qual type");
1478       return CTRL_ERROR;
1479     }
1480
1481     memset(src_mac, 0, 6);
1482   } else {
1483     if(src_mac_str.substr(0,3) == NOT) {
1484       src_mac_qual = NOT_TYPE;
1485       src_mac_str = src_mac_str.substr(4);
1486     } else {
1487       src_mac_qual = EMPTY_TYPE;
1488     }
1489     
1490     src_mac_str = src_mac_str.substr(0,2) + src_mac_str.substr(3,2) + src_mac_str.substr(6,2) + src_mac_str.substr(9,2) + src_mac_str.substr(12,2) + src_mac_str.substr(15,2);
1491   
1492     ConvertHexEthernetAddressToBinary(src_mac_str.c_str(), src_mac);
1493   }
1494   
1495
1496   if (dest_mac_str.find (":",0) == string::npos) {
1497     dest_mac_qual = get_qual_type(dest_mac_str);
1498
1499     if (dest_mac_qual == -1) {
1500                 ret_str->assign("Invalid Qual Type");
1501       return CTRL_ERROR;
1502     }
1503
1504     memset(dest_mac, 0, 6);
1505   } else {
1506     if(dest_mac_str.substr(0,3) == NOT) {
1507       dest_mac_qual = NOT_TYPE;
1508       dest_mac_str = dest_mac_str.substr(4);
1509     } else {
1510       dest_mac_qual = EMPTY_TYPE;
1511     }
1512     
1513     dest_mac_str = dest_mac_str.substr(0,2) + dest_mac_str.substr(3,2) + dest_mac_str.substr(6,2) + dest_mac_str.substr(9,2) + dest_mac_str.substr(12,2) + dest_mac_str.substr(15,2);
1514     
1515     ConvertHexEthernetAddressToBinary(dest_mac_str.c_str(), dest_mac);  
1516   }
1517   
1518   if (type == INTERFACE) {
1519     int dest_dev;
1520
1521     dest_dev = get_device(dest_str);
1522
1523     if (dest_dev == -1) {
1524                 ret_str->assign("Could not find Destination Interface");
1525       return CTRL_ERROR;
1526     }
1527
1528     dest = dest_dev;
1529
1530     route_type = INTERFACE_TYPE;
1531   } else if (type == EDGE) {
1532     hostent * remote_he;
1533
1534     if ((remote_he = gethostbyname(dest_str.c_str())) == NULL) {
1535                 ret_str->assign("Could not lookup address for " + dest_str);
1536       return CTRL_ERROR;
1537     }
1538
1539     dest = find_link_entry((*((struct in_addr *)remote_he->h_addr)).s_addr, -1);
1540     if (dest == -1) {
1541                 ret_str->assign("Route requested for invalid destination");
1542       return CTRL_ERROR;
1543     }
1544
1545     route_type = EDGE_TYPE;
1546   }
1547
1548
1549   if (src_type.empty() || (src_type == ANY_SRC)) {
1550     src = -1;
1551     src_route_type = ANY_SRC_TYPE;
1552   } else if (src_type == INTERFACE) {
1553
1554     if (src_str.empty()) {
1555                 ret_str->assign("Missing Source INTERFACE");
1556       return CTRL_ERROR;
1557     }
1558     if (src_str == ANY_SRC) {
1559       src = -1;
1560     } else {
1561       int src_dev;
1562       src_dev = get_device(src_str);
1563       
1564       if (src_dev == -1) {
1565                   ret_str->assign("Could not find Source Interface");
1566         return CTRL_ERROR;
1567       }
1568       
1569       src = src_dev;
1570     }
1571     src_route_type = INTERFACE_TYPE;
1572
1573   } else if (src_type == EDGE) {
1574
1575     if (src_str.empty()) {
1576                 ret_str->assign("Missing Source EDGE Address");
1577       return CTRL_ERROR;
1578     }
1579
1580     if (src_str == ANY_SRC) {
1581       src = -1;
1582     } else {
1583       hostent * src_he;
1584     
1585       if ((src_he = gethostbyname(src_str.c_str())) == NULL) {
1586                   ret_str->assign("Could not lookup address for " + src_str);
1587         return CTRL_ERROR;
1588       }
1589       
1590       src = find_link_entry((*((struct in_addr *)src_he->h_addr)).s_addr, -1);
1591
1592       if (src == -1) {
1593         JRLDBG("DeleteRoute: Invalid Destination: %s\n", inet_ntoa((*((struct in_addr *)src_he->h_addr))));
1594                 ret_str->assign("DeleteToute requested for invalid destination");
1595         return CTRL_ERROR;
1596       }
1597     }
1598     src_route_type = EDGE_TYPE;
1599   }
1600
1601   ret = delete_route_entry(src_mac, dest_mac, src_mac_qual, dest_mac_qual, dest, route_type, src, src_route_type);
1602   
1603   if (ret == 0) {
1604           ret_str->assign("Successfully deleted the route for " +src_mac_str+ " and "+dest_mac_str);
1605   } else {
1606           ret_str->assign("Could not delete the route");
1607     return CTRL_ERROR;
1608   }
1609   
1610   return ret;
1611 }
1612 #endif
1613
1614 int delete_sock(struct sock_list * socks, int *first_sock, int *last_sock, SOCK fd) {
1615   int i;
1616   int prev_i;
1617   int next_i;
1618
1619   
1620   FOREACH_SOCK(i, socks, (*first_sock)) {
1621     if (socks[i].sock == fd) {
1622       V3_Close_Socket(socks[i].sock);
1623       socks[i].sock = -1;
1624
1625       prev_i = socks[i].prev;
1626       next_i = socks[i].next;
1627
1628       if (prev_i != -1)
1629         socks[prev_i].next = socks[i].next;
1630       
1631       if (next_i != -1) 
1632         socks[next_i].prev = socks[i].prev;
1633       
1634       if (*first_sock == i)
1635         *first_sock = socks[i].next;
1636       
1637       if (*last_sock == i) 
1638         *last_sock = socks[i].prev;
1639
1640       socks[i].next = -1;
1641       socks[i].prev = -1;
1642
1643       return 0;
1644     }
1645   }
1646   return -1;
1647 }
1648
1649 /*
1650 //During testing, route table, link table, etc. are writen in program, isteadjing of AddRoute(), AddLink()...
1651 void Create_topologies()
1652 {
1653         //create link table
1654         unsigned long dest; //  dest_addr = *((struct in_addr *)remote_he->h_addr);  dest = dest_addr.s_addr;
1655         add_link_entry(dest, TCP_STR, int data_port, SOCK fd)  //the parameter need modify
1656
1657         //create device table
1658
1659         add_device_to_table(eth0)
1660
1661         //create route table
1662         //example(VnetClientJava):FORWARD endeavor.cs.northwestern.edu EDGE not-00:0C:29:0F:4E:AA 00:0C:29:0F:4E:AA virtuoso-22.cs.northwestern.edu ANY ANY     
1663         //format(VnetClientJava): String routeStr = "FORWARD " + host.getHostname() + " " + dstType +  " " +  srcMacStr + " " + dstMacStr + " " + dst + " " + srcType + " " + src; 
1664         char src_mac[6]; //={};  //00:0C:29:0F:4E:AA
1665         char dest_mac[6];       //00:0C:29:0F:4E:AA, empty type is only a mac adress.
1666         add_route_entry(src_mac, dest_mac, NOT_TYPE, EMPTY_TYPE, , EDGE, ANY, ANY); //decide "dest" after creade device table or link table.
1667 }
1668
1669 */
1670
1671
1672 //int data_port, is udp/tcp port.  SOCK fd comes from socket() function.. so this function is called after socket().
1673 void store_topologies(int data_port,  SOCK fd)
1674 {
1675         int i;
1676         int src_mac_qual = ANY_TYPE;
1677         int dest_mac_qual = ANY_TYPE;
1678         int dest =0; //this is in_addr.s_addr
1679         int type = UDP_TYPE;
1680         int src = 0;
1681         int src_type= ANY_SRC_TYPE;
1682         
1683         //store link table
1684   for(i = 0; i < 1; i++) {
1685     if (g_links[i].use == 0) {
1686       g_links[i].dest = dest;
1687  //     g_links[i].authenticated = authenticated;
1688       g_links[i].type = type;
1689       g_links[i].link_sock = fd;
1690       g_links[i].remote_port = data_port;
1691       g_links[i].use = 1;
1692  //     g_links[i].link_class = link_class;
1693
1694       if (g_first_link == -1) 
1695         g_first_link = i;
1696
1697       g_links[i].prev = g_last_link;
1698       g_links[i].next = -1;
1699       
1700       if (g_last_link != -1) {
1701         g_links[g_last_link].next = i;
1702       }
1703
1704       g_last_link = i;
1705
1706       g_num_links++;
1707     }
1708   }
1709         //store route table
1710
1711         type = EDGE_TYPE;
1712         dest =0;
1713
1714         for(i = 0; i < 1; i++) {
1715                 if (g_routes[i].use == 0) {
1716      
1717                  if ((src_mac_qual != ANY_TYPE) && (src_mac_qual != NONE_TYPE)) {
1718         //              memcpy(g_routes[i].src_mac, src_mac, 6);
1719                 } else {
1720                         memset(g_routes[i].src_mac, 0, 6);
1721                 }
1722       
1723                 if ((dest_mac_qual != ANY_TYPE) && (dest_mac_qual != NONE_TYPE)) {
1724         //              memcpy(g_routes[i].dest_mac, dest_mac, 6);
1725                 } else {
1726                         memset(g_routes[i].dest_mac, 0, 6);
1727                 }
1728
1729       g_routes[i].src_mac_qual = src_mac_qual;
1730       g_routes[i].dest_mac_qual = dest_mac_qual;
1731       g_routes[i].dest = dest;
1732       g_routes[i].type = type;
1733       g_routes[i].src = src;
1734       g_routes[i].src_type = src_type;
1735       
1736       g_routes[i].use = 1;
1737
1738       if (g_first_route == -1) 
1739                 g_first_route = i;
1740
1741       g_routes[i].prev = g_last_route;
1742       g_routes[i].next = -1;
1743
1744       if (g_last_route != -1) {
1745         g_routes[g_last_route].next = i;
1746       }
1747
1748       g_last_route = i;
1749
1750       g_num_routes++;
1751
1752         }
1753   }
1754 }
1755
1756 //int MatchRoute(char * src_mac, char * dst_mac, int src_type, int src_index, int * do_we_analyze, int * matches) {
1757 int MatchRoute(char * src_mac, char * dst_mac, int src_type, int src_index, int * matches) { 
1758
1759   int values[g_num_routes];
1760   int matched_routes[g_num_routes];
1761
1762   int num_matches = 0;
1763   int i;
1764   int max = 0;
1765   int no = 0;
1766   int exact_match = 0;
1767
1768
1769
1770    FOREACH_ROUTE(i, g_routes, g_first_route) {
1771     if ( (g_routes[i].src_type != ANY_SRC_TYPE) &&
1772      ( (g_routes[i].src_type != src_type) ||
1773        ( (g_routes[i].src != src_index) &&
1774          (g_routes[i].src != -1) ) ) ) {
1775       PrintDebug("Source route is on and does not match\n");
1776       continue;
1777     }
1778
1779     if ( (g_routes[i].dest_mac_qual == ANY_TYPE) &&
1780      (g_routes[i].src_mac_qual == ANY_TYPE) ) {
1781       
1782       matched_routes[num_matches] = i;
1783       values[num_matches] = 3;
1784
1785       num_matches++;
1786     }
1787     
1788     if (memcmp((void *)&g_routes[i].src_mac, (void *)src_mac, 6) == 0) {
1789       if (g_routes[i].src_mac_qual !=  NOT_TYPE) {
1790     if (g_routes[i].dest_mac_qual == ANY_TYPE) {
1791       
1792       matched_routes[num_matches] = i;
1793       values[num_matches] = 6;
1794       
1795       num_matches++;
1796     } else if (memcmp((void *)&g_routes[i].dest_mac, (void *)dst_mac, 6) == 0) {
1797       if (g_routes[i].dest_mac_qual != NOT_TYPE) {
1798         
1799         matched_routes[num_matches] = i;
1800         values[num_matches] = 8;
1801         
1802         exact_match = 1;
1803
1804         num_matches++;
1805       }
1806     }
1807       }
1808     }
1809     
1810     if (memcmp((void *)&g_routes[i].dest_mac, (void *)dst_mac, 6) == 0) {
1811       if (g_routes[i].dest_mac_qual != NOT_TYPE) {
1812     if (g_routes[i].src_mac_qual == ANY_TYPE) {
1813       
1814       matched_routes[num_matches] = i;
1815       values[num_matches] = 6;
1816
1817       num_matches++;
1818     } else if (memcmp((void *)&g_routes[i].src_mac, (void *)src_mac, 6) == 0) {
1819       if (g_routes[i].src_mac_qual != NOT_TYPE) {
1820
1821         if (exact_match == 0) {
1822           matched_routes[num_matches] = i;
1823           values[num_matches] = 8;
1824
1825           num_matches++;
1826         }
1827       }
1828     }
1829       }
1830     }
1831     
1832     if ( (g_routes[i].dest_mac_qual == NOT_TYPE) &&
1833      (memcmp((void *)&g_routes[i].dest_mac, (void *)dst_mac, 6) != 0)) {
1834       if (g_routes[i].src_mac_qual == ANY_TYPE) {
1835     
1836     matched_routes[num_matches] = i;
1837     values[num_matches] = 5;
1838     
1839     num_matches++;    
1840       } else if (memcmp((void *)&g_routes[i].src_mac, (void *)src_mac, 6) == 0) {
1841     if (g_routes[i].src_mac_qual != NOT_TYPE) {
1842       
1843       matched_routes[num_matches] = i;
1844       values[num_matches] = 7;
1845       
1846       num_matches++;
1847     }
1848       }
1849     }
1850     
1851     if ( (g_routes[i].src_mac_qual == NOT_TYPE) &&
1852      (memcmp((void *)&g_routes[i].src_mac, (void *)src_mac, 6) != 0) ) {
1853       if (g_routes[i].dest_mac_qual == ANY_TYPE) {
1854     
1855     matched_routes[num_matches] = i;
1856     values[num_matches] = 5;
1857     
1858     num_matches++;
1859       } else if (memcmp((void *)&g_routes[i].dest_mac, (void *)dst_mac, 6) == 0) {
1860     if (g_routes[i].dest_mac_qual != NOT_TYPE) {
1861       
1862       matched_routes[num_matches] = i;
1863       values[num_matches] = 7;
1864
1865       num_matches++;
1866     }
1867       }
1868     }
1869   }
1870
1871
1872
1873   FOREACH_ROUTE(i, g_routes, g_first_route) {
1874     if ( (memcmp((void *)&g_routes[i].src_mac, (void *)src_mac, 6) == 0) &&
1875      (g_routes[i].dest_mac_qual == NONE_TYPE) &&
1876      ( (g_routes[i].src_type == ANY_SRC_TYPE) ||
1877        ( (g_routes[i].src_type == src_type) &&
1878          ( (g_routes[i].src == src_index) ||
1879            (g_routes[i].src == -1) )))) {
1880
1881       matched_routes[num_matches] = i;
1882       values[num_matches] = 4;
1883       PrintDebug("We matched a default route (%d)\n", i);
1884       num_matches++;
1885     }
1886   }
1887  
1888   //If many rules have been matched, we choose one which has the highest value rating
1889   if (num_matches == 0) {
1890     return 0;
1891   }
1892
1893   for (i = 0; i < num_matches; i++) {
1894     if (values[i] > max) {
1895       no = 0;
1896
1897       max = values[i];
1898       matches[no] = matched_routes[i];
1899
1900       no++;
1901     } else if (values[i] == max) {
1902       matches[no] = matched_routes[i];
1903
1904       no++;
1905     }
1906   }
1907
1908   return no;
1909 }
1910
1911 bool HandleDataOverLink(RawEthernetPacket *pkt, int src_link_index)
1912 {
1913
1914   char src_mac[6];
1915   char dst_mac[6];
1916 //  int do_we_analyze;
1917
1918   int matches[g_num_routes];
1919
1920   int num_matched_routes = 0;
1921   int i;
1922   struct HEADERS headers;
1923 //  char hash_key[HASH_KEY_SIZE];
1924
1925   // get the ethernet and ip headers from the packet
1926   memcpy((void *)&headers, (void *)pkt->data, sizeof(headers));
1927   int j;
1928   for(j = 0;j < 6; j++) {
1929     src_mac[j] = headers.ethernetsrc[j];
1930     dst_mac[j] = headers.ethernetdest[j];
1931   }
1932  
1933
1934 //#ifdef DEBUG
1935   char dest_str[18];
1936   char src_str[18];
1937
1938   mac_to_string(src_mac, src_str);  
1939   mac_to_string(dst_mac, dest_str);
1940
1941   PrintDebug("SRC(%s), DEST(%s)\n", src_str, dest_str);
1942 //#endif
1943
1944 //  make_hash_key(hash_key, src_mac, dst_mac, EDGE_TYPE, src_link_index);
1945
1946
1947   //  num_matched_routes = MatchRoute(src_mac, dst_mac, EDGE_TYPE, src_link_index, &do_we_analyze, matches);
1948   num_matched_routes = MatchRoute(src_mac, dst_mac, EDGE_TYPE, src_link_index, matches);
1949
1950   PrintDebug("Matches=%d\n", num_matched_routes);
1951
1952   for (i = 0; i < num_matched_routes; i++) {
1953     int route_index = -1;
1954     int link_index = -1;
1955     int dev_index = -1;
1956
1957     route_index = matches[i];
1958
1959 #ifdef DEBUG
1960     {
1961   //    char *route_str;
1962       PrintDebug("Forward packet from link according to Route entry %d\n", route_index);
1963  //     route_to_str(route_index, &route_str);
1964    //   PrintDebug("Route Rule: %s\n", route_str.c_str());
1965     }
1966 #endif
1967
1968     if (g_routes[route_index].type == EDGE_TYPE) {
1969      
1970       link_index = g_routes[route_index].dest;
1971             
1972    //   PrintDebug("Destination Host: %s\n", ip_to_string(htonl(g_links[link_index].dest)));
1973
1974       if(g_links[link_index].type == UDP_TYPE) {
1975    
1976           int size;
1977           PrintDebug("Serializing UDP Packet from LINK, fd=%d\n", g_links[link_index].link_sock);
1978  
1979           if ((size = V3_SendTo_IP(g_links[link_index].link_sock,  g_links[link_index].dest,  g_links[link_index].remote_port, pkt->data, pkt->size)) != pkt->size)  {
1980             PrintError("Vnet: sending by UDP Exception, %x\n", size);
1981             return false;
1982          }
1983
1984       }  else if (g_links[link_index].type == TCP_TYPE) {
1985  //   PrintDebug("Serializing TCP Packet from link to LINk %s\n", ip_to_string(htonl(g_links[link_index].dest)));
1986                 RawEthernetPacketSerialize(pkt, g_links[link_index].link_sock);
1987       }
1988     } else if (g_routes[route_index].type == INTERFACE_TYPE) {
1989       dev_index = g_routes[route_index].dest;
1990       
1991       PrintDebug("Writing Packet to device=%s\n", g_devices[dev_index].device_name);
1992
1993       if (if_write_pkt(g_devices[dev_index].vnet_device, pkt) == -1) {
1994           PrintDebug("Can't write output packet to link\n");
1995           return false;
1996       }
1997     }
1998   }
1999   return true;
2000 }
2001
2002
2003
2004
2005 #endif  //Route
2006
2007
2008 static void hanlder_ProcessTcp(struct handler *hd)
2009 {
2010   RawEthernetPacket *pt;
2011   
2012   pt = (RawEthernetPacket *)V3_Malloc(sizeof(RawEthernetPacket));
2013   if (pt == NULL){
2014         PrintError("Vnet: Malloc fails\n");
2015         return;
2016   }
2017
2018   if (RawEthernetPacketUnserialize(pt, hd->fd) == false){
2019         PrintError("Vnet: Hanlder:ProcessTcp: receiving packet from TCP fails\n");
2020         return;
2021   }
2022
2023   PrintDebug("Vnet: In Hanlder.ProcessTcp: get packet\n");
2024   print_packet(pt->data, pt->size);
2025 #ifdef ROUTE
2026 /*  int  *link_index ;
2027   link_index = (int *)V3_Malloc(sizeof(int));
2028   if (link_index == NULL){
2029         PrintError("Vnet: Malloc fails\n");
2030         return;
2031   }
2032
2033   *link_index = find_link_by_fd(hd->fd);
2034 */
2035   int link_index;
2036 //  int *link_index_ptr;
2037   link_index = find_link_by_fd(hd->fd);
2038 //  link_index_ptr = &link_index;
2039 //  v3_enqueue(src_link_index_q, (addr_t)link_index_ptr);
2040   pt->index = link_index;
2041 #endif
2042   v3_enqueue(vnet_inpkt_q, (addr_t)pt);
2043 }
2044
2045 static void RunUdp(struct handler *hd)
2046 {
2047   RawEthernetPacket *pt;
2048
2049   while (1) {
2050         pt = (RawEthernetPacket *)V3_Malloc(sizeof(RawEthernetPacket));
2051         if (pt == NULL){
2052                 PrintError("Vnet: Malloc fails\n");
2053                 return;
2054         }
2055
2056         PrintDebug("Vnet: In Hanlder.RunUdp: socket: %d receive from ip %x, port %d\n", hd->fd, hd->remote_address, hd->remote_port);
2057
2058         pt->size = V3_RecvFrom_IP(hd->fd, hd->remote_address, hd->remote_port, pt->data, ETHERNET_PACKET_LEN);
2059
2060         if (pt->size <= 0){
2061                 PrintDebug("Vnet: Hanlder:ProcessUdp: receiving packet from UDP fails\n");
2062                 V3_Free(pt);
2063                 return;
2064         }
2065
2066        PrintDebug("Vnet: In Hanlder.RunUdp: get packet\n");
2067         print_packet(pt->data, pt->size);
2068         
2069
2070         v3_enqueue(vnet_inpkt_q, (addr_t)pt);
2071         
2072   }
2073 }
2074
2075
2076 static void RunTcp(struct handler *hd)
2077 {
2078       struct v3_sock_set fds;
2079       int rc;
2080   
2081       while (1) {
2082          V3_SOCK_ZERO(&fds);
2083          V3_SOCK_SET(hd->fd, &fds);
2084          rc = V3_Select_Socket(&fds, NULL, NULL, NULL);
2085
2086          PrintDebug("Vnet: In Hanlder.Run: Return from Select(): rc : %d\n", rc);
2087                 
2088         if (rc < 0) {
2089                 PrintError("Vnet: In Hanlder.Run: Return from Select() Error: rc : %d\n", rc);
2090                 return;
2091         } else if (rc == 0) {
2092           // huh? didn't ask for timeouts so just repeat
2093                 continue;
2094         } else {
2095                 hanlder_ProcessTcp(hd);
2096         } 
2097       }
2098 }
2099
2100 static int vnet_handle(struct handler *hd)
2101 {
2102       if (use_tcp)
2103                 RunTcp(hd);
2104       else
2105                 RunUdp(hd);
2106           
2107       return 0;
2108 }
2109
2110 static bool handler_tx_packet(struct handler *hd, RawEthernetPacket *pt)
2111 {
2112
2113   if (pt == NULL) {
2114     PrintError("VNET Hanlder: sending a NULL packet\n");
2115         
2116     return false;
2117   }
2118
2119   PrintDebug("VNET Hanlder: socket: %d local %x:[%d], remote %x:[%d]\n", hd->fd, hd->local_address, hd->local_port, hd->remote_address, hd->remote_port);
2120
2121   if (use_tcp)
2122         return RawEthernetPacketSerialize(pt, hd->fd);
2123   else 
2124         return RawEthernetPacketSendUdp(pt, hd->fd, hd->remote_address, hd->remote_port);
2125 }
2126
2127
2128 int V3_Send_pkt(uchar_t *buf, int length)
2129 {
2130         PrintDebug("VNET: In V3_Send_pkt: pkt length %d\n", length);
2131
2132         print_packet((char *)buf, length);
2133
2134         return vnet_send_pkt((char *)buf, length);
2135 }
2136
2137 int V3_Register_pkt_event(int (*netif_input)(uchar_t * pkt, uint_t size))
2138 {
2139         return vnet_register_pkt_event("NE2000", netif_input, NULL);
2140 }
2141
2142 int vnet_send_pkt(char *buf, int length)
2143 {
2144         struct handler * hd;
2145         RawEthernetPacket pt;
2146
2147         hd = get_handler();
2148
2149         if (hd == NULL){
2150                 return -1;
2151         }
2152
2153         PrintDebug("Vnet: vnet_send_pkt: get handler: %p\n", hd);
2154
2155         RawEthernetPacketInit(&pt, buf, length);  //====here we copy sending data once 
2156
2157         if (!handler_tx_packet(hd, &pt))
2158                 return -1;
2159
2160        V3_Yield();
2161
2162         return 0;
2163         
2164 }
2165
2166 int vnet_register_pkt_event(char *dev_name, int (*netif_input)(uchar_t * pkt, uint_t size), void *data)
2167 {
2168         struct vnet_device *dev;
2169
2170         dev = (struct vnet_device *)V3_Malloc(sizeof(struct vnet_device));
2171
2172         if(dev == NULL){
2173                 PrintError("VNET: Malloc fails\n");
2174                 return -1;
2175         }
2176
2177         strncpy(dev->name, dev_name, (strlen(dev_name) < 50)?strlen(dev_name):50);
2178
2179         dev->input = netif_input;
2180         dev->data = data;
2181
2182         if (!add_device(dev))
2183                 return -1;
2184
2185         return 0;
2186 }
2187
2188 int vnet_check()
2189 {
2190 //      struct vnet_device *(*dev)[]; -- YT
2191 //      struct vnet_device *dev;
2192         RawEthernetPacket *pt;
2193         int link_index;
2194 //      int i;
2195
2196         //PrintDebug("VNET: In vnet_check\n");
2197
2198         V3_Yield();
2199         
2200 //      while (((pt = (RawEthernetPacket *)v3_dequeue(vnet_inpkt_q)) != NULL)&&((link_index = (int *)v3_dequeue(src_link_index_q)) != NULL)){
2201         while ((pt = (RawEthernetPacket *)v3_dequeue(vnet_inpkt_q)) != NULL){
2202 #ifdef ROUTE
2203 /*              dev = get_device(pt);
2204                 //while (dev[device_num] != NULL) {     //multi-get_device -- YT
2205                 if (dev == NULL){
2206                         PrintDebug("VNET: In vnet_check: pkt length %d, no destination device, pkt discarded\n", (int)pt->size);
2207                         V3_Free(pt);
2208                         continue;
2209                 }
2210                 
2211                 dev->input((uchar_t *)pt->data, pt->size);
2212
2213                 PrintDebug("VNET: In vnet_check: pkt length %d, device: %s\n", (int)pt->size, dev->name);
2214
2215                 for (i = 0; i <  (int)pt->size; i++)
2216                         PrintDebug("%x ", pt->data[i]);
2217                 PrintDebug("\n");
2218 */
2219                 link_index = pt->index;
2220                 if(HandleDataOverLink(pt, link_index)) {
2221                         PrintDebug("VNET: vnet_check: Receive and Send a packet!\n");  //--YT
2222                 }
2223 #endif
2224 //              V3_Free(link_index);
2225                 V3_Free(pt); //be careful here
2226         }
2227
2228         return 0;
2229 }
2230
2231 static int handler_thread(void *arg)
2232 {
2233     struct handler *hd = (struct handler *)arg;
2234
2235     return vnet_handle(hd);
2236 }
2237
2238 static int vnet_setup_handler(int con_fd, ctype local_config, int remote_addr, int remote_port)
2239 {
2240      struct handler *h;
2241
2242      h = (struct handler *)V3_Malloc(sizeof(struct handler));
2243          
2244      if (local_config != LOCAL && local_config != REMOTE){ 
2245            PrintError("VNET: bad local config\n");
2246            return -1;
2247      }  
2248      h->local_config = local_config;
2249      
2250      h->local_address = bind_address;
2251      h->local_port = bind_port;
2252
2253      h->remote_address = remote_addr;
2254      h->remote_port = remote_port;
2255
2256  
2257      if (h->local_config == LOCAL) {
2258              if ((h->fd = V3_Create_TCP_Socket() < 0)){
2259                    PrintError("VNET: can't create socket\n");
2260                    return -1;
2261              }
2262           
2263              if (V3_Connect_To_IP(h->fd, h->remote_address, h->remote_port) < 0){ 
2264                    V3_Close_Socket(h->fd);
2265                    PrintError("VNET: can't connect to remote VNET server\n");
2266                    return -1;
2267              }
2268
2269              PrintDebug("VNET: ConnectToHost done\n");
2270      } else if (local_config == REMOTE) {
2271              if (con_fd < 0) {
2272                 PrintError("VNET: Invalid socket discriptor\n");
2273                 return -1;
2274              }
2275              h->fd = con_fd;
2276      } else {
2277              return -1;
2278      }
2279
2280      add_handler(h);
2281                  
2282      // Now run protocol to bootstrap the remote VNET server
2283      PrintDebug("VNET: socket connection done socket: %d\n", h->fd);
2284
2285      V3_CREATE_THREAD(&handler_thread, (void *)h, "VNET_HANDLER");
2286
2287      return 0;
2288 }
2289
2290 static int vnet_setup_tcp()
2291 {
2292   uint_t remote_ip;
2293   uint_t remote_port;
2294   int accept_socket;
2295   int connection_socket;
2296   uint_t server_ip =  (0 | 172 << 24 | 23 << 16 | 1 );
2297   uint_t server_port = 22;
2298         
2299
2300   if (vnet_server) {
2301         if ((accept_socket = V3_Create_TCP_Socket() < 0)){
2302               PrintError("VNET: Can't setup socket\n");
2303               return -1;
2304         }
2305
2306         if (bind_address == 0) {
2307               if (V3_Bind_Socket(accept_socket, bind_port) < 0){ 
2308                   PrintError("VNET: Can't bind socket\n");
2309                   return -1;
2310               }
2311         } else {
2312               if (0) {//BindSocketwAdx(accept_socket, bind_address, bind_port) < 0){
2313                   PrintError("VNET: Can't bind socket\n");
2314                   return -1;
2315               }
2316         }
2317
2318         if (V3_Listen_Socket(accept_socket, 1) < 0) {
2319               PrintError("VNET: Can't listen socket\n");
2320               return -1;
2321         }
2322           
2323         // create new connection for each handler remotely
2324         // this will stuck the initiation of vnet
2325         // TODO: put this in a separate kernel thread
2326         do{
2327               PrintDebug("VNET: In Accepting Socket\n");
2328                 
2329               connection_socket = V3_Accept_Socket(accept_socket, &remote_ip, &remote_port);
2330
2331               PrintDebug("VNET: return from Accepting Socket %d\n", connection_socket);
2332              
2333               if (connection_socket < 0){
2334                      PrintError("VNET: Accept failed");
2335                      return -1;
2336               }
2337
2338               //At this point our TCP connection is setup and running
2339               vnet_setup_handler(connection_socket, REMOTE, 0, 0);
2340         }while (0);
2341   }else { //vnet_host
2342         PrintDebug("VNET: In host status\n");
2343   
2344         //At this point our TCP connection is not setup
2345       vnet_setup_handler(-1, LOCAL, server_ip, server_port);
2346   }
2347
2348   return 0;
2349 }
2350
2351
2352 static int vnet_setup_udp()
2353 {
2354   uint_t client_ip = (0 | 172 << 24 | 23 << 16 | 2 );
2355   uint_t client_port = 22;
2356   int socket;
2357   uint_t server_ip =  (0 | 172 << 24 | 23 << 16 | 1 );
2358   uint_t server_port = 22;
2359   struct handler *hd;
2360
2361   hd = (struct handler *)V3_Malloc(sizeof(struct handler));
2362
2363   if ((socket = V3_Create_UDP_Socket()) < 0){
2364               PrintError("VNET: Can't setup udp socket\n");
2365               return -1; 
2366   }
2367
2368
2369   if (vnet_server) {// vnet_proxy
2370         PrintDebug("VNET: In proxy status local ip: %x, %d\n", server_ip, server_port);
2371         
2372        if (V3_Bind_Socket(socket, server_port) < 0){ 
2373                   PrintError("VNET: Can't bind socket\n");
2374                   return -1;
2375         }
2376
2377       hd->local_address = server_ip;
2378       hd->local_port = server_port;
2379       hd->remote_address = client_ip;
2380       hd->remote_port = client_port;
2381       hd->fd = socket;
2382       hd->remote_config = REMOTE;       
2383   }else { //vnet_host
2384         PrintDebug("VNET: In host status local ip: %x\n", client_ip);
2385
2386         if (V3_Bind_Socket(socket, client_port) < 0){ 
2387                   PrintError("VNET: Can't bind socket\n");
2388                   return -1;
2389         }
2390         
2391       hd->local_address = client_ip;
2392       hd->local_port = client_port;
2393       hd->remote_address = server_ip;
2394       hd->remote_port = server_port;
2395       hd->fd = socket;
2396       hd->remote_config = LOCAL;
2397   }
2398
2399   PrintDebug("VNET: vnet_setup_udp new handler: socket: %d local %x:[%d], remote %x:[%d]\n", hd->fd, hd->local_address, hd->local_port, hd->remote_address, hd->remote_port);
2400
2401   add_handler(hd);
2402                  
2403   PrintDebug("VNET: add handler: %d\n", hd->fd);
2404
2405   V3_CREATE_THREAD(&handler_thread, (void *)hd, "VNET_HANDLER");
2406
2407   return 0;
2408 }
2409
2410
2411 void vnet_init()
2412 {       
2413         int i=0;
2414
2415         #ifdef VNET_SERVER
2416                 vnet_server = 1;
2417         #endif
2418
2419         extern struct v3_socket_hooks * sock_hooks;
2420         PrintDebug("In VMM_SOCK: %p\n", sock_hooks);
2421
2422         PrintDebug("VNET Init: VNET_SERVER: %d\n", vnet_server);
2423
2424         vnet_inpkt_q = v3_create_queue();
2425         v3_init_queue(vnet_inpkt_q);
2426
2427         //queue for src_link_index -- YT
2428 #ifdef ROUTE
2429 //      src_link_index_q = v3_create_queue();
2430 //      v3_init_queue(src_link_index_q);
2431 #endif
2432
2433         for (i = 0; i < NUM_DEVICES; i++)
2434                 available_devices[i] = NULL;
2435
2436         for (i = 0; i < NUM_HANDLERS; i++)
2437                 active_handlers[i] = NULL;
2438
2439         if (use_tcp)
2440                 vnet_setup_tcp();
2441         else 
2442                 vnet_setup_udp();
2443
2444       //not continue on the guest
2445         //while(1){}
2446 }
2447
2448 #if 0
2449         
2450 static void test_send(int sock, int time)
2451 {
2452     char *buf = "\001\002\003\004\005\006\007\008\009\010\011\012\013\014\015\n";
2453     int i, j;
2454     int num;
2455
2456     i = time;
2457     while(i-- > 0){
2458         num = V3_Send_pkt((uchar_t *)buf, strlen(buf));
2459
2460         PrintDebug("VNET: In test Send: sent size %d\n", num);
2461         
2462         for (j = 0; i < strlen(buf); j++)
2463                 PrintDebug("%x ", buf[j]);
2464         PrintDebug("\n");
2465     }
2466 }
2467   
2468  #endif  
2469