Пример #1
0
/* ------------------------------------------------------------------------- *\
 * FUNCTION diskdb_setcurrent (host, rec)                                    *
 * --------------------------------------                                    *
 * Writes the provided record to /var/state/n2/current atomically, then      *
 * calls diskdb_store to write the record to the database as well, using     *
 * the current date/time as an index reference.                              *
\* ------------------------------------------------------------------------- */
void diskdb_setcurrent (unsigned long host, netload_rec *rec)
{
	char tempfilename[256];
	char permfilename[256];
	char ipstr[32];
	FILE *f;
	unsigned int date;
	int index;
	
	diskdb_now (&date, &index);
	
	printip (host, ipstr);
	sprintf (tempfilename, "/var/state/n2/tmp/%s", ipstr);
	sprintf (permfilename, "/var/state/n2/current/%s", ipstr);
	
	f = fopen (tempfilename, "w");
	if (! f)
	{
		fprintf (stderr, "diskdb_setcurrent: Could not open: %s: %s\n",
				 tempfilename, strerror (errno));
		return;
	}
	
	fwrite (rec, (size_t) 640, 1, f);
	fclose (f);
	rename (tempfilename, permfilename);

	diskdb_store (host, rec, date, index);
}
Пример #2
0
static void dhtstatus_onDraw(ToxWindow *self)
{
    Client_data   *close_clientlist = DHT_get_close_list();
    curs_set(0);
    werase(self->window);

    uint64_t now = unix_time();
    uint32_t i, j;
    ipbuf ipbuf;
    wprintw(self->window,
            "\n%llu  ______________________ CLOSE LIST ________________________  ___ IP ADDR ___ _PRT_   LST   PNG    ____ SELF ____ _PRT_  LST\n\n",
            now);

    for (i = 0; i < 32; i++) { /*Number of nodes in closelist*/
        Client_data *client = close_clientlist + i;

        if (i == num_selected) wattron(self->window, COLOR_PAIR(3));

        wprintw(self->window, "[%02i]  ", i);
        uint16_t port = ntohs(client->ip_port.port);

        if (port) {
            for (j = 0; j < CLIENT_ID_SIZE; j++)
                wprintw(self->window, "%02hhx", client->client_id[j]);

            printip(ipbuf, client->ip_port.ip);
            wprintw(self->window, "  %15s %5u ", ipbuf, port);
            wprintw(self->window, "  %3llu ", now - client->timestamp);
            wprintw(self->window, "  %3llu ", now - client->last_pinged);

            port = ntohs(client->ret_ip_port.port);

            if (port) {
                printip(ipbuf, client->ret_ip_port.ip);
                wprintw(self->window, "  %15s %5u  %3llu", ipbuf, port, now - close_clientlist[i].ret_timestamp);
            }
        }

        wprintw(self->window, "\n");

        if (i == num_selected) wattroff(self->window, COLOR_PAIR(3));
    }

    wrefresh(self->window);
}
Пример #3
0
/* ------------------------------------------------------------------------- *\
 * FUNCTION diskdb_open (host, date)                                         *
 * ---------------------------------                                         *
 * Looks for a diskdb in /var/state/n2/log matching the provided host        *
 * address and date. If none was found, this function will attempt to create *
 * a fresh database file with the required filename.                         *
\* ------------------------------------------------------------------------- */
FILE *diskdb_open (unsigned long host, unsigned int date)
{
	char filename[256];
	char dirname[256];
	char ipstr[32];
	struct stat statbuf;
	char *nullblock;
	FILE *res;
	int i;
	
	printip (host, ipstr);
	sprintf (dirname, "/var/state/n2/log/%s", ipstr);
	sprintf (filename, "/var/state/n2/log/%s/%s-%u.n2db", ipstr, ipstr, date);

	if (stat (dirname, &statbuf) != 0) mkdir (dirname, 0750);	
	
	if (stat (filename, &statbuf)) /* true if the file doesn't exist */
	{
		res = fopen (filename, "a+");
		if (! res)
		{
			fprintf (stderr, "diskdb_open: Could not create: %s: %s\n",
					 filename, strerror (errno));
			return NULL;
		}
		
		nullblock = (char *) calloc (1, (size_t) 92160);
		
		for (i=0; i<10; ++i)
		{
			fwrite (nullblock, (size_t) 92160, 1, res);
		}
		
		free (nullblock);
		fclose (res);
		res = fopen (filename, "r+");
		fseek (res, 0, SEEK_SET);
	}
	else
	{
		res = fopen (filename, "r+");
		if (! res)
		{
			fprintf (stderr, "diskdb_open: Could not open: %s: %s\n",
					 filename, strerror (errno));
			return NULL;
		}
		fseek (res, 0, SEEK_SET);
	}
	
	return res;
}
Пример #4
0
void printipmask(void (*putch) (int, void **), void **putdat, uint8_t * ip)
{
	int i, j, n;
	/* look for a prefix mask */
	for (i = 0; i < 16; i++)
		if (ip[i] != 0xff)
			break;
	if (i < 16) {
		if ((prefixvals[ip[i]] & Isprefix) == 0) {
			printip(putch, putdat, ip);
			return;
		}
		for (j = i + 1; j < 16; j++)
			if (ip[j] != 0) {
				printip(putch, putdat, ip);
				return;
			}
		n = 8 * i + (prefixvals[ip[i]] & ~Isprefix);
	} else
		n = 8 * 16;

	/* got one, use /xx format */
	printfmt(putch, putdat, "/%d", n);
}
Пример #5
0
/* ------------------------------------------------------------------------- *\
 * FUNCTION diskdb_get_current (host)                                        *
 * ----------------------------------                                        *
 * Reads the current from the disk database. If it runs into a lock it will  *
 * retry a number of times.                                                  *
\* ------------------------------------------------------------------------- */
netload_rec *diskdb_get_current (unsigned long host)
{
	int valid;
	int retries;
	FILE *f;
	size_t sz;
	char filename[256];
	char ipstr[32];
	netload_rec *rec;
	
	valid = 0;
	retries = 0;
	printip (host, ipstr);
	sprintf (filename, "/var/state/n2/current/%s", ipstr);
	
	f = fopen (filename, "r");
	if (! f)
	{
		fprintf (stderr, "diskdb_get_current: Could not open: %s: %s\n",
				 filename, strerror (errno));
		return NULL;
	}
	
	rec = (netload_rec *) calloc (1, sizeof (netload_rec));

	if ((sz = fread (rec, 1, 640, f) != 640))
	{
		fprintf (stderr, "diskdb_get: Short read sz=%u\n", sz);
		fclose (f);
		free (rec);
		return NULL;
	}
	
	rec->pos = 4;
	rec->rpos = 2;
	rec->eof = 0;
	sz = rec_read16 (rec);
	rec->pos = sz;
	rec->rpos = 0;
	rec->eof = 0;
	
	fclose (f);
	return rec;
}
Пример #6
0
void Disassembler::disassemble(const char *filename)
{
	open(filename);

	word start;
	if ((1 != fread(&start, sizeof(word), 1, m_fp))) {
		throw Exception("can't read from file \"%s\": %s", filename,
		                strerror(errno));
	}

	PxDisassembler::ip = start;

	int c;
	while ((c = fgetc(m_fp)) != EOF) {
		ungetc(c, m_fp);
		printip();
		PxDisassembler::disassemble(fetch());
	}

	close();
}
Пример #7
0
bool
bootpc_init(bool update_files, bool forever)
{
  struct bootp_packet call;
  struct bootp_packet reply;
  static u_int32_t xid = ~0xFF;
  
  struct ifreq ireq;
  struct ifnet *ifp;
  struct socket *so;
  int j;
  int error;
  struct sockaddr_in myaddr;
  struct ifaddr *ifa;
  struct sockaddr_dl *sdl = NULL;
  char *delim;
  struct proc *procp = NULL;

  /*
   * If already filled in, don't touch it here 
   */
  if (nfs_diskless_valid)
    return true;

  /*
   * If we are to update the files create the root
   * file structure.
   */
  if (update_files)
    if (rtems_create_root_fs () < 0) {
      printf("Error creating the root filesystem.\nFile not created.\n");
      update_files = 0;
    }

  if (dhcp_hostname != NULL) {
	/* free it */
    dhcp_hostname=bootp_strdup_realloc(dhcp_hostname,0);
  }

  /*
   * Find a network interface.
   */
  for (ifp = ifnet; ifp != 0; ifp = ifp->if_next)
    if ((ifp->if_flags &
      (IFF_LOOPBACK|IFF_POINTOPOINT)) == 0)
	break;
  if (ifp == NULL) {
    printf("bootpc_init: no suitable interface\n");
    return false;
  }
  bzero(&ireq,sizeof(ireq));
  sprintf(ireq.ifr_name, "%s%d", ifp->if_name,ifp->if_unit);
  printf("bootpc_init: using network interface '%s'\n",
	 ireq.ifr_name);

  if ((error = socreate(AF_INET, &so, SOCK_DGRAM, 0,procp)) != 0) {
    printf("bootpc_init: socreate, error=%d", error);
    return false;
  }
  if (bootpc_fakeup_interface(&ireq,so,procp) != 0) {
    soclose(so);
    return false;
  }

  /* Get HW address */

  for (ifa = ifp->if_addrlist;ifa; ifa = ifa->ifa_next)
    if (ifa->ifa_addr->sa_family == AF_LINK &&
        (sdl = ((struct sockaddr_dl *) ifa->ifa_addr)) &&
        sdl->sdl_type == IFT_ETHER)
      break;
  
  if (!sdl) {
    printf("bootpc: Unable to find HW address\n");
    soclose(so);
    return false;
  }
  if (sdl->sdl_alen != EALEN ) {
    printf("bootpc: HW address len is %d, expected value is %d\n",
	   sdl->sdl_alen,EALEN);
    soclose(so);
    return false;
  }

  printf("bootpc hw address is ");
  delim="";
  for (j=0;j<sdl->sdl_alen;j++) {
    printf("%s%x",delim,((unsigned char *)LLADDR(sdl))[j]);
    delim=":";
  }
  printf("\n");

#if 0
  bootpboot_p_iflist();
  bootpboot_p_rtlist();
#endif

  while (true) {
    bzero((caddr_t) &call, sizeof(call));

    /* bootpc part */
    call.op = 1; 			/* BOOTREQUEST */
    call.htype= 1;		/* 10mb ethernet */
    call.hlen=sdl->sdl_alen;	/* Hardware address length */
    call.hops=0;	
    xid++;
    call.xid = txdr_unsigned(xid);
    bcopy(LLADDR(sdl),&call.chaddr,sdl->sdl_alen);
  
    call.vend[0]=99;
    call.vend[1]=130;
    call.vend[2]=83;
    call.vend[3]=99;
    call.vend[4]=255;
  
    call.secs = 0;
    call.flags = htons(0x8000); /* We need an broadcast answer */
  
    error = bootpc_call(&call,&reply,procp);
  
    if (!error)
      break;
    
    printf("BOOTP call failed -- error %d", error);

    if (!forever) {
      soclose(so);
      return false;
    }
  }
  
  /*
   * Initialize network address structures
   */
  bzero(&myaddr,sizeof(myaddr));
  bzero(&dhcp_netmask,sizeof(dhcp_netmask));
  bzero(&dhcp_gw,sizeof(dhcp_gw));
  myaddr.sin_len = sizeof(myaddr);
  myaddr.sin_family = AF_INET;
  dhcp_netmask.sin_len = sizeof(dhcp_netmask);
  dhcp_netmask.sin_family = AF_INET;
  dhcp_gw.sin_len = sizeof(dhcp_gw);
  dhcp_gw.sin_family= AF_INET;

  /*
   * Set our address
   */
  myaddr.sin_addr = reply.yiaddr;
  printip("My ip address",myaddr.sin_addr);

  /*
   * Process BOOTP/DHCP options
   */
  if (reply.vend[0]==99 && reply.vend[1]==130 &&
      reply.vend[2]==83 && reply.vend[3]==99) {
    processOptions (&reply.vend[4], sizeof(reply.vend) - 4);
  }
  if (dhcpOptionOverload & 1) {
    processOptions ((unsigned char *)reply.file, sizeof reply.file);
  }
  else {
    if (reply.file[0])
      rtems_bsdnet_bootp_boot_file_name = 
	bootp_strdup_realloc(rtems_bsdnet_bootp_boot_file_name,reply.file);
  }
  if (dhcpOptionOverload & 2) {
    processOptions ((unsigned char *)reply.sname, sizeof reply.sname);
  }
  else {
    if (reply.sname[0])
      rtems_bsdnet_bootp_server_name = 
	bootp_strdup_realloc(rtems_bsdnet_bootp_server_name,reply.sname);
  }
  if (rtems_bsdnet_bootp_server_name)
    printf ("Server name is %s\n", rtems_bsdnet_bootp_server_name);
  if (rtems_bsdnet_bootp_boot_file_name)
    printf ("Boot file is %s\n", rtems_bsdnet_bootp_boot_file_name);
  if (rtems_bsdnet_bootp_cmdline)
    printf ("Command line is %s\n", rtems_bsdnet_bootp_cmdline);

  /*
   * Use defaults if values were not supplied by BOOTP/DHCP options
   */
  if (!dhcp_gotnetmask) {
    if (IN_CLASSA(ntohl(myaddr.sin_addr.s_addr)))
      dhcp_netmask.sin_addr.s_addr = htonl(IN_CLASSA_NET);
    else if (IN_CLASSB(ntohl(myaddr.sin_addr.s_addr)))
      dhcp_netmask.sin_addr.s_addr = htonl(IN_CLASSB_NET);
    else 
      dhcp_netmask.sin_addr.s_addr = htonl(IN_CLASSC_NET);
  }
  printip ("Subnet mask", dhcp_netmask.sin_addr);
  if (!dhcp_gotserver)
   rtems_bsdnet_bootp_server_address = reply.siaddr;
  printip ("Server ip address" ,rtems_bsdnet_bootp_server_address);
  if (!dhcp_gotgw)
    dhcp_gw.sin_addr = reply.giaddr;
  printip ("Gateway ip address", dhcp_gw.sin_addr);
  if (!dhcp_gotlogserver)
    rtems_bsdnet_log_host_address = rtems_bsdnet_bootp_server_address;
  printip ("Log server ip address", rtems_bsdnet_log_host_address);

  /*
   * Update the files if we are asked too.
   */
  if (update_files) {
    char *dn = rtems_bsdnet_domain_name;
    char *hn = dhcp_hostname;
    if (!dn)
      dn = "mydomain";
    if (!hn)
      hn = "me";
    rtems_rootfs_append_host_rec(myaddr.sin_addr.s_addr, hn, dn);

    /*
     * Should the given domainname be used here ?
     */
    if (dhcp_gotserver) {
      if (rtems_bsdnet_bootp_server_name)
        hn = rtems_bsdnet_bootp_server_name;
      else
        hn = "bootps";
      rtems_rootfs_append_host_rec(rtems_bsdnet_bootp_server_address.s_addr,
                                   hn, dn);
    }

    if (dhcp_gotlogserver) {
      rtems_rootfs_append_host_rec(rtems_bsdnet_log_host_address.s_addr,
                                   "logs", dn);
    }

    /*
     * Setup the DNS configuration file /etc/resolv.conf.
     */
    if (rtems_bsdnet_nameserver_count) {
      int        i;
      char       buf[64];
      const char *bufl[1];

      bufl[0] = buf;
      
#define MKFILE_MODE (S_IRUSR | S_IWUSR | S_IWGRP | S_IRGRP | S_IROTH)
      
      if (rtems_bsdnet_domain_name &&
          (strlen(rtems_bsdnet_domain_name) < (sizeof(buf) - 1))) {
        strcpy(buf, "search ");
        strcat(buf, rtems_bsdnet_domain_name);
        strcat(buf, "\n");
        rtems_rootfs_file_append ("/etc/resolv.conf", MKFILE_MODE, 1, bufl);
      }

      for (i = 0; i < rtems_bsdnet_nameserver_count; i++) {
        strcpy(buf, "nameserver ");
        strcat(buf, inet_ntoa(rtems_bsdnet_nameserver[i]));
        strcat(buf, "\n");
        if (rtems_rootfs_file_append ("/etc/resolv.conf", MKFILE_MODE, 1, bufl))
          break;
      }
    }
  }

  /*
   * Configure the interface with the new settings
   */
  error = bootpc_adjust_interface(&ireq,so,
				  &myaddr,&dhcp_netmask,&dhcp_gw,procp);
  soclose(so);

  return true;
}
/*
 * IPCP RX protocol Handler
 */
