static int set_h225_addr(struct sk_buff **pskb,
			 unsigned char **data, int dataoff,
			 TransportAddress * addr,
			 __be32 ip, u_int16_t port)
{
	return set_addr(pskb, data, dataoff, addr->ipAddress.ip, ip, port);
}
Esempio n. 2
0
void SocketAddress::set_ip_bytes(const void *bytes, nsapi_version_t version)
{
    nsapi_addr_t addr;
    addr.version = version;
    memcpy(addr.bytes, bytes, NSAPI_IP_BYTES);
    set_addr(addr);
}
Esempio n. 3
0
/**
 * \brief      Write to the PCI configuration data port.
 * \param addr Address of PCI configuration register.
 * \param data Value to write.
 */
void
pci_config_write(pci_config_addr_t addr, uint32_t data)
{
  set_addr(addr);

  outl(PCI_CONFIG_DATA_PORT, data);
}
Esempio n. 4
0
/**
 * \brief      Read from the specified PCI configuration register.
 * \param addr Address of PCI configuration register.
 * \return     Value read from PCI configuration register.
 */
uint32_t
pci_config_read(pci_config_addr_t addr)
{
  set_addr(addr);

  return inl(PCI_CONFIG_DATA_PORT);
}
Esempio n. 5
0
void sr_handleARPpacket(struct sr_instance *sr, uint8_t* packet, unsigned int len, struct sr_if * iface) {
    assert(packet);
    sr_ethernet_hdr_t* ethHeader = (sr_ethernet_hdr_t*) packet;
    sr_arp_hdr_t * arpHeader = (sr_arp_hdr_t *) (packet+14);

    enum sr_arp_opcode request = arp_op_request;
    enum sr_arp_opcode reply = arp_op_reply;

    struct sr_if *interface = sr_get_interface_from_ip(sr, htonl(arpHeader->ar_tip));

    /* handle an arp request.*/
    if (ntohs(arpHeader->ar_op) == request) {
        /* found an ip->mac mapping. send a reply to the requester's MAC addr */
        if (interface){
          arpHeader->ar_op = ntohs(reply);
          uint32_t temp = arpHeader->ar_sip;
          arpHeader->ar_sip = arpHeader->ar_tip;
          arpHeader->ar_tip = temp;
          memcpy(arpHeader->ar_tha, arpHeader->ar_sha,6);
          memcpy(arpHeader->ar_sha, iface->addr,6);

          /*swapping outgoing and incoming addr*/
          set_addr(ethHeader, iface->addr, ethHeader->ether_shost);
          sr_send_packet(sr,(uint8_t*)ethHeader,len,iface->name);
        }
    }
    /* handle an arp reply */
    else {
      struct sr_packet *req_packet = NULL;
      struct sr_arpreq *req = NULL;
      pthread_mutex_lock(&(sr->cache.lock));   
      
      for (req = sr->cache.requests; req != NULL; req = req->next){
        if(req->ip == arpHeader->ar_sip){
          /* find the interface the packets should be sent out of */
          struct sr_rt * rt = (struct sr_rt *)sr_find_routing_entry_int(sr, req->ip);
          if (rt) {
            iface = sr_get_interface(sr, rt->interface);
            /* send all packets waiting on the request that was replied to */
            for (req_packet = req->packets; req_packet != NULL; req_packet = req_packet->next) {
              sr_ethernet_hdr_t * outEther = (sr_ethernet_hdr_t *)req_packet->buf;
              memcpy(outEther->ether_shost, iface->addr,6);
              memcpy(outEther->ether_dhost, ethHeader->ether_shost,6);

              sr_ip_hdr_t * outIP = (sr_ip_hdr_t *)(req_packet->buf+14);
              outIP->ip_ttl = outIP->ip_ttl-1;
              outIP->ip_sum = 0;
              outIP->ip_sum = cksum((uint8_t *)outIP,20);
              
              sr_send_packet(sr,req_packet->buf,req_packet->len,iface->name);
            }
            sr_arpreq_destroy(&(sr->cache), req);
          }
          break;
        }
      }
      pthread_mutex_unlock(&(sr->cache.lock));
      sr_arpcache_insert(&(sr->cache),arpHeader->ar_sha,arpHeader->ar_sip);
    }
}
static int set_h245_addr(struct sk_buff **pskb,
			 unsigned char **data, int dataoff,
			 H245_TransportAddress * addr,
			 __be32 ip, u_int16_t port)
{
	return set_addr(pskb, data, dataoff,
			addr->unicastAddress.iPAddress.network, ip, port);
}
Esempio n. 7
0
static int set_h225_addr(struct sk_buff *skb,
			 unsigned char **data, int dataoff,
			 TransportAddress *taddr,
			 union nf_inet_addr *addr, __be16 port)
{
	return set_addr(skb, data, dataoff, taddr->ipAddress.ip,
			addr->ip, port);
}
Esempio n. 8
0
	void Vflyspi_adc::setup_controller(uint32_t startaddr, uint32_t endaddr, bool single_mode, bool trigger_enabled, bool trigger_channel) {
//write configuration
		sp6data *buf=writeBlock(0,18);
        set_addr(buf, startaddr, endaddr);
// set enable and single shot bit, set start and stop bit to zero
		writeBuf(buf, startstop,static_cast<sp6data>((trigger_channel<<4) | (trigger_enabled<<3) | (single_mode<<2) | 0x00 ));
		
		doWB();
	}
Esempio n. 9
0
int16_t MeUSBHost::initHIDDevice()
{
  int16_t irq, len, address;
  if(usbtype==USB1_0) set_freq(); //work on a lower freq, necessary for ch375
  irq = get_desr(1);
#ifdef CH375_DBG
  Serial.printf("get des irq:%x\n",irq);
#endif
  if(irq==USB_INT_SUCCESS){
      len = rd_usb_data( RECV_BUFFER );
#ifdef CH375_DBG
      Serial.printf("descr1 len %d type %x\r\n",len,p_dev_descr->bDescriptorType);
#endif
      irq = set_addr(2);
      if(irq==USB_INT_SUCCESS){
        irq = get_desr(2); // max buf 64byte, todo:config descr overflow
        if(irq==USB_INT_SUCCESS){
          len = rd_usb_data( RECV_BUFFER );
#ifdef CH375_DBG
          Serial.printf("descr2 len %d class %x subclass %x\r\n",len,p_cfg_descr->itf_descr.bInterfaceClass, p_cfg_descr->itf_descr.bInterfaceSubClass); // interface class should be 0x03 for HID
          Serial.printf("num of ep %d\r\n",p_cfg_descr->itf_descr.bNumEndpoints);
          Serial.printf("ep0 %x %x\r\n",p_cfg_descr->endp_descr[0].bLength, p_cfg_descr->endp_descr[0].bDescriptorType);
#endif
          if(p_cfg_descr->endp_descr[0].bDescriptorType==0x21){ // skip hid des
            tmpEp = (PUSB_ENDP_DESCR)((int8_t*)(&(p_cfg_descr->endp_descr[0]))+p_cfg_descr->endp_descr[0].bLength); // get the real ep position
          }
#ifdef CH375_DBG
          Serial.printf("endpoint %x %x\r\n",tmpEp->bEndpointAddress,tmpEp->bDescriptorType);
#endif
          endp_out_addr=endp_in_addr=0;
          address =tmpEp->bEndpointAddress;  /* Address of First EndPoint */
          // actually we only care about the input end points
          if( address&0x80 ){
            endp_in_addr = address&0x0f;  /* Address of IN EndPoint */
          }else{  /* OUT EndPoint */
            endp_out_addr = address&0x0f;
            endp_out_size = p_cfg_descr->endp_descr[0].wMaxPacketSize;
			/* Length of Package for Received Data EndPoint */
            if( endp_out_size == 0 || endp_out_size > 64 )
              endp_out_size = 64;
          }
          // todo: some joystick with more than 2 node
          // just assume every thing is fine, bring the device up
          irq = set_config(p_cfg_descr->cfg_descr.bConfigurationvalue);
          if(irq==USB_INT_SUCCESS){
            CH375_WR( CMD_SET_RETRY );  // set the retry times
            CH375_WR( 0x25 );
            CH375_WR( 0x85 );
            device_ready = true;
            return 1;
          }
        }

      }
  }
  return 0;
}
Esempio n. 10
0
static int set_h245_addr(struct sk_buff *skb,
			 unsigned char **data, int dataoff,
			 H245_TransportAddress *taddr,
			 union nf_inet_addr *addr, __be16 port)
{
	return set_addr(skb, data, dataoff,
			taddr->unicastAddress.iPAddress.network,
			addr->ip, port);
}
Esempio n. 11
0
void SocketAddress::set_ip_bytes(const void *bytes, nsapi_version_t version)
{
    nsapi_addr_t addr;

    addr = nsapi_addr_t();
    addr.version = version;
    if (version == NSAPI_IPv6) {
        memcpy(addr.bytes, bytes, NSAPI_IPv6_BYTES);
    } else if (version == NSAPI_IPv4) {
        memcpy(addr.bytes, bytes, NSAPI_IPv4_BYTES);
    }
    set_addr(addr);
}
 bool network::set(char * network)
 {
     char * ip, * mask;
     ip=strtok(network, "/");
     if(ip==NULL)
         return false;
     mask=strtok(NULL, "/");
     if (mask==NULL)
         return false;
     _mask=atoi(mask);
     if (!set_addr(ip))
         return false;
     return true;
 }