void
ipv6cp_rx(u8_t *buffer, u16_t count)
{
  u8_t *bptr = buffer;
//  IPCPPKT *pkt=(IPCPPKT *)buffer;
  u16_t len;

  ANNOTATE("IPV6CP len %d\n",count);
	
  switch(*bptr++) {

  case CONF_REQ:
    /* parce request and see if we can ACK it */
    ++bptr;
    len = (*bptr++ << 8);
    len |= *bptr++;
    /* len-=2; */

    ANNOTATE("check lcplist\n");
    if(scan_packet(IPV6CP, ipv6cplist, buffer, bptr, (u16_t)(len - 4))) {
      UIP_LOG("option was bad\n");
    } else {
      ANNOTATE("IPV6CP options are good\n");
      /*
       * Parse out the results
       */
      /* lets try to implement what peer wants */
      /* Reject any protocol not */
      /* Error? if we we need to send a config Reject ++++ this is
	 good for a subroutine*/
      //GD-2011-09-15 None of the IPv6CP options are supported with current implementation.
#if 0
#warning option implementation example based on IPCP IPv4 address configuration.
      /* All we should get is the peer IP address */
      if(IPV6CP_IPADDRESS == *bptr++) {
	         /* dump length */
	         ++bptr;
         #ifdef IPV6CP_GET_PEER_IP
	         ((u8_t*)peer_ip_addr.u8)[0] = *bptr++;
	         ((u8_t*)peer_ip_addr.u8)[1] = *bptr++;
	         ((u8_t*)peer_ip_addr.u8)[2] = *bptr++;
	         ((u8_t*)peer_ip_addr.u8)[3] = *bptr++;
	         ANNOTATE("Peer IP ");
	         /*	printip(peer_ip_addr);*/
	         ANNOTATE("\n");
         #else
	         bptr += 18;
         #endif
      } else {
	      UIP_LOG("HMMMM this shouldn't happen IPV6CP1\n");
      }
#endif
      
#if 0			
      if(error) {
	      /* write the config NAK packet we've built above, take on the header */
	      bptr = buffer;
	      *bptr++ = CONF_NAK;		/* Write Conf_rej */
	      *bptr++;
	      /*tptr++;*/  /* skip over ID */

	      /* Write new length */
	      *bptr++ = 0;
	      *bptr = tptr - buffer;
	      
	      /* write the reject frame */
	      UIP_LOG("Writing NAK frame \n");
	      ahdlc_tx(IPV6CP, buffer, (u16_t)(tptr - buffer));
	      ANNOTATE("- End NAK Write frame\n");
	      
      } else {
      }
#endif
         /*
          * If we get here then we are OK, lets send an ACK and tell the rest
          * of our modules our negotiated config.
          */
         ipv6cp_state |= IPV6CP_RX_UP;
         ipv6cp_state &= ~IPV6CP_TX_UP;//phlb force send request with ipv6cp task
         ANNOTATE("Send IPV6CP ACK!\n");
         bptr = buffer;
         *bptr++ = CONF_ACK;		/* Write Conf_ACK */
         bptr++;				/* Skip ID (send same one) */
         /*
          * Set stuff
          */
         ppp_flags |= tflag;
         ANNOTATE("SET- stuff -- are we up? c=%d dif=%d \n", count, (u16_t)(bptr-buffer));
	   
         /* write the ACK frame */
         ANNOTATE("Writing ACK frame \n");
         /* Send packet ahdlc_txz(procol,header,data,headerlen,datalen);	*/
         ahdlc_tx(IPV6CP, 0, buffer, 0, count /*bptr-buffer*/);
         ANNOTATE("- End ACK Write frame\n");
	   
         /* expire the timer to make things happen after a state change */
         TIMER_expire(); //timer_expire(); //modify phlb uncomment
	   
         /*			} */
    }
    break;
    
    //
  case CONF_ACK:			/* config Ack */
       ANNOTATE("CONF ACK\n");
       /*
        * Parse out the results
        *
        * Dump the ID and get the length.
        */
       /* dump the ID */
       bptr++;

       /* get the length */
       len = (*bptr++ << 8);
       len |= *bptr++;
   #if 0 //modify phlb 
       /* Parse ACK and set data */
       while(bptr < buffer + len) {
         switch(*bptr++) {
         case IPV6CP_IPADDRESS:
	   /* dump length */
	   bptr++;		
	   ((u8_t*)ipaddr)[0] = *bptr++;
	   ((u8_t*)ipaddr)[1] = *bptr++;
	   ((u8_t*)ipaddr)[2] = *bptr++;
	   ((u8_t*)ipaddr)[3] = *bptr++;
	   break;
         case IPV6CP_PRIMARY_DNS:
	   bptr++;
	   ((u8_t*)pri_dns_addr)[0] = *bptr++;
	   ((u8_t*)pri_dns_addr)[1] = *bptr++;
	   ((u8_t*)pri_dns_addr)[2] = *bptr++;
	   ((u8_t*)pri_dns_addr)[3] = *bptr++;
	   break;
         case IPV6CP_SECONDARY_DNS:
	   bptr++;
	   ((u8_t*)sec_dns_addr)[0] = *bptr++;
	   ((u8_t*)sec_dns_addr)[1] = *bptr++;
	   ((u8_t*)sec_dns_addr)[2] = *bptr++;
	   ((u8_t*)sec_dns_addr)[3] = *bptr++;
	   break;
         default:
	   UIP_LOG("IPV6CP CONFIG_ACK problem1\n");
         }
       }
   #endif
       ipv6cp_state |= IPV6CP_TX_UP;
       //ipv6cp_state &= ~IPV6CP_RX_UP;
       ANNOTATE("were up! \n");
       printip(pppif.ipaddr);
   #ifdef IPV6CP_GET_PRI_DNS
       printip(pri_dns_addr);
   #endif
   #ifdef IPV6CP_GET_SEC_DNS
       printip(sec_dns_addr);
   #endif
       ANNOTATE("\n");
		   
       /* expire the timer to make things happen after a state change */
       TIMER_expire();
    break;

    //
  case CONF_NAK:			/* Config Nack */
    UIP_LOG("CONF NAK\n");
    /* dump the ID */
    bptr++;
    /* get the length */
    len = (*bptr++ << 8);
    len |= *bptr++;

    /* Parse ACK and set data */
    while(bptr < buffer + len) {
      switch(*bptr++) {
#if 0
#warning option implementation example based on IPCP IPv4 address configuration.
               case IPV6CP_IPADDRESS:
	         /* dump length */
	         bptr++;
	         ((u8_t*)pppif.ipaddr.u8)[0] = *bptr++;
	         ((u8_t*)pppif.ipaddr.u8)[1] = *bptr++;
	         ((u8_t*)pppif.ipaddr.u8)[2] = *bptr++;
	         ((u8_t*)pppif.ipaddr.u8)[3] = *bptr++;
	         uip_fw_register( &pppif );
	         ANNOTATE("My PPP-ipno: (%d.%d.%d.%d)\n", ((u8_t*)pppif.ipaddr.u8)[0], ((u8_t*)pppif.ipaddr.u8)[1], ((u8_t*)pppif.ipaddr.u8)[2], ((u8_t*)pppif.ipaddr.u8)[3]); 
	         break;
#endif
         #ifdef IPV6CP_GET_PRI_DNS
               case IPV6CP_PRIMARY_DNS:
	         bptr++;
	         ((u8_t*)pri_dns_addr)[0] = *bptr++;
	         ((u8_t*)pri_dns_addr)[1] = *bptr++;
	         ((u8_t*)pri_dns_addr)[2] = *bptr++;
	         ((u8_t*)pri_dns_addr)[3] = *bptr++;
	         break;
         #endif
         #ifdef IPV6CP_GET_SEC_DNS
               case IPV6CP_SECONDARY_DNS:
	         bptr++;
	         ((u8_t*)sec_dns_addr)[0] = *bptr++;
	         ((u8_t*)sec_dns_addr)[1] = *bptr++;
	         ((u8_t*)sec_dns_addr)[2] = *bptr++;
	         ((u8_t*)sec_dns_addr)[3] = *bptr++;
	         break;
         #endif

            //
            default:
	            UIP_LOG("IPCP CONFIG_ACK problem 2\n");
          }
       }
       ppp_id++;
       printip(pppif.ipaddr);
   #ifdef IPV6CP_GET_PRI_DNS
       printip(pri_dns_addr);
   #endif
   #ifdef IPV6CP_GET_PRI_DNS
       printip(sec_dns_addr);
   #endif
       ANNOTATE("\n");
       /* expire the timer to make things happen after a state change */
       TIMER_expire();
       break;

     case CONF_REJ:			/* Config Reject */
       ANNOTATE("CONF REJ\n");
       /* Remove the offending options*/
       ppp_id++;
       /* dump the ID */
       bptr++;
       /* get the length */
       len = (*bptr++ << 8);
       len |= *bptr++;

       /* Parse ACK and set data */
       while(bptr < buffer + len) {
         switch(*bptr++) {
#if 0
#warning option implementation example based on IPCP IPv4 address configuration.
            case IPV6CP_IPADDRESS:
	         ipv6cp_state |= IPV6CP_IP_BIT;
	         bptr += 5;
	         break;
#endif

         #ifdef IPV6CP_GET_PRI_DNS
            case IPV6CP_PRIMARY_DNS:
	         ipv6cp_state |= IPV6CP_PRI_DNS_BIT;
	         bptr += 5;
	         break;
         #endif

         #ifdef IPV6CP_GET_PRI_DNS
             case IPV6CP_SECONDARY_DNS:
	         ipv6cp_state |= IPV6CP_SEC_DNS_BIT;
	         bptr += 5;
	         break;
         #endif

            default:
	         UIP_LOG("IPV6CP this shoudln't happen 3\n");
         }
    }
    /* expire the timer to make things happen after a state change */
    /*timer_expire(); */
    break;

    default:
      UIP_LOG("-Unknown 4\n");
  }
}
Пример #9
0
void ipcp_rx(struct ppp_context_s *ctx, u8_t *buffer, u16_t count)
{
  u8_t *bptr = buffer;
  //IPCPPKT *pkt=(IPCPPKT *)buffer;
  u16_t len;

  DEBUG1(("IPCP len %d\n",count));

  switch (*bptr++)
  {
  case CONF_REQ:
    /* Parse request and see if we can ACK it */

    ++bptr;
    len = (*bptr++ << 8);
    len |= *bptr++;
    /* len-=2; */

    DEBUG1(("check lcplist\n"));
    if (scan_packet(ctx, IPCP, ipcplist, buffer, bptr, (u16_t)(len - 4)))
      {
        DEBUG1(("option was bad\n"));
      }
    else
      {
        DEBUG1(("IPCP options are good\n"));

        /* Parse out the results */
        /* lets try to implement what peer wants */
        /* Reject any protocol not */
        /* Error? if we we need to send a config Reject ++++ this is good for a subroutine*/
        /* All we should get is the peer IP address */

        if (IPCP_IPADDRESS == *bptr++)
          {
            /* Dump length */

            ++bptr;
#ifdef IPCP_GET_PEER_IP
            ((u8_t*)&ctx->peer_ip)[0] = *bptr++;
            ((u8_t*)&ctx->peer_ip)[1] = *bptr++;
            ((u8_t*)&ctx->peer_ip)[2] = *bptr++;
            ((u8_t*)&ctx->peer_ip)[3] = *bptr++;

            DEBUG1(("Peer IP "));
            /* printip(peer_ip_addr); */
            DEBUG1(("\n"));

            netlib_set_dripv4addr((char*)ctx->ifname, &ctx->peer_ip);
#else
            bptr += 4;
#endif
          }
        else
          {
            DEBUG1(("HMMMM this shouldn't happen IPCP1\n"));
          }

#if 0
        if (error)
          {
            /* Write the config NAK packet we've built above, take on the header */

            bptr = buffer;
            *bptr++ = CONF_NAK;        /* Write Conf_rej */
            *bptr++;
            /*tptr++;*/  /* skip over ID */

            /* Write new length */

            *bptr++ = 0;
            *bptr = tptr - buffer;

            /* Write the reject frame */

            DEBUG1(("Writing NAK frame \n"));
            ahdlc_tx(IPCP, buffer, (u16_t)(tptr - buffer));
            DEBUG1(("- End NAK Write frame\n"));
          }
        else
          {
          }
#endif
        /* If we get here then we are OK, lets send an ACK and tell the rest
         * of our modules our negotiated config.
         */

        ctx->ipcp_state |= IPCP_RX_UP;
        DEBUG1(("Send IPCP ACK!\n"));
        bptr = buffer;
        *bptr++ = CONF_ACK; /* Write Conf_ACK */
        bptr++;             /* Skip ID (send same one) */

        /* Set stuff */

        /* ppp_flags |= tflag; */
        DEBUG1(("SET- stuff -- are we up? c=%d dif=%d \n", count, (u16_t)(bptr - buffer)));

        /* Write the ACK frame */

        DEBUG1(("Writing ACK frame \n"));

        /* Send packet ahdlc_txz(procol,header,data,headerlen,datalen); */

        ahdlc_tx(ctx, IPCP, 0, buffer, 0, count /*bptr-buffer*/);
        DEBUG1(("- End ACK Write frame\n"));
      }
    break;

  case CONF_ACK: /* config Ack */
    DEBUG1(("CONF ACK\n"));
    /* Parse out the results
     *
     * Dump the ID and get the length.
     */

    /* Dump the ID */

    bptr++;

    /* Get the length */

    len = (*bptr++ << 8);
    len |= *bptr++;

#if 0
    /* Parse ACK and set data */

    while (bptr < buffer + len)
      {
        switch (*bptr++)
        {
        case IPCP_IPADDRESS:
          /* Dump length */

          bptr++;
          ((u8_t*)ipaddr)[0] = *bptr++;
          ((u8_t*)ipaddr)[1] = *bptr++;
          ((u8_t*)ipaddr)[2] = *bptr++;
          ((u8_t*)ipaddr)[3] = *bptr++;
          break;

        case IPCP_PRIMARY_DNS:
          bptr++;
          ((u8_t*)pri_dns_addr)[0] = *bptr++;
          ((u8_t*)pri_dns_addr)[1] = *bptr++;
          ((u8_t*)pri_dns_addr)[2] = *bptr++;
          ((u8_t*)pri_dns_addr)[3] = *bptr++;
          break;

        case IPCP_SECONDARY_DNS:
          bptr++;
          ((u8_t*)sec_dns_addr)[0] = *bptr++;
          ((u8_t*)sec_dns_addr)[1] = *bptr++;
          ((u8_t*)sec_dns_addr)[2] = *bptr++;
          ((u8_t*)sec_dns_addr)[3] = *bptr++;
          break;

        default:
           DEBUG1(("IPCP CONFIG_ACK problem1\n"));
        }
      }
#endif

    ctx->ipcp_state |= IPCP_TX_UP;
    /*ppp_ipcp_state &= ~IPCP_RX_UP;*/

    DEBUG1(("were up! \n"));
    //printip(pppif.ipaddr);
#ifdef IPCP_GET_PRI_DNS
    printip(pri_dns_addr);
#endif
#ifdef IPCP_GET_SEC_DNS
    printip(sec_dns_addr);
#endif
    DEBUG1(("\n"));
    break;

  case CONF_NAK: /* Config Nack */
    DEBUG1(("CONF NAK\n"));

    /* Dump the ID */

    bptr++;

    /* Get the length */

    len = (*bptr++ << 8);
    len |= *bptr++;

    /* Parse ACK and set data */

    while (bptr < buffer + len)
      {
        switch (*bptr++)
        {
        case IPCP_IPADDRESS:
          /* dump length */
          bptr++;

          ((u8_t*)&ctx->local_ip)[0] = (char)*bptr++;
          ((u8_t*)&ctx->local_ip)[1] = (char)*bptr++;
          ((u8_t*)&ctx->local_ip)[2] = (char)*bptr++;
          ((u8_t*)&ctx->local_ip)[3] = (char)*bptr++;

          netlib_ifup((char*)ctx->ifname);
          netlib_set_ipv4addr((char*)ctx->ifname, &ctx->local_ip);
          //DEBUG1(("My PPP-ipno: (%d.%d.%d.%d)\n", ((u8_t*)pppif.ipaddr)[0], ((u8_t*)pppif.ipaddr)[1], ((u8_t*)pppif.ipaddr)[2], ((u8_t*)pppif.ipaddr)[3]));
          break;

#ifdef IPCP_GET_PRI_DNS
        case IPCP_PRIMARY_DNS:
          bptr++;
          ((u8_t*)&ctx->pri_dns_addr)[0] = *bptr++;
          ((u8_t*)&ctx->pri_dns_addr)[1] = *bptr++;
          ((u8_t*)&ctx->pri_dns_addr)[2] = *bptr++;
          ((u8_t*)&ctx->pri_dns_addr)[3] = *bptr++;
          break;
#endif

#ifdef IPCP_GET_SEC_DNS
        case IPCP_SECONDARY_DNS:
          bptr++;
          ((u8_t*)&ctx->sec_dns_addr)[0] = *bptr++;
          ((u8_t*)&ctx->sec_dns_addr)[1] = *bptr++;
          ((u8_t*)&ctx->sec_dns_addr)[2] = *bptr++;
          ((u8_t*)&ctx->sec_dns_addr)[3] = *bptr++;
          break;
#endif

        default:
          DEBUG1(("IPCP CONFIG_ACK problem 2\n"));
        }
      }

    ctx->ppp_id++;

    printip(pppif.ipaddr);
#ifdef IPCP_GET_PRI_DNS
    printip(pri_dns_addr);
#endif
#ifdef IPCP_GET_PRI_DNS
    printip(sec_dns_addr);
#endif
    DEBUG1(("\n"));
    break;

  case CONF_REJ: /* Config Reject */
    DEBUG1(("CONF REJ\n"));

    /* Remove the offending options*/

    ctx->ppp_id++;

    /* Dump the ID */

    bptr++;

    /* Get the length */

    len = (*bptr++ << 8);
    len |= *bptr++;

    /* Parse ACK and set data */

    while (bptr < buffer + len)
      {
        switch (*bptr++)
        {
        case IPCP_IPADDRESS:
          ctx->ipcp_state |= IPCP_IP_BIT;
          bptr += 5;
          break;

#ifdef IPCP_GET_PRI_DNS
        case IPCP_PRIMARY_DNS:
          ctx->ipcp_state |= IPCP_PRI_DNS_BIT;
          bptr += 5;
          break;
#endif

#ifdef IPCP_GET_PRI_DNS
        case IPCP_SECONDARY_DNS:
          ctx->ipcp_state |= IPCP_SEC_DNS_BIT;
          bptr += 5;
          break;
#endif

        default:
          DEBUG1(("IPCP this shoudln't happen 3\n"));
        }
      }
    break;

  default:
    DEBUG1(("-Unknown 4\n"));
  }
}
Пример #10
0
static void
processOptions (unsigned char *optbuf, int optbufSize)
{
  int j = 0;
  int len;
  int code, ncode;
  unsigned char *p;

  ncode = optbuf[0];
  while (j < optbufSize) {
    code = optbuf[j] = ncode;
    if (code == 255)
      return;
    if (code == 0) {
      j++;
      continue;
    }
    len = optbuf[j+1];
    j += 2;
    if ((len + j) >= optbufSize) {
      printf ("Truncated field for code %d", code);
      return;
    }
    ncode = optbuf[j+len];
    optbuf[j+len] = '\0';
    p = &optbuf[j];
    j += len;

    /*
     * Process the option
     */
    switch (code) {
    case 1:
      /* Subnet mask */
      if (len!=4) {
        printf("bootpc: subnet mask len is %d\n",len);
        continue;
      }
      bcopy (p, &dhcp_netmask.sin_addr, 4);
      dhcp_gotnetmask = 1;
      break;

    case 2:
      /* Time offset */
      if (len!=4) {
        printf("bootpc: time offset len is %d\n",len);
        continue;
      }
      bcopy (p, &rtems_bsdnet_timeoffset, 4);
      rtems_bsdnet_timeoffset = ntohl (rtems_bsdnet_timeoffset);
      break;

    case 3:
      /* Routers */
      if (len % 4) {
        printf ("bootpc: Router Len is %d\n", len);
        continue;
      }
      if (len > 0) {
        bcopy(p, &dhcp_gw.sin_addr, 4);
	dhcp_gotgw = 1;
      }
      break;

    case 42:
      /* NTP servers */
      if (len % 4) {
        printf ("bootpc: time server Len is %d\n", len);
        continue;
      }
      {
      int tlen = 0;
      while ((tlen < len) &&
             (rtems_bsdnet_ntpserver_count < sizeof rtems_bsdnet_config.ntp_server /
             sizeof rtems_bsdnet_config.ntp_server[0])) {
        bcopy (p+tlen,
		&rtems_bsdnet_ntpserver[rtems_bsdnet_ntpserver_count],
		4);
        printip("Time Server",
          rtems_bsdnet_ntpserver[rtems_bsdnet_ntpserver_count]);
        rtems_bsdnet_ntpserver_count++;
        tlen += 4;
      }
      }
      break;

    case 6:
      /* Domain Name servers */
      if (len % 4) {
        printf ("bootpc: DNS Len is %d", len);
        continue;
      }
      {
      int dlen = 0;
      while ((dlen < len) &&
             (rtems_bsdnet_nameserver_count < sizeof rtems_bsdnet_config.name_server /
        sizeof rtems_bsdnet_config.name_server[0])) {
        bcopy (p+dlen,
        &rtems_bsdnet_nameserver[rtems_bsdnet_nameserver_count],
        4);
        printip("Domain Name Server",
          rtems_bsdnet_nameserver[rtems_bsdnet_nameserver_count]);
        rtems_bsdnet_nameserver_count++;
        dlen += 4;
      }
      }
      break;

    case 12:
      /* Host name */
      if (len>=MAXHOSTNAMELEN) {
        printf ("bootpc: hostname >=%d bytes", MAXHOSTNAMELEN);
        continue;
      }
      if (sethostname ((char *)p, len) < 0) {
        printf("bootpc: Can't set host name");
      }
      printf("Hostname is %s\n", p);
      dhcp_hostname = bootp_strdup_realloc(dhcp_hostname,(char *)p);
      break;

    case 7:
      /* Log servers */
      if (len % 4) {
        printf ("bootpc: Log server Len is %d", len);
        continue;
      }
      if (len > 0) {
        bcopy(p, &rtems_bsdnet_log_host_address, 4);
	dhcp_gotlogserver = 1;
      }
      break;

    case 15:
      /* Domain name */
      if (p[0]) {
        rtems_bsdnet_domain_name = 
	  bootp_strdup_realloc(rtems_bsdnet_domain_name,(char *)p);
        printf("Domain name is %s\n", rtems_bsdnet_domain_name);
      }
      break;

    case 16:  /* Swap server IP address. unused */
      break;

    case 52:
      /* DHCP option override */
      if (len != 1) {
        printf ("bootpc: DHCP option overload len is %d", len);
        continue;
      }
      dhcpOptionOverload = p[0];
      break;

    case 128: /* Site-specific option for DHCP servers that 
               *   a) don't supply tag 54
               * and
               *   b) don't supply the server address in siaddr
               * For example, on Solaris 2.6 in.dhcpd, include in the dhcptab:
               *    Bootsrv s Site,128,IP,1,1
               * and use that symbol in the macro that defines the client:
               *    Bootsrv=<tftp-server-ip-address>
               */
    case 54:
      /* DHCP server */
      if (len != 4) {
        printf ("bootpc: DHCP server len is %d", len);
        continue;
      }
      bcopy(p, &rtems_bsdnet_bootp_server_address, 4);
      dhcp_gotserver = 1;
      break;

    case 66:
      /* DHCP server name option */
      if (p[0])
        rtems_bsdnet_bootp_server_name = 
	  bootp_strdup_realloc(rtems_bsdnet_bootp_server_name,(char *)p);
      break;

    case 67:
      /* DHCP bootfile option */
      if (p[0])
        rtems_bsdnet_bootp_boot_file_name = 
	  bootp_strdup_realloc(rtems_bsdnet_bootp_boot_file_name,(char *)p);
      break;

	case 129:
	  /* Site specific option; we use this to get 
	   * a 'command line string'
	   */
	  if (p[0])
	  	rtems_bsdnet_bootp_cmdline = strdup((char *)p);
	  break;

    default:
      printf ("Ignoring BOOTP/DHCP option code %d\n", code);
      break;
    }
  }
}
Пример #11
0
/* ------------------------------------------------------------------------- *\
 * FUNCTION diskdb_get (host, date, index)                                   *
 * ---------------------------------------                                   *
 * Reads a record from the disk database. If it runs into a lock it will     *
 * retry a number of times.                                                  *
\* ------------------------------------------------------------------------- */
netload_rec *diskdb_get (unsigned long host, unsigned int date, int index)
{
	int valid;
	int retries;
	FILE *f;
	size_t sz;
	struct stat st;
	char filename[256];
	char oldfilename[256];
	char dirname[256];
	char ipstr[32];
	netload_rec *rec;
	
	valid = 0;
	retries = 0;
	printip (host, ipstr);
	sprintf (filename, "/var/state/n2/log/%s/%s-%u.n2db", ipstr, ipstr, date);
	
	f = fopen (filename, "r");
	if (! f)
	{
		return NULL;
	}
	
	while (! valid)
	{
		if (fseek (f, 640 * index, SEEK_SET))
		{
			fprintf (stderr, "diskdb_get: Failed seek offset=%i\n", 640 * index);
			fclose (f);
			return NULL;
		}
	
		rec = (netload_rec *) calloc (1, sizeof (netload_rec));
	
		if ((sz = fread (rec, 1, 640, f) != 640))
		{
			fprintf (stderr, "diskdb_get: Short read sz=%u\n", sz);
			fclose (f);
			free (rec);
			return NULL;
		}
		
		rec->pos = 4;
		rec->rpos = 2;
		rec->eof = 0;
		sz = rec_read16 (rec);
		rec->pos = sz;
		rec->rpos = 0;
		rec->eof = 0;
		
		if (! diskdb_locked (rec))
		{
			valid = 1;
		}
		else
		{
			++retries;
			if (retries > 8)
			{
				fprintf (stderr, "diskdb_get: Stale lock, overriding\n");
				valid = 1;
			}
			else
			{
				free (rec);
				usleep (100);
			}
		}
	}
	
	fclose (f);
	return rec;
}
Пример #12
0
static void dhcp_cb(void *data, size_t sz, uint32_t srcip, uint16_t srcport, void *arg) {
	dhcp_msg_t *msg = data;
	u8 *opt;
	u32 netmask = 0;
	u32 gateway = 0;
	u32 dns = 0;
	u32 server = 0;
	int op = -1;

	if (sz < sizeof(dhcp_msg_t)) return;

	if (memcmp(msg->chaddr, mac, 6)) return;

#if TRACE_DHCP
	printf("dhcp op=%d len=%d from p=%d ip=", msg->opcode, sz, srcport);
	printip("", srcip);
#endif

	if (configured) {
		printf("already configured\n");
		return;
	}
#if TRACE_DHCP
	printip("ciaddr", msg->ciaddr);
	printip("yiaddr", msg->yiaddr);
	printip("siaddr", msg->siaddr);
	printip("giaddr", msg->giaddr);
	printf("chaddr %02x:%02x:%02x:%02x:%02x:%02x\n",
		msg->chaddr[0], msg->chaddr[1], msg->chaddr[2],
		msg->chaddr[3], msg->chaddr[4], msg->chaddr[5]);
#endif
	sz -= sizeof(dhcp_msg_t);
	opt = msg->options;
	while (sz >= 2) {
		sz -= 2;
		if (opt[1] > sz) {
			break;
		}
#if TRACE_DHCP
		printf("#%d (%d), ", opt[0], opt[1]);
#endif
		switch (opt[0]) {
		case OPT_MSG_TYPE:
			if (opt[1] == 1) op = opt[2];
			break;	
		case OPT_NET_MASK:
			if (opt[1] == 4) memcpy(&netmask, opt + 2, 4);
			break;
		case OPT_ROUTERS:
			if (opt[1] >= 4) memcpy(&gateway, opt + 3, 4);
			break;
		case OPT_DNS:
			if (opt[1] >= 4) memcpy(&dns, opt + 3, 4);
			break;
		case OPT_SERVER_ID:
			if (opt[1] == 4) memcpy(&server, opt + 3, 4);
			break;
		case OPT_DONE:
			goto done;
		}
		opt += opt[1] + 2;
		sz -= opt[1];
	}
done:
#if TRACE_DHCP
	printf("\n");
	if (server) printip("server", server);
	if (netmask) printip("netmask", netmask);
	if (gateway) printip("gateway", gateway);
	if (dns) printip("dns", dns);
#endif
	if (cfgstate == 0) {
		if (op == OP_DHCPOFFER) {
			printip("dhcp: offer:", msg->yiaddr);
			if (server) {
				dhcp_request(0xaabbccdd, server, msg->yiaddr);
				cfgstate = 1;
			}
		}
	} else if (cfgstate == 1) {
		if (op == OP_DHCPACK) {
			printip("dhcp: ack:", msg->yiaddr);
			minip_set_ipaddr(msg->yiaddr);
			configured = 1;
		}
	}
}
Пример #13
0
int main(int argc, char *argv[])
{
    if (argc < 4) {
        printf("usage %s ip port filename(of file to send)\n", argv[0]);
        exit(0);
    }
    new_keys();
    printf("OUR ID: ");
    uint32_t i;
    for(i = 0; i < 32; i++) {
        if(self_public_key[i] < 16)
            printf("0");
        printf("%hhX",self_public_key[i]);
    }
    printf("\n");
    
    memcpy(self_client_id, self_public_key, 32);
    
    char temp_id[128];
    printf("Enter the client_id of the friend to connect to (32 bytes HEX format):\n");
    scanf("%s", temp_id);
    
    uint8_t friend_id[32];
    memcpy(friend_id, hex_string_to_bin(temp_id), 32);
    
    /* memcpy(self_client_id, "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", 32); */
    

    DHT_addfriend(friend_id);
    IP_Port friend_ip;
    int connection = -1;
    int inconnection = -1;
    
    uint8_t acceptedfriend_public_key[crypto_box_PUBLICKEYBYTES];
    int friendrequest = -1;
    uint8_t request_data[512];
    
    /* initialize networking
     * bind to ip 0.0.0.0:PORT */
    IP ip;
    ip.i = 0;
    init_networking(ip, PORT);
    initNetCrypto();
    
    perror("Initialization");
    IP_Port bootstrap_ip_port;
    bootstrap_ip_port.port = htons(atoi(argv[2]));
    bootstrap_ip_port.ip.i = inet_addr(argv[1]);
    DHT_bootstrap(bootstrap_ip_port);
    
    IP_Port ip_port;
    uint8_t data[MAX_UDP_PACKET_SIZE];
    uint32_t length;
    
    uint8_t buffer1[128];
    int read1 = 0;
    uint8_t buffer2[128];
    int read2 = 0;
    FILE *file1 = fopen(argv[3], "rb");
    if ( file1==NULL ){printf("Error opening file.\n");return 1;}
    FILE *file2 = fopen("received.txt", "wb");
    if ( file2==NULL ){return 1;}
    read1 = fread(buffer1, 1, 128, file1);
    
    while(1) {
        while(receivepacket(&ip_port, data, &length) != -1) {
            if(rand() % 3 != 1) { /* simulate packet loss */
                if(DHT_handlepacket(data, length, ip_port) && LosslessUDP_handlepacket(data, length, ip_port)) {
                    /* if packet is not recognized */
                    printf("Received unhandled packet with length: %u\n", length);
                } else {
                    printf("Received handled packet with length: %u\n", length);
                }
            }
        }
        friend_ip = DHT_getfriendip(friend_id);
        if(friend_ip.ip.i != 0) {
            if(connection == -1 && friendrequest == -1) {
                printf("Sending friend request to peer:");
                printip(friend_ip);
                friendrequest = send_friendrequest(friend_id, friend_ip,(uint8_t *) "Hello World", 12);
                /* connection = crypto_connect((uint8_t *)friend_id, friend_ip); */
                /* connection = new_connection(friend_ip); */
            }
            if(check_friendrequest(friendrequest) == 1) {
                printf("Started connecting to friend:");
                connection = crypto_connect(friend_id, friend_ip);
            }
        }
        if(inconnection == -1) {
            uint8_t secret_nonce[crypto_box_NONCEBYTES];
            uint8_t public_key[crypto_box_PUBLICKEYBYTES];
            uint8_t session_key[crypto_box_PUBLICKEYBYTES];
            inconnection = crypto_inbound(public_key, secret_nonce, session_key);
            inconnection = accept_crypto_inbound(inconnection, acceptedfriend_public_key, secret_nonce, session_key);
            /* inconnection = incoming_connection(); */
            if(inconnection != -1) {
                printf("Someone connected to us:\n");
               /* printip(connection_ip(inconnection)); */
            }
        }
        if(handle_friendrequest(acceptedfriend_public_key, request_data) > 1) {
            printf("RECIEVED FRIEND REQUEST: %s\n", request_data);
        }

        /* if someone connected to us write what he sends to a file
         * also send him our file. */
        if(inconnection != -1) {
            if(write_cryptpacket(inconnection, buffer1, read1)) {
                printf("Wrote data1.\n");
                read1 = fread(buffer1, 1, 128, file1);
            }
            read2 = read_cryptpacket(inconnection, buffer2);
            if(read2 != 0) {
                printf("Received data1.\n");
                if(!fwrite(buffer2, read2, 1, file2)) {
                        printf("file write error1\n");
                }
                if(read2 < 128) {
                    printf("Closed file1 %u\n", read2);
                    fclose(file2);
                }
            }
            /* if buffer is empty and the connection timed out. */
            else if(is_cryptoconnected(inconnection) == 4) {
                crypto_kill(inconnection);
            }
        }
        /* if we are connected to a friend send him data from the file.
         * also put what he sends us in a file. */
        if(is_cryptoconnected(connection) >= 3)  {
            if(write_cryptpacket(0, buffer1, read1)) {
                printf("Wrote data2.\n");
                read1 = fread(buffer1, 1, 128, file1);
            }
            read2 = read_cryptpacket(0, buffer2);
            if(read2 != 0) {
                printf("Received data2.\n");
                if(!fwrite(buffer2, read2, 1, file2)) {
                        printf("file write error2\n");
                }
                if(read2 < 128) {
                    printf("Closed file2 %u\n", read2);
                    fclose(file2);
                }
            }
            /* if buffer is empty and the connection timed out. */
            else if(is_cryptoconnected(connection) == 4) {
                crypto_kill(connection);
            }
        }
        doDHT();
        doLossless_UDP();
        doNetCrypto();
        /*print_clientlist();
         *print_friendlist();
         *c_sleep(300); */
        c_sleep(1);
    }
    
    shutdown_networking();
    return 0;   
}
int main(int argc, char *argv[])
{
    if (argc < 4) {
        printf("usage: %s ip port filename\n", argv[0]);
        exit(0);
    }
    
    uint8_t buffer[512];
    int read;
    
    FILE *file = fopen(argv[3], "rb");
    if (file == NULL)
      return 1;
    
    
    /* initialize networking */
    /* bind to ip 0.0.0.0:PORT */
    IP ip;
    ip.i = 0;
    init_networking(ip, PORT);
    perror("Initialization");
    IP_Port serverip;
    serverip.ip.i = inet_addr(argv[1]);
    serverip.port = htons(atoi(argv[2]));
    printip(serverip);
    int connection = new_connection(serverip);
    uint64_t timer = current_time();
    while (1) {
       /* printconnection(connection); */
        Lossless_UDP();
        if (is_connected(connection) == 3) {
            printf("Connecting took: %llu us\n", (unsigned long long)(current_time() - timer));
            break;
        }
        if (is_connected(connection) == 0) {
            printf("Connection timeout after: %llu us\n", (unsigned long long)(current_time() - timer));
            return 1;
        }
        c_sleep(1);
    }
    timer = current_time();
    
    
    /*read first part of file */
    read = fread(buffer, 1, 512, file);
    
    while (1) {
        /* printconnection(connection); */
        Lossless_UDP();
        if (is_connected(connection) == 3) {
            
            if (write_packet(connection, buffer, read)) {
               /* printf("Wrote data.\n"); */
                read = fread(buffer, 1, 512, file);

            }
            /* printf("%u\n", sendqueue(connection)); */
            if (sendqueue(connection) == 0) {
                if (read == 0) {
                    printf("Sent file successfully in: %llu us\n", (unsigned long long)(current_time() - timer));
                    break;
                }
            }
        }
        else {
            printf("Connecting Lost after: %llu us\n", (unsigned long long)(current_time() - timer));
            return 0;
        }
        /* c_sleep(1); */
    }
        
    return 0;
}
Пример #15
0
int main(int argc, char *argv[])
{
    //memcpy(self_client_id, "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", 32);
    
    if (argc < 6) {
        printf("usage %s ip port client_id(of friend to find ip_port of) filename(of file to send) client_id(ours)\n", argv[0]);
        exit(0);
    }
    addfriend(argv[3]);
    IP_Port friend_ip;
    int connection = -1;
    int inconnection = -1;
    
    //initialize networking
    //bind to ip 0.0.0.0:PORT
    IP ip;
    ip.i = 0;
    init_networking(ip, PORT);
    
    memcpy(self_client_id, argv[5], 32);
    

    perror("Initialization");
    IP_Port bootstrap_ip_port;
    bootstrap_ip_port.port = htons(atoi(argv[2]));
    bootstrap_ip_port.ip.i = inet_addr(argv[1]);
    bootstrap(bootstrap_ip_port);
    
    IP_Port ip_port;
    char data[MAX_UDP_PACKET_SIZE];
    uint32_t length;
    
    char buffer1[128];
    int read1 = 0;
    char buffer2[128];
    int read2 = 0;
    FILE *file1 = fopen(argv[4], "rb");
    if ( file1==NULL ){printf("Error opening file.\n");return 1;}
    FILE *file2 = fopen("received.txt", "wb");
    if ( file2==NULL ){return 1;}
    read1 = fread(buffer1, 1, 128, file1);
    
    while(1)
    {

        while(recievepacket(&ip_port, data, &length) != -1)
        {
            if(rand() % 3 != 1)//simulate packet loss
            {
                if(DHT_handlepacket(data, length, ip_port) && LosslessUDP_handlepacket(data, length, ip_port))
                {
                    //if packet is not recognized
                    printf("Received unhandled packet with length: %u\n", length);
                }
                else
                {
                    printf("Received handled packet with length: %u\n", length);
                }
            }
        }
        friend_ip = getfriendip(argv[3]);
        if(friend_ip.ip.i != 0)
        {
            if(connection == -1)
            {
                printf("Started connecting to friend:");
                printip(friend_ip);
                connection = new_connection(friend_ip);
            }
        }
        if(inconnection == -1)
        {
            inconnection = incoming_connection();
            if(inconnection != -1)
            {
                printf("Someone connected to us:");
                printip(connection_ip(inconnection));
            }
        }
        //if someone connected to us write what he sends to a file
        //also send him our file.
        if(inconnection != -1)
        {
            if(write_packet(inconnection, buffer1, read1))
            {
                printf("Wrote data.\n");
                read1 = fread(buffer1, 1, 128, file1);
            }
            read2 = read_packet(inconnection, buffer2);
            if(read2 != 0)
            {
                printf("Received data.\n");
                if(!fwrite(buffer2, read2, 1, file2))
                {
                        printf("file write error\n");
                }
                if(read2 < 128)
                {
                    fclose(file2);
                }
            } 
        }
        //if we are connected to a friend send him data from the file.
        //also put what he sends us in a file.
        if(is_connected(connection) == 3)
        {
            if(write_packet(0, buffer1, read1))
            {
                printf("Wrote data.\n");
                read1 = fread(buffer1, 1, 128, file1);
            }
            read2 = read_packet(0, buffer2);
            if(read2 != 0)
            {
                printf("Received data.\n");
                if(!fwrite(buffer2, read2, 1, file2))
                {
                        printf("file write error\n");
                }
                if(read2 < 128)
                {
                    fclose(file2);
                }
            } 
        }
        doDHT();
        doLossless_UDP();
        //print_clientlist();
        //print_friendlist();
        //c_sleep(300);
        c_sleep(1);
    }
    
    shutdown_networking();
    return 0;   
}
int main(int argc, char *argv[])
{
    /* let user override default by cmdline */
    uint8_t ipv6enabled = TOX_ENABLE_IPV6_DEFAULT; /* x */
    int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled);

    if (argvoffset < 0)
        exit(1);

    if (argc < argvoffset + 4) {
        printf("Usage: %s [--ipv4|--ipv6] ip port filename\n", argv[0]);
        exit(0);
    }

    uint8_t buffer[512];
    int read;

    FILE *file = fopen(argv[argvoffset + 3], "rb");

    if (file == NULL) {
        printf("Failed to open file \"%s\".\n", argv[argvoffset + 3]);
        return 1;
    }


    /* initialize networking */
    /* bind to ip 0.0.0.0:PORT */
    IP ip;
    ip_init(&ip, ipv6enabled);

    Lossless_UDP *ludp = new_lossless_udp(new_networking(ip, PORT));
    perror("Initialization");

    IP_Port serverip;
    ip_init(&serverip.ip, ipv6enabled);

    if (!addr_resolve(argv[argvoffset + 1], &serverip.ip, NULL)) {
        printf("Failed to convert \"%s\" into an IP address.\n", argv[argvoffset + 1]);
        return 1;
    }

    serverip.port = htons(atoi(argv[argvoffset + 2]));
    printip(serverip);

    int connection = new_connection(ludp, serverip);
    uint64_t timer = current_time();

    while (1) {
        /* printconnection(connection); */
        networking_poll(ludp->net);
        do_lossless_udp(ludp);

        if (is_connected(ludp, connection) == 3) {
            printf("Connecting took: %llu us\n", (unsigned long long)(current_time() - timer));
            break;
        }

        if (is_connected(ludp, connection) == 0) {
            printf("Connection timeout after: %llu us\n", (unsigned long long)(current_time() - timer));
            return 1;
        }

        c_sleep(1);
    }

    timer = current_time();


    /*read first part of file */
    read = fread(buffer, 1, 512, file);

    while (1) {
        /* printconnection(connection); */
        networking_poll(ludp->net);
        do_lossless_udp(ludp);

        if (is_connected(ludp, connection) == 3) {

            if (write_packet(ludp, connection, buffer, read)) {
                /* printf("Wrote data.\n"); */
                read = fread(buffer, 1, 512, file);

            }

            /* printf("%u\n", sendqueue(connection)); */
            if (sendqueue(ludp, connection) == 0) {
                if (read == 0) {
                    printf("Sent file successfully in: %llu us\n", (unsigned long long)(current_time() - timer));
                    break;
                }
            }
        } else {
            printf("Connecting Lost after: %llu us\n", (unsigned long long)(current_time() - timer));
            return 0;
        }

        /* c_sleep(1); */
    }

    return 0;
}
Пример #17
0
/* ------------------------------------------------------------------------- *\
 * FUNCTION main (argc, argv)                                                *
 * --------------------------                                                *
 * Goes over configured host-groups and fishes for hosts in /var/state/n2    *
 * for some summary information. Prints out the information either in a CSV  *
 * format (default), in XML (with -x) or as tabulated human-readable data    *
 * (with -f). An optional groupname argument will limit the scope of the     *
 * search to a single host-group.                                            *
\* ------------------------------------------------------------------------- */
int main (int argc, char *argv[])
{
	DIR *dir;
	struct dirent *de;
	FILE *fsumm;
	char *name;
	unsigned int addr;
	hostgroup *grp;
	int first=1;
	netload_rec *rec;
	hstat *info;
	unsigned long long netin, netout;
	int numwarn, numalert, numcrit;
	int rtt, count;
	int asxml;
	int ascsv;
	int asjson=0;
	int op;
	int firstmember=0;
	int firstgroup=1;
	char outline[256];
	char addrbuf[32];
	const char *groupname = NULL;
	ipnode *firstnode = NULL;
	ipnode *currentnode = NULL;
	ipnode *newnode = NULL;
	int isacked;
	
	asxml = 0;
	ascsv = 1;
	
	while ((op = getopt (argc, argv, "xfjg:")) > 0)
	{
		switch (op)
		{
			case 'x': asjson=0; asxml=1; ascsv=0; break;
			case 'f': asjson=0; ascsv=0; asxml=0; break;
			case 'j': asxml=0; ascsv=0; asjson=1; break;
			case 'g': groupname=optarg; break;
		}
	}
	
	conf_init ();
	acl_init ();
	load_config ("/etc/n2/n2rxd.conf");
	
	if (asxml)
	{
		printf ("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		printf ("<nl.madscience.svc.n2.groups>\n");
	}
	else if ((!ascsv)&&(!asjson))
	{
		printf ("Host              Status   Load      CPU    RTT   "
				"Loss  Net In/    Out     i/o\n");
				//                    Kb/s   "
	}
	else if (asjson)
	{
		printf ("{");
	}
	
	fsumm = fopen ("/var/state/n2/current/summary", "r");
	if (! fsumm)
	{
		fprintf (stderr, "%% Error loading summary file\n");
		return 1;
	}

	newnode = (ipnode *) malloc (sizeof (ipnode));

	while (fread (newnode, sizeof (hstat), 1, fsumm) > 0)
	{
		newnode->next = NULL;
		if (currentnode)
		{
			currentnode->next = newnode;
			currentnode = newnode;
		}
		else
		{
			currentnode = firstnode = newnode;
		}

		newnode = (ipnode *) malloc (sizeof (ipnode));
	}
	fclose (fsumm);
	free (newnode);

	grp = GROUPS.groups;
	
	while (grp)
	{
		if ((! groupname) || (! strcmp (groupname, grp->name)))
		{
			netin = netout = 0;
			numwarn = numalert = numcrit = rtt = count = 0;
			if (ascsv)
			{
				if (ascsv) printf ("%s:", grp->name);
			}
			else if (asjson)
			{
				if (firstgroup) firstgroup=0;
				else printf (",");
				printf ("\"%s\":{\"description\":\"%s\",\"members\":{",
						grp->name, grp->description);
				firstmember=1;
			}
			else if (asxml)
			{
				printf ("  <group name=\"%s\" description=\"%s\">\n",
											grp->name, grp->description);
				printf ("    <members>\n");
			}
			first = 1;
			currentnode = firstnode;
			while (currentnode)
			{
				addr = currentnode->st.addr;
				printip (addr, addrbuf);
				if (grp == hostgroup_acl_resolve (addr))
				{
					isacked = 0;
					if (asxml)
					{
						printf ("      <member ip=\"%s\"", addrbuf);
					}
					else if (asjson)
					{
						if (firstmember) firstmember=0;
						else printf (",");
						printf ("\"%s\":{", addrbuf);
					}
					else if (ascsv)
					{
						printf ("%s%s", first ? "" : " ", addrbuf);
					}
					first = 0;
					info = &(currentnode->st);
					if (info)
					{
						if (CHKOFLAG(info->oflags,OFLAG_ACKED))
						{
							// hide the flag, but keep it tracked.
							info->oflags ^= 1<<OFLAG_ACKED;
							isacked = 1;
						}
						else isacked = 0;
						if (asxml || asjson)
						{
							// FIXME@ koert: potential stack overflow here if error flags are added
							// or get longer names
							char flags[512];
							flags[0] = '\0';

							if( CHKSTATUSFLAG(info->status,FLAG_RTT) ) strcat(flags,", rtt");
							if( CHKSTATUSFLAG(info->status,FLAG_LOSS) ) strcat(flags,", loss");
							if( CHKSTATUSFLAG(info->status,FLAG_LOAD) ) strcat(flags,", load");
							if( CHKOFLAG(info->oflags,OFLAG_RAM) ) strcat(flags,", ram");
							if( CHKOFLAG(info->oflags,OFLAG_SWAP) ) strcat(flags,", swap");
							if( CHKOFLAG(info->oflags,OFLAG_NETIN) ) strcat(flags,", netin");
							if( CHKOFLAG(info->oflags,OFLAG_NETOUT) ) strcat(flags,", netout");
							if( CHKOFLAG(info->oflags,OFLAG_SVCDOWN) ) strcat(flags,", svcdown");
							if( CHKOFLAG(info->oflags,OFLAG_DISKIO) ) strcat(flags,", diskio");
							if( CHKOFLAG(info->oflags,OFLAG_DISKSPACE) ) strcat(flags,", diskspace");
							if( CHKOFLAG(info->oflags,OFLAG_DECODINGERR) ) strcat(flags,", decodingerr");
							if( CHKOFLAG(info->oflags,OFLAG_IOWAIT) ) strcat(flags,", iowait");
							// if( CHKSTATUSFLAG(info->status,FLAG_OTHER) ) strcat(flags,", other");

							if (asxml)
							{
								printf (" netin=\"%u\" netout=\"%u\" "
										"rtt=\"%.1f\" cpu=\"%.2f\" "
										"loadavg=\"%.2f\" status=\"%s\" "
										"diskio=\"%u\" flags=\"%s\" ",
										info->netin, info->netout,
										((double) info->ping10) / 10.0,
										((double) info->cpu) / 2.56,
										((double) info->load1) / 100.0,
										isacked ? "ACKED" : STR_STATUS[info->status & 15],
										info->diskio,
										*flags ? flags+2 : flags );
							}
							else
							{
								printf ("\"netin\":%u,", info->netin);
								printf ("\"netout\":%u,", info->netout);
								printf ("\"rtt\":%.1f,", ((double)info->ping10)/10.0);
								printf ("\"cpu\":%.2f,",((double) info->cpu)/2.56);
								printf ("\"loadavg\":%.2f,",((double)info->load1)/100.0);
								printf ("\"status\":\"%s\",",isacked?"ACKED":STR_STATUS[info->status&15]);
								printf ("\"diskio\":%u,",info->diskio);
								printf ("\"flags\":\"%s\"", *flags?flags+2:flags);
							}
						}
						else if (! ascsv)
						{
							sprintf (outline, "%-17s                  ",
									 addrbuf);
							sprintf (outline+18, "%s        ",
									 isacked ? "ACKED" : STR_STATUS[info->status&15]);
							if (info->status == ST_DEAD)
							{
								sprintf (outline+24, "   -.--   -.-- %% "
										 "%6.1f  %3i %%       -/      -"
										 "       -",
										 ((double)info->ping10) / 10.0,
										 info->loss/100
										);
							}
							else sprintf (outline+24, " %6.2f %6.2f %% "
									 "%6.1f  %3i %% %7i/%7i %7i",
									 ((double) info->load1) / 100.0,
									 ((double) info->cpu) / 2.56,
									 ((double) info->ping10) / 10.0,
									 info->loss/100,
									 info->netin, info->netout,
									 info->diskio);
									 
							printf ("%s\n", outline); 
						}
						netin += info->netin;
						netout += info->netout;
						rtt += info->ping10;
						if (ascsv)
						{
							switch (RDSTATUS(info->status))
							{
								case ST_WARNING:
									if (isacked) break;
									printf ("=WARNING");
									++numwarn; break;

								case ST_STALE:
								case ST_ALERT:
								case ST_DEAD:
									if (isacked) break;
									printf ("=ALERT");
									++numalert; break;

								case ST_CRITICAL:
									if (isacked) break;
									printf ("=CRITICAL");
									++numcrit; break;
								
								default:
									printf ("=OK");
									break;
							}
						}
						pool_free (info);
					}
					else
					{
						free (rec);
					}
					if (asxml) printf ("/>\n");
					if (asjson) printf ("}");
					++count;
				}
				currentnode = currentnode->next;
			}
			if (asjson)
			{
				printf ("},\"summary\":{");
				printf ("\"netin\":%u,", netin);
				printf ("\"netout\":%u,",netout);
				printf ("\"rtt\":%.1f,",((double)rtt/(10.0*((double)count))));
				printf ("\"counts.warning\":%i,", numwarn);
				printf ("\"counts.alert\":%i,", numalert);
				printf ("\"counts.critical\":%i", numcrit);
				printf ("}}");
			}
			else if (! asxml)
			{
				if (! count) count=1;
				if (ascsv)
				{
					printf (":%i:%llu:%llu:%.1f:%i:%i:%i\n",
							count, netin, netout,
							((double) rtt / (10.0 * ((double) count))),
							numwarn, numalert, numcrit);
				}
			}
			else if (! ascsv)
			{
				printf ("    </members>\n");
				printf ("    <summary>\n");
				printf ("      <netin>%u</netin>\n", netin);
				printf ("      <netout>%u</netout>\n", netout);
				printf ("      <rtt>%.1f</rtt>\n",
						((double) rtt / (10.0 * ((double) count))));
				printf ("      <counts.warning>%i</counts.warning>\n", numwarn);
				printf ("      <counts.alert>%i</counts.alert>\n", numalert);
				printf ("      <counts.critical>%i</counts.critical>\n",
						numcrit);
				printf ("    </summary>\n");
				printf ("  </group>\n");
			}
		}
		grp = grp->next;
	}
	if (asxml)
	{
		printf ("</nl.madscience.svc.n2.groups>\n");
	}
	if (asjson) printf ("}\n");
	exit(0);
}