Esempio n. 13
0
void TalkConnection::open_sockets()
{
    struct sockaddr_in ctl_addr;
    struct sockaddr_in my_addr;

    /* open the ctl socket */
    ctl_sockt = open_socket(&ctl_addr, SOCK_DGRAM);
    /* store its address */
    set_ctl_addr((const struct talk_addr *)&ctl_addr);

    /* open the text socket */
    sockt = open_socket(&my_addr, SOCK_STREAM);
    /* store its address */
    set_addr((const struct talk_addr *)&my_addr);
}
Esempio n. 14
0
unsigned char init_print() {  /* 初始化USB打印机,完成打印机枚举 */
#define	p_dev_descr		((PUSB_DEV_DESCR)buffer)
#define	p_cfg_descr		((PUSB_CFG_DESCR_LONG)buffer)
	unsigned char status, len, c;
	status=get_descr(1);  /* 获取设备描述符 */
	if ( status==USB_INT_SUCCESS ) {
		len=rd_usb_data( buffer );  /* 将获取的描述符数据从CH375中读出到单片机的RAM缓冲区中,返回描述符长度 */
		if ( len<18 || p_dev_descr->bDescriptorType!=1 ) return( UNKNOWN_USB_DEVICE );  /* 意外错误:描述符长度错误或者类型错误 */
		if ( p_dev_descr->bDeviceClass!=0 ) return( UNKNOWN_USB_DEVICE );  /* 连接的USB设备不是USB打印机,或者不符合USB规范 */
		status=set_addr(3);  /* 设置打印机的USB地址 */
		if ( status==USB_INT_SUCCESS ) {
			status=get_descr(2);  /* 获取配置描述符 */
			if ( status==USB_INT_SUCCESS ) {  /* 操作成功则读出描述符并分析 */
				len=rd_usb_data( buffer );  /* 将获取的描述符数据从CH375中读出到单片机的RAM缓冲区中,返回描述符长度 */
				if ( p_cfg_descr->itf_descr.bInterfaceClass!=7 || p_cfg_descr->itf_descr.bInterfaceSubClass!=1 ) return( UNKNOWN_USB_PRINT );  /* 不是USB打印机或者不符合USB规范 */
				endp_out_addr=endp_in_addr=0;
				c=p_cfg_descr->endp_descr[0].bEndpointAddress;  /* 第一个端点的地址 */
				if ( c&0x80 ) endp_in_addr=c&0x0f;  /* IN端点的地址 */
				else {  /* OUT端点 */
					endp_out_addr=c&0x0f;
					endp_out_size=p_cfg_descr->endp_descr[0].wMaxPacketSize;  /* 数据接收端点的最大包长度 */
				}
				if ( p_cfg_descr->itf_descr.bNumEndpoints>=2 ) {  /* 接口有两个以上的端点 */
					if ( p_cfg_descr->endp_descr[1].bDescriptorType==5 ) {  /* 端点描述符 */
						c=p_cfg_descr->endp_descr[1].bEndpointAddress;  /* 第二个端点的地址 */
						if ( c&0x80 ) endp_in_addr=c&0x0f;  /* IN端点 */
						else {  /* OUT端点 */
							endp_out_addr=c&0x0f;
							endp_out_size=p_cfg_descr->endp_descr[1].wMaxPacketSize;
						}
					}
				}
				if ( p_cfg_descr->itf_descr.bInterfaceProtocol<=1 ) endp_in_addr=0;  /* 单向接口不需要IN端点 */
				if ( endp_out_addr==0 ) return( UNKNOWN_USB_PRINT );  /* 不是USB打印机或者不符合USB规范 */
				status=set_config( p_cfg_descr->cfg_descr.bConfigurationValue );  /* 加载USB配置值 */
				if ( status==USB_INT_SUCCESS ) {
					CH375_WR_CMD_PORT( CMD_SET_RETRY );  /* 设置USB事务操作的重试次数 */
					CH375_WR_DAT_PORT( 0x25 );
					CH375_WR_DAT_PORT( 0x89 );  /* 位7为1则收到NAK时无限重试, 位3~位0为超时后的重试次数 */
/* 如果单片机在打印机忙时并无事可做,建议设置位7为1,使CH375在收到NAK时自动重试直到操作成功或者失败 */
/* 如果希望单片机在打印机忙时能够做其它事,那么应该设置位7为0,使CH375在收到NAK时不重试,
   所以在下面的USB通讯过程中,如果USB打印机正忙,issue_token等子程序将得到状态码USB_INT_RET_NAK */
				}
			}
		}
	}
	return(status);
}
Esempio n. 15
0
int main(int argc, char** argv){

    if(argc != 3){
        printf("[uso]: %s <porta> <arquivo>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int servidor_socket, cliente_socket;
    struct sockaddr_in servidor, cliente;
    int SOCK_LEN = sizeof(struct sockaddr_in);

    size_t bytes_enviados = 0;
    struct timeval tempo_ini;
    struct timeval tempo_fim;
    unsigned long int tempo_total = 0;

    size_t tamanho_arquivo = 0;

    servidor_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    set_addr(&servidor, atoi(argv[1]));

    bind(servidor_socket, (struct sockaddr*) &servidor,
         sizeof(struct sockaddr_in));

    listen(servidor_socket, 1024);
    printf("Esperando conexoes: localhost:%s\n", argv[1]);

    while(true){
        cliente_socket = accept(servidor_socket, (struct sockaddr*) &cliente,
                                (socklen_t*) &SOCK_LEN);
        notifica_conn(&cliente, true);

        gettimeofday(&tempo_ini, NULL);
        send_huge_file(cliente_socket, &bytes_enviados, argv[2]);
        gettimeofday(&tempo_fim, NULL);

        tempo_total = tempo_fim.tv_sec - tempo_ini.tv_sec;
        fprintf(stderr, "Vazao: %.3lfKB/s\n",
                (bytes_enviados/1024.0)/(float)tempo_total);

        close(cliente_socket);
        notifica_conn(&cliente, false);

    }

    close(servidor_socket);

}
Esempio n. 16
0
void readROM(char *filename) {
  unsigned long addr;
  unsigned char byte;

  FILE *ROMFile;
  ROMFile = fopen(filename, "w");

  for (addr = 0; addr < ROM_SIZE; addr++) {
    set_addr(addr);
    usleep(200);
    byte = read_byte();
    fputc(byte, ROMFile);
  }

  fclose(ROMFile);
}
Esempio n. 17
0
/**
 * \brief                 Set current IRQ to PIRQ. The interrupt router can be
 *                        programmed to allow PIRQ[A:H] to be routed internally
 *                        to the 8259 as ISA compatible interrupts. See also
 *                        pci_irq_agent_set_pirq().
 * \param pirq            PIRQ to be used, PIRQ[A:H].
 * \param pin             IRQ to be used, IRQ[0:15].
 * \param route_to_legacy Whether or not the interrupt should be routed to PIC 8259.
 */
void
pci_pirq_set_irq(PIRQ pirq, uint8_t irq, uint8_t route_to_legacy)
{
  pci_config_addr_t pci;
  uint32_t value;

  assert(pirq >= PIRQA && pirq <= PIRQH);
  assert(irq >= 0 && irq <= 0xF);
  assert(route_to_legacy == 0 || route_to_legacy == 1);

  pci.raw = 0;
  pci.bus = 0;
  pci.dev = 31;
  pci.func = 0;
  pci.reg_off = (pirq <= PIRQD) ? 0x60 : 0x64; /* PABCDRC and PEFGHRC Registers */

  value = pci_config_read(pci);

  switch(pirq) {
  case PIRQA:
  case PIRQE:
    value &= ~0x8F;
    value |= irq;
    value |= (!route_to_legacy << 7);
    break;
  case PIRQB:
  case PIRQF:
    value &= ~0x8F00;
    value |= (irq << 8);
    value |= (!route_to_legacy << 15);
    break;
  case PIRQC:
  case PIRQG:
    value &= ~0x8F0000;
    value |= (irq << 16);
    value |= (!route_to_legacy << 23);
    break;
  case PIRQD:
  case PIRQH:
    value &= ~0x8F000000;
    value |= (irq << 24);
    value |= (!route_to_legacy << 31);
  }

  set_addr(pci);
  outl(PCI_CONFIG_DATA_PORT, value);
}
Esempio n. 18
0
redis_commands::redis_commands(const char* addr, const char* passwd,
	int conn_timeout, int rw_timeout, bool prefer_master,
	const char* cmds_file)
	: conn_timeout_(conn_timeout)
	, rw_timeout_(rw_timeout)
	, prefer_master_(prefer_master)
	, all_cmds_perm_("yes")
{
	if (passwd && *passwd)
		passwd_ = passwd;

	set_addr(addr, addr_);
	conns_ = NULL;

	init(cmds_file);
	create_cluster();
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
    int in, out;
    ssize_t sz;
    size_t left;
    off_t offset;

    in = open("./sendfile.c", O_RDONLY);

#ifdef SEND_TO_FILE
    out = open("./foo.out", O_WRONLY);
#else
    int ret;
    struct sockaddr_in addr;

    out = socket(AF_INET, SOCK_STREAM, 0);
    assert(out > 0);
    set_addr(&addr, "127.0.0.1", 8080);
    ret = connect(out, (const struct sockaddr *)&addr, sizeof(struct sockaddr_in));
    if (ret != 0) {
        perror("connect");
    }
    assert(ret == 0);
#endif
    assert(in>0 && out>0);

    offset = 0x4020008BD0LLU;
    left = 60000;

    while (left) {
        sz = sendfile(out, in, &offset, left);
        if (sz < 1) {
            perror("sendfile");
            break;
        }
        printf("sent: %zd\n", sz);
        left -= sz;
        offset += sz;
    }
    close(in);
    close(out);

    return 0;
}
Esempio n. 20
0
// this updates the unpacked info for a new code buffer
address BoundRelocation::update_addrs(address old_addr, const CodeBuffer& new_cb, const CodeBuffer& old_cb) {

  // Point to the relocation info
  Relocation *r = reloc();

  // Transform the addr for the new code buffer
  address new_addr = old_cb.transform_address(new_cb, old_addr);

  // Set the transformed address
  set_addr( new_addr );

  // Update any internal addresses
  r->update_addrs(new_cb, old_cb);

  // Apply a delta to internal pointers
  r->fix_relocation_at_move(new_addr - old_addr);

  // Return the new address
  return (new_addr);
}
Esempio n. 21
0
void incoming_arp(VCC *vcc,struct atmarphdr *hdr,int len)
{
    ITF *itf;
    ENTRY *entry;
    void *sha,*ssa,*spa,*tha,*tsa,*tpa;
    struct sockaddr_atmsvc source,target;
    uint32_t src_ip,tgt_ip;
    unsigned char *here;

    if (len < hdr->data-(unsigned char *) hdr) {
	diag(COMPONENT,DIAG_ERROR,"got truncated ARP packet (%d bytes)",len);
	return;
    }
    if (hdr->ar_hrd != htons(ARPHRD_ATM)) {
	diag(COMPONENT,DIAG_ERROR,"unknown hw protocol 0x%04x",
	  ntohs(hdr->ar_hrd));
	return;
    }
    if (hdr->ar_pro != htons(ETH_P_IP)) {
	diag(COMPONENT,DIAG_ERROR,"unknown upper protocol 0x%04x",
	  ntohs(hdr->ar_pro));
	return;
    }
    if (!(hdr->ar_shtl & TL_LEN)) hdr->ar_shtl = 0; /* paranoia */
    if (!(hdr->ar_thtl & TL_LEN)) hdr->ar_thtl = 0;
    here = hdr->data;
    sha = get_addr(&here,hdr->ar_shtl & TL_LEN);
    ssa = get_addr(&here,hdr->ar_sstl & TL_LEN);
    spa = get_addr(&here,hdr->ar_spln);
    tha = get_addr(&here,hdr->ar_thtl & TL_LEN);
    tsa = get_addr(&here,hdr->ar_tstl & TL_LEN);
    tpa = get_addr(&here,hdr->ar_tpln);
    if (here-(unsigned char *) hdr > len) {
	diag(COMPONENT,DIAG_ERROR,"message too short (got %d, need %d)",len,
	  here-(unsigned char *) hdr);
	return;
    }
    set_addr(&source,sha,ssa,hdr->ar_shtl,hdr->ar_sstl);
    set_addr(&target,tha,tsa,hdr->ar_thtl,hdr->ar_tstl);
    src_ip = get_ip(spa);
    tgt_ip = get_ip(tpa);
{
   unsigned char *ipp;
   char buffer[MAX_ATM_ADDR_LEN+1];

   ipp = (unsigned char *) &src_ip;
   diag(COMPONENT,DIAG_DEBUG,"  SRC IP: %d.%d.%d.%d",ipp[0],ipp[1],ipp[2],
     ipp[3]);
   if (atm2text(buffer,MAX_ATM_ADDR_LEN+1,(struct sockaddr *) &source,pretty)
     >= 0) diag(COMPONENT,DIAG_DEBUG,"  SRC ATM: %s",buffer);
   ipp = (unsigned char *) &tgt_ip;
   diag(COMPONENT,DIAG_DEBUG,"  DST IP: %d.%d.%d.%d",ipp[0],ipp[1],ipp[2],
     ipp[3]);
   if (atm2text(buffer,MAX_ATM_ADDR_LEN+1,(struct sockaddr *) &target,pretty)
     >= 0) diag(COMPONENT,DIAG_DEBUG,"  DST ATM: %s",buffer);
}
    switch (ntohs(hdr->ar_op)) {
	case ARPOP_REQUEST:
	    diag(COMPONENT,DIAG_DEBUG,"got ARP_REQ");
	    if (learn(vcc,src_ip,&source)) break;
	    entry = NULL;
	    itf = lookup_itf_by_ip(tgt_ip);
	    entry = itf ? lookup_ip(itf,tgt_ip) : NULL;
	    if (entry && entry->state == as_valid && (entry->flags & ATF_PUBL))
	      {
		if (entry->addr)
		    arp_reply(vcc,tgt_ip,entry->addr,src_ip,&source);
		else arp_nak(vcc,tgt_ip,src_ip,&source);
	    }
	    else {
		if (itf && itf->local_ip == tgt_ip)
		    arp_reply(vcc,tgt_ip,NULL,src_ip,&source);
		else arp_nak(vcc,tgt_ip,src_ip,&source);
	    }
	    break;
	case ARPOP_REPLY:
	    diag(COMPONENT,DIAG_DEBUG,"got ARP_REP");
	    if (!vcc->entry || !(vcc->entry->flags & ATF_ARPSRV)) {
		diag(COMPONENT,DIAG_ERROR,"got ARP response from charlatan");
		break;
	    }
	    (void) learn(NULL,src_ip,&source);
	    break;
	case ARPOP_InREQUEST:
	    diag(COMPONENT,DIAG_DEBUG,"got InARP_REQ");
	    if (!learn(vcc,src_ip,&source)) inarp_reply(vcc,src_ip,&source);
	    break;
	case ARPOP_InREPLY:
	    diag(COMPONENT,DIAG_DEBUG,"got InARP_REP");
	    (void) learn(vcc,src_ip,&source);
	    break;
	case ARPOP_NAK:
	    diag(COMPONENT,DIAG_DEBUG,"got ARP_NAK");
	    if (!vcc->entry || !(vcc->entry->flags & ATF_ARPSRV)) {
		diag(COMPONENT,DIAG_ERROR,"got ARP response from charlatan");
		break;
	    }
	    learn_nak(tgt_ip);
	    break;
	default:
	    diag(COMPONENT,DIAG_ERROR,"unrecognized ARP op 0x%x",
	      ntohs(hdr->ar_op));
    }
}
Esempio n. 22
0
inline void set_dst_addr(ap_package_t *pkt, U8 addr)
{
	set_addr(&pkt->dst_addr, addr);
}
Esempio n. 23
0
/*************************************************
  Function:		storage_add_jddev
  Description: 	添加设备类型
  Input:
  	1.info
  Output:		无
  Return:		ECHO_STORAGE
  Others:
*************************************************/
ECHO_STORAGE storage_add_jddev (PJD_DEV_INFO info)
{
    PJD_DEV_LIST_INFO jddevlist = NULL;
    ECHO_STORAGE ret = ECHO_STORAGE_ERR;
    uint8 i,j;
    uint8 max = 0;

    if (NULL == info)
    {
        return ECHO_STORAGE_ERR;
    }

    if (info->IsUsed && is_same_addr(info->JdType,info->Address,info->Index))
    {
        return ECHO_STORAGE_SAME_ADDR;
    }

    max = get_dev_max(info->JdType);
    jddevlist = storage_get_jddev(info->JdType, FALSE);

    if (jddevlist)
    {
        for (i = 0; i < jddevlist->nCount; i++)
        {
            if (jddevlist->pjd_dev_info[i].IsUsed)
            {
#ifndef _USERDEFINE_JDNAME_
                if ((jddevlist->pjd_dev_info[i].TextIDPos == info->TextIDPos&& jddevlist->pjd_dev_info[i].TextIDName == info->TextIDName)
                        && jddevlist->pjd_dev_info[i].Index != info->Index)
                {
                    ret = ECHO_STORAGE_SAME_NAME;
                    break;
                }
#endif
            }
        }

        if (ECHO_STORAGE_SAME_ADDR != ret && ECHO_STORAGE_SAME_NAME != ret)
        {
            jddevlist->pjd_dev_info[info->Index].IsUsed = info->IsUsed;
            if (0 == info->IsUsed)
            {
                jddevlist->pjd_dev_info[info->Index].Address = 0;
                jddevlist->pjd_dev_info[info->Index].TextIDName = 0;
                jddevlist->pjd_dev_info[info->Index].TextIDPos= 0;
                jddevlist->pjd_dev_info[info->Index].IsGroup = 0;
                jddevlist->pjd_dev_info[info->Index].IsTune = 0;
                jddevlist->pjd_dev_info[info->Index].TextID = 0;
                for (j = 0; j < JD_SCENE_MAX; j++)
                {
                    jddevlist->pjd_dev_info[info->Index].Commond[j] = 0;
                    jddevlist->pjd_dev_info[info->Index].param[j][0] = 0;
                }
            }
            else
            {
                for (i = 0; i < JD_SCENE_MAX; i++)
                {
                    info->Commond[i] = jddevlist->pjd_dev_info[info->Index].Commond[i];
                    info->param[i][0] = jddevlist->pjd_dev_info[info->Index].param[i][0];
                    if (info->Commond[i] > 1)
                    {
                        info->Commond[i] = 0;
                    }

                    if (info->param[i][0] > 10)
                    {
                        info->param[i][0] = 4;
                    }
                    info->param[i][1] = jddevlist->pjd_dev_info[info->Index].param[i][1];
                    info->param[i][2] = jddevlist->pjd_dev_info[info->Index].param[i][2];
                    info->param[i][3] = jddevlist->pjd_dev_info[info->Index].param[i][3];
                    info->param[i][4] = jddevlist->pjd_dev_info[info->Index].param[i][4];
                    info->param[i][5] = jddevlist->pjd_dev_info[info->Index].param[i][5];
                    info->param[i][6] = jddevlist->pjd_dev_info[info->Index].param[i][6];
                }
                memcpy(&jddevlist->pjd_dev_info[info->Index],info,sizeof(JD_DEV_INFO));
            }
            set_addr(info->JdType, info->Index, jddevlist->pjd_dev_info[info->Index].Address);
            save_jd_storage(info->JdType, jddevlist->pjd_dev_info, max);
            ret = ECHO_STORAGE_OK;
        }
    }

    free_jd_memory(&jddevlist);
    return ret;
}
Esempio n. 24
0
SocketAddress::SocketAddress(const SocketAddress &addr)
{
    _ip_address[0] = '\0';
    set_addr(addr.get_addr());
    set_port(addr.get_port());
}
Esempio n. 25
0
SocketAddress::SocketAddress(nsapi_addr_t addr, uint16_t port)
{
    _ip_address[0] = '\0';
    set_addr(addr);
    set_port(port);
}
Esempio n. 26
0
File: ifc.c Progetto: dbittman/sea
int main(int argc, char **argv)
{
	int c;
	int read = 1; /* by default, we read data and print it out. operation modes that
				   * write settings change this to 0. */
	const char *name = 0;
	/* parse options to look for the interface name... */
	opterr = 0;
	while((c = getopt(argc, argv, "hi:")) != -1) {
		switch(c) {
			case 'h':
				usage();
				break;
			case 'i':
				name = optarg;
				break;
		}
	}

	/* reset getopt() and set the things */
	optind = 0;
	opterr = 1;
	while((c = getopt(argc, argv, "u:s:n:m:i:hb:")) != -1) {
		switch(c) {
			case 'u':
				read = 0;
				if(!name) {
					fprintf(stderr, "ifc: no interface specified\n");
					exit(1);
				}
				if(set_flag(name, optarg, 1))
					exit(1);
				break;
			case 's':
				read = 0;
				if(!name) {
					fprintf(stderr, "ifc: no interface specified\n");
					exit(1);
				}
				if(set_flag(name, optarg, 0))
					exit(1);
				break;
			case 'n':
				read = 0;
				if(!name) {
					fprintf(stderr, "ifc: no interface specified\n");
					exit(1);
				}
				if(set_addr(name, optarg))
					exit(1);
				break;
			case 'b':
				read = 0;
				if(!name) {
					fprintf(stderr, "ifc: no interface specified\n");
					exit(1);
				}
				if(set_broad_addr(name, optarg))
					exit(1);
				break;
			case 'm':
				read = 0;
				if(!name) {
					fprintf(stderr, "ifc: no interface specified\n");
					exit(1);
				}
				if(set_mask(name, optarg))
					exit(1);
				break;
			case 't':
				read = 0;
				if(!name) {
					fprintf(stderr, "ifc: no interface specified\n");
					exit(1);
				}
				if(set_mtu(name, optarg))
					exit(1);
				break;
			case 'i': break;
			default:
				exit(1);
		}
	}
	if(read)
		read_stats(name);
	return 0;
}
Esempio n. 27
0
int main(int argc, char **argv)
{
	int forks = 1;
	array_t(char*) addr_set;
	array_init(addr_set);
	char *keyfile = NULL;
	const char *config = NULL;
	char *keyfile_buf = NULL;

	/* Long options. */
	int c = 0, li = 0, ret = 0;
	struct option opts[] = {
		{"addr", required_argument,   0, 'a'},
		{"config", required_argument, 0, 'c'},
		{"keyfile",required_argument, 0, 'k'},
		{"forks",required_argument,   0, 'f'},
		{"verbose",    no_argument,   0, 'v'},
		{"version",   no_argument,    0, 'V'},
		{"help",      no_argument,    0, 'h'},
		{0, 0, 0, 0}
	};
	while ((c = getopt_long(argc, argv, "a:c:f:k:vVh", opts, &li)) != -1) {
		switch (c)
		{
		case 'a':
			array_push(addr_set, optarg);
			break;
		case 'c':
			config = optarg;
			break;
		case 'f':
			g_interactive = 0;
			forks = atoi(optarg);
			if (forks == 0) {
				kr_log_error("[system] error '-f' requires number, not '%s'\n", optarg);
				return EXIT_FAILURE;
			}
#if (!defined(UV_VERSION_HEX)) || (!defined(SO_REUSEPORT))
			if (forks > 1) {
				kr_log_error("[system] libuv 1.7+ is required for SO_REUSEPORT support, multiple forks not supported\n");
				return EXIT_FAILURE;
			}
#endif
			break;
		case 'k':
			keyfile_buf = malloc(PATH_MAX);
			assert(keyfile_buf);
			/* Check if the path is absolute */
			if (optarg[0] == '/') {
				keyfile = strdup(optarg);
			} else {
				/* Construct absolute path, the file may not exist */
				keyfile = realpath(".", keyfile_buf);
				if (keyfile) {
					int len = strlen(keyfile);
					int namelen = strlen(optarg);
					if (len + namelen < PATH_MAX - 1) {
						keyfile[len] = '/';
						memcpy(keyfile + len + 1, optarg, namelen + 1);
						keyfile = strdup(keyfile); /* Duplicate */
					} else {
						keyfile = NULL; /* Invalidate */
					}
				}
			}
			free(keyfile_buf);
			if (!keyfile) {
				kr_log_error("[system] keyfile '%s': not writeable\n", optarg);
				return EXIT_FAILURE;
			}
			break;
		case 'v':
			kr_debug_set(true);
			break;
		case 'V':
			kr_log_info("%s, version %s\n", "Knot DNS Resolver", PACKAGE_VERSION);
			return EXIT_SUCCESS;
		case 'h':
		case '?':
			help(argc, argv);
			return EXIT_SUCCESS;
		default:
			help(argc, argv);
			return EXIT_FAILURE;
		}
	}

	/* Switch to rundir. */
	if (optind < argc) {
		const char *rundir = argv[optind];
		if (access(rundir, W_OK) != 0) {
			kr_log_error("[system] rundir '%s': %s\n", rundir, strerror(errno));
			return EXIT_FAILURE;
		}
		ret = chdir(rundir);
		if (ret != 0) {
			kr_log_error("[system] rundir '%s': %s\n", rundir, strerror(errno));
			return EXIT_FAILURE;
		}
		if(config && access(config, R_OK) != 0) {
			kr_log_error("[system] rundir '%s'\n", rundir);
			kr_log_error("[system] config '%s': %s\n", config, strerror(errno));
			return EXIT_FAILURE;
		}
	}

	kr_crypto_init();

	/* Fork subprocesses if requested */
	int fork_count = forks;
	while (--forks > 0) {
		int pid = fork();
		if (pid < 0) {
			perror("[system] fork");
			return EXIT_FAILURE;
		}
		/* Forked process */
		if (pid == 0) {
			kr_crypto_reinit();
			break;
		}
	}

	/* Block signals. */
	uv_loop_t *loop = uv_default_loop();
	uv_signal_t sigint, sigterm;
	uv_signal_init(loop, &sigint);
	uv_signal_init(loop, &sigterm);
	uv_signal_start(&sigint, signal_handler, SIGINT);
	uv_signal_start(&sigterm, signal_handler, SIGTERM);
	/* Create a server engine. */
	knot_mm_t pool = {
		.ctx = mp_new (4096),
		.alloc = (knot_mm_alloc_t) mp_alloc
	};
	struct engine engine;
	ret = engine_init(&engine, &pool);
	if (ret != 0) {
		kr_log_error("[system] failed to initialize engine: %s\n", kr_strerror(ret));
		return EXIT_FAILURE;
	}
	/* Create worker */
	struct worker_ctx *worker = init_worker(loop, &engine, &pool, forks, fork_count);
	if (!worker) {
		kr_log_error("[system] not enough memory\n");
		return EXIT_FAILURE;
	}
	/* Bind to sockets and run */
	for (size_t i = 0; i < addr_set.len; ++i) {
		int port = 53;
		const char *addr = set_addr(addr_set.at[i], &port);
		ret = network_listen(&engine.net, addr, (uint16_t)port, NET_UDP|NET_TCP);
		if (ret != 0) {
			kr_log_error("[system] bind to '%s#%d' %s\n", addr, port, knot_strerror(ret));
			ret = EXIT_FAILURE;
		}
	}
	/* Start the scripting engine */
	if (ret == 0) {
		ret = engine_start(&engine, config ? config : "config");
		if (ret == 0) {
			if (keyfile) {
				auto_free char *cmd = afmt("trust_anchors.file = '%s'", keyfile);
				if (!cmd) {
					kr_log_error("[system] not enough memory\n");
					return EXIT_FAILURE;
				}
				engine_cmd(&engine, cmd);
				lua_settop(engine.L, 0);
			}
			/* Run the event loop */
			ret = run_worker(loop, &engine);
		}
	}
	/* Cleanup. */
	array_clear(addr_set);
	engine_deinit(&engine);
	worker_reclaim(worker);
	mp_delete(pool.ctx);
	if (ret != 0) {
		ret = EXIT_FAILURE;
	}
	kr_crypto_cleanup();
	return ret;
}
Esempio n. 28
0
/* Helper function to handle ARP requests */
void handle_arpreq(struct sr_instance *sr, struct sr_arpreq *req) {
  time_t curtime = time(NULL);
  struct sr_packet *packet;
  struct sr_arpcache *cache = &(sr->cache);

  if (difftime(curtime, req->sent) > 1.0) { 
    /* send icmp host unreachable to source addr of all pkts waiting on this request  */
    if (req->times_sent >= 5) {
      for (packet = req->packets; packet != NULL; packet = packet->next) {
        assert(packet->buf);
        sr_ip_hdr_t *ipDropped = (sr_ip_hdr_t *) (packet->buf + 14); 

        struct sr_if* iface;
        iface = sr_get_interface(sr, packet->iface);

        uint8_t *outgoing = malloc(sizeof(sr_ethernet_hdr_t) + sizeof(sr_ip_hdr_t) + sizeof(sr_icmp_t3_hdr_t));
        sr_ethernet_hdr_t *ethHeader = (sr_ethernet_hdr_t *)outgoing;
        sr_ip_hdr_t *ipHeader = (sr_ip_hdr_t *) (outgoing + 14);  
        
        /* Get ICMP Packet*/
        uint8_t* icmp_packet;
        icmp_packet = createICMP(3, 1, (uint8_t *)ipDropped, ipDropped->ip_len);
        memcpy(outgoing+34, icmp_packet, sizeof(sr_icmp_t3_hdr_t));
        free(icmp_packet);

        /*Setup IP Header*/
        ipHeader->ip_hl = 5;
        ipHeader->ip_v = 4;
        ipHeader->ip_tos = 0;
        ipHeader->ip_id = ipDropped->ip_id;
        ipHeader->ip_dst = ipDropped->ip_src;
        ipHeader->ip_src = iface->ip;
        ipHeader->ip_ttl = INIT_TTL;
        ipHeader->ip_off = htons(IP_DF);
        ipHeader->ip_sum = 0;
        ipHeader->ip_p = 1;
        ipHeader->ip_len = htons(sizeof(sr_ip_hdr_t) + sizeof(sr_icmp_t3_hdr_t));
        ipHeader->ip_sum = cksum((uint8_t *)ipHeader,20);        

        /*Setup Ethernet Header*/
        set_addr(ethHeader, iface->addr, ethHeader->ether_shost);
        ethHeader->ether_type = htons(0x0800);

        sr_send_packet(sr, outgoing, sizeof(sr_ethernet_hdr_t) + sizeof(sr_ip_hdr_t) + sizeof(sr_icmp_t3_hdr_t), packet->iface);
        free(outgoing);
      }
      sr_arpreq_destroy(&sr->cache, req);
    }

    /* send an arp request */
    else {
      packet = req->packets;
      assert(packet->buf);
      /*struct sr_ethernet_hdr *ethIncoming = (struct sr_ethernet_hdr *)(packet->buf);*/
      sr_ip_hdr_t * ipIncoming = (sr_ip_hdr_t *)((packet->buf) + 14);

      uint8_t * outgoing = (uint8_t*)malloc(sizeof(sr_ethernet_hdr_t) + sizeof(sr_arp_hdr_t));
      sr_ethernet_hdr_t *ethHeader = (sr_ethernet_hdr_t *) outgoing;
      sr_arp_hdr_t * arpHeader = (sr_arp_hdr_t *)(outgoing + sizeof(sr_ethernet_hdr_t));

      /* set ARPHeader to request */
      arpHeader->ar_hrd = htons(0x0001); 
      arpHeader->ar_pro = htons(0x800); 
      arpHeader->ar_op = htons(0x0001);
      arpHeader->ar_hln = 0x0006; 
      arpHeader->ar_pln = 0x0004;
      memset(arpHeader->ar_tha, 255, 6);
      arpHeader->ar_tip = ipIncoming->ip_dst;

      /* set Ethernet Header */
      ethHeader->ether_type = htons(0x0806);
      memset(ethHeader->ether_dhost, 255,6);

      /* get outgoing interface and send the request */
      struct sr_if* if_walker = 0;
      if_walker = sr->if_list;

      while(if_walker)
      {
        arpHeader->ar_sip = if_walker->ip;
        memcpy(arpHeader->ar_sha, if_walker->addr, 6);
        memcpy(ethHeader->ether_shost, if_walker->addr, 6);

        sr_send_packet(sr, outgoing, sizeof(sr_ethernet_hdr_t) + sizeof(sr_arp_hdr_t), if_walker->name);
        
        if_walker = if_walker->next;
      }

      free(outgoing);
      req->sent = curtime;
      req->times_sent++;
    }
  }
}
Esempio n. 29
0
void sr_natHandleIP(struct sr_instance* sr, uint8_t* packet,unsigned int len, struct sr_if * iface){
  assert(packet);
  sr_ethernet_hdr_t* ethHeader = (sr_ethernet_hdr_t*) packet;
  uint8_t* ip_packet = packet+sizeof(sr_ethernet_hdr_t);
  sr_ip_hdr_t * ipHeader = (sr_ip_hdr_t *) (ip_packet);  

  uint16_t incm_cksum = ipHeader->ip_sum;
  ipHeader->ip_sum = 0;
  uint16_t currentChecksum = cksum(ip_packet,20);
  ipHeader->ip_sum = incm_cksum;
  uint8_t* icmp_packet;

  /* if the destination address is one of my interfaces */
  if (currentChecksum==incm_cksum && sr_get_interface_from_ip(sr,ntohl(ipHeader->ip_dst)) != NULL){
    /* check cache for ip->mac mapping for next hop */
    /*struct sr_arpentry *entry;
    entry = sr_arpcache_lookup(&sr->cache, ipHeader->ip_dst);
    struct sr_rt * rt = (struct sr_rt *)sr_find_routing_entry_int(sr, ipHeader->ip_dst);
*/
    /* found next hop. send packet */
    if (ipHeader->ip_ttl <= 1){   /* IP TTL died. send ICMP type 11, code 0 */
      icmp_packet = createICMP(11, 0, ip_packet,len-14);
      memcpy(ip_packet+20,icmp_packet,sizeof(sr_icmp_t3_hdr_t));
      ipHeader->ip_p = 1;
      ipHeader->ip_len = htons(20+8+(len-34<28?len-34:28));
      free(icmp_packet);      
    } else if(ipHeader->ip_p==6){  /* IP TCP */
      icmp_packet = createICMP(3,3,ip_packet,len-14);
      memcpy(ip_packet+20,icmp_packet,sizeof(sr_icmp_t3_hdr_t));
      
      ipHeader->ip_p = 1;
      ipHeader->ip_len = htons(20+8+(len-34<28?len-34:28));
      free(icmp_packet);
    }else if(ipHeader->ip_tos==0 && ipHeader->ip_p==1){ /* IP ping */
	    sr_icmp_hdr_t * icmp_header = (sr_icmp_hdr_t *) (packet + sizeof(sr_ethernet_hdr_t) + sizeof(sr_ip_hdr_t));
      incm_cksum = icmp_header->icmp_sum;
      icmp_header->icmp_sum = 0;
	    currentChecksum = cksum(icmp_header,len - sizeof(sr_ethernet_hdr_t) - sizeof(sr_ip_hdr_t));
	    
      if(currentChecksum == incm_cksum && icmp_header->icmp_type == 8 && icmp_header->icmp_code == 0) {
	      icmp_header->icmp_type = 0;
        ipHeader->ip_sum = 0;
	      icmp_header->icmp_sum = cksum(icmp_header,len - sizeof(sr_ethernet_hdr_t) - sizeof(sr_ip_hdr_t));
	    }
      else{
        printf("ICMP INVALID\n");
        printf("%d != %d OR %d != %d\n",currentChecksum,incm_cksum, icmp_header->icmp_type, 8);
      }
    } else {
      printf("IP Bad\n");
      ip_packet = NULL;
    }
  }
  else{
      printf("IP INVALID\n");
      ip_packet = NULL;
  }
  if(ip_packet){  /* send ICMP packet */
    ipHeader->ip_dst = ipHeader->ip_src;
    ipHeader->ip_src = iface->ip;
    ipHeader->ip_ttl = 64;
    ipHeader->ip_sum = 0;
    ipHeader->ip_sum = cksum(ip_packet,20);

    struct sr_arpentry *entry;
    entry = sr_arpcache_lookup(&sr->cache, ipHeader->ip_dst);
    struct sr_rt * rt = (struct sr_rt *)sr_find_routing_entry_int(sr, ipHeader->ip_dst);

    if (entry && rt) {    /* found next hop. send packet */
      iface = sr_get_interface(sr, rt->interface);
      set_addr(ethHeader, iface->addr, entry->mac);
      sr_send_packet(sr,packet,len,iface->name);
      free(entry);
      ip_packet = NULL;
    } else if (rt) { /* send an arp request to find out what the next hop should be */
      struct sr_arpreq *req;
      sr_arpcache_insert(&(sr->cache), ethHeader->ether_shost, ipHeader->ip_src);
      req = sr_arpcache_queuereq(&(sr->cache), ipHeader->ip_dst, packet, len, iface->name);
      /*handle_arpreq(sr, req);*/
      ip_packet = NULL;
    }
  }
}