Example #1
0
uint16_t ipv6_csum(ipv6_hdr_t *ipv6_header, uint8_t *buf, uint16_t len, uint8_t proto)
{
    uint16_t sum = 0;
    DEBUG("Calculate checksum over src: %s, dst: %s, len: %04X, buf: %p, proto: %u\n",
          ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN,
                           &ipv6_header->srcaddr),
          ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN,
                           &ipv6_header->destaddr),
          len, buf, proto);
    sum = len + proto;
    sum = csum(sum, (uint8_t *)&ipv6_header->srcaddr, 2 * sizeof(ipv6_addr_t));
    sum = csum(sum, buf, len);
    return (sum == 0) ? 0xffff : HTONS(sum);
}
Example #2
0
void igmp_handler::set_ip_igmp_hdr(ip_igmp_tx_hdr_template_t* ip_igmp_hdr)
{
	ip_igmp_hdr->m_ip_hdr.ihl = IPV4_IGMP_HDR_LEN_WORDS;
	ip_igmp_hdr->m_ip_hdr.tot_len = htons(IPV4_IGMP_HDR_LEN + sizeof(igmphdr));
	ip_igmp_hdr->m_ip_hdr_ext = htonl(IGMP_IP_HEADER_EXT);
	ip_igmp_hdr->m_ip_hdr.check = 0;
	ip_igmp_hdr->m_ip_hdr.check = csum((unsigned short*)&ip_igmp_hdr->m_ip_hdr, (IPV4_IGMP_HDR_LEN_WORDS) * 2);

	// Create the IGMP header
	ip_igmp_hdr->m_igmp_hdr.type = IGMPV2_HOST_MEMBERSHIP_REPORT;
	ip_igmp_hdr->m_igmp_hdr.code = 0;
	ip_igmp_hdr->m_igmp_hdr.group = m_mc_addr.get_in_addr();
	ip_igmp_hdr->m_igmp_hdr.csum = 0;
	ip_igmp_hdr->m_igmp_hdr.csum = csum((unsigned short*)&ip_igmp_hdr->m_igmp_hdr, IGMP_HDR_LEN_WORDS * 2);
}
Example #3
0
double cmean(double *vec, int tlen)
{
	double tsum, tmean;
	tsum= csum(vec, tlen);
	tmean= tsum/(double) tlen;
	return(tmean);
}
Example #4
0
/*
 * The main procedure for processing the filtered packets
 */
bool process(char *packet, int pack_src)
{
    ssize_t                  send_len;
    uint16_t                 size_ip, tot_len;
    struct iphdr            *ip_header;
    struct udphdr           *udp_header;
    ip_port_pair_mapping_t  *test;

    ip_header  = (struct iphdr*)packet;
    size_ip    = ip_header->ihl<<2;
    tot_len    = ntohs(ip_header->tot_len);
    udp_header = (struct udphdr*)((char *)ip_header + size_ip);

    test = get_test_pair(&(clt_settings.transfer),
            ip_header->saddr, udp_header->source);
    ip_header->daddr = test->target_ip;
    udp_header->dest = test->target_port;

    udpcsum(ip_header, udp_header);
    ip_header->check = 0;
    ip_header->check = csum((unsigned short *)ip_header, size_ip); 

    send_len   = send_ip_packet(ip_header, tot_len);
    if (-1 == send_len) {
        log_info(LOG_ERR, "send to back error,tot_len:%d", tot_len);
        return false;
    }

    return true;
}
Example #5
0
int main(int argc, char *argv[])
{
  double t = 0.0;
  struct sigaction sig;
  unsigned int k = 0;
  unsigned int iters = atoi(argv[1]); //Purposefully not validating input
  unsigned int bs = atoi(argv[2]);
  int sum;
  unsigned char *block = NULL;

  /* initialize RNG */
  srand(time(NULL));

  /* setup signals */
  memset(&sig,0,sizeof(sig));
  sig.sa_handler = signal_handler;
  sigaction (SIGINT,  &sig, NULL);
  sigaction (SIGALRM, &sig, NULL);
  
  /* allocate and initialize data block */
  block = (unsigned char*)malloc(sizeof(unsigned char) * bs);
  memset(block,rand()%256,sizeof(unsigned char)*bs);
	
  while (k < iters) 
  {
    t = getTime();
    sum = csum((unsigned short*)block, bs);
    t = getTime() - t;	
    printf("%3.7f 0X%xd \n",t,sum);
    k++;
  }     

  exit(0);
}
Example #6
0
bool tcp_write_checksum(uint8_t * tcp_segment, buffer_t * ip_psh)
{
    struct tcphdr * tcp_header = (struct tcphdr *) tcp_segment;
    size_t          size_ip    = buffer_get_size(ip_psh),
                    size_tcp   = tcp_get_header_size(tcp_segment) + 2, // hardcoded payload size
                    size_psh   = size_ip + size_tcp;
    uint8_t       * psh;

    // TCP checksum computation requires the IPv* header
    if (!ip_psh) {
        errno = EINVAL;
        return false;
    }

    // Allocate the buffer which will contains the pseudo header
    if (!(psh = calloc(1, size_psh))) {
        return false;
    }

    // Put the excerpt of the IP header into the pseudo header
    memcpy(psh, buffer_get_data(ip_psh), size_ip);

    // Put the TCP header and its content into the pseudo header
    memcpy(psh + size_ip, tcp_segment, size_tcp);

    // Overrides the TCP checksum in psh with zeros
    memset(psh + size_ip + offsetof(struct tcphdr, check), 0, sizeof(uint16_t));

    // Compute the checksum
    tcp_header->check = csum((const uint16_t *) psh, size_psh);
    free(psh);
    return true;
}
Example #7
0
File: icmp.c Project: OPSF/uClinux
static void icmp6csum(struct in6_addr *src, struct in6_addr *dst,
							 sendip_data *hdr, sendip_data *data) {
	icmp_header *icp = (icmp_header *)hdr->data;
	struct ipv6_pseudo_hdr phdr;

	/* Make sure tempbuf is word aligned */
	u_int16_t *buf = malloc(sizeof(phdr)+hdr->alloc_len+data->alloc_len);
	u_int8_t *tempbuf = (u_int8_t *)buf;
	icp->check = 0;
	if(tempbuf == NULL) {
		fprintf(stderr,"Out of memory: ICMP checksum not computed\n");
		return;
	}
	memcpy(tempbuf+sizeof(phdr), hdr->data, hdr->alloc_len);
	memcpy(tempbuf+sizeof(phdr)+hdr->alloc_len, data->data, data->alloc_len);

	/* do an ipv6 checksum */
	memset(&phdr, 0, sizeof(phdr));
	memcpy(&phdr.source, src, sizeof(struct in6_addr));
	memcpy(&phdr.destination, dst, sizeof(struct in6_addr));
	phdr.ulp_length = htonl(hdr->alloc_len+data->alloc_len);
	phdr.nexthdr = IPPROTO_ICMPV6;
	
	memcpy(tempbuf, &phdr, sizeof(phdr));
	
	icp->check = csum(buf,sizeof(phdr)+hdr->alloc_len+data->alloc_len);
	free(buf);
}
Example #8
0
static inline uint16_t icmp_cksum(uint16_t l4_len,
                                          struct icmphdr const* icmp) 
{
    uint16_t cksum;

    cksum = csum((void*)icmp, l4_len);
    return cksum;
}
Example #9
0
static inline uint16_t
ipv4_cksum(const struct iphdr *ipv4_hdr)
{
    uint16_t cksum;
    
    cksum = csum((void*)ipv4_hdr, sizeof(struct iphdr));
    return cksum;
}
Example #10
0
/* Make sure we get the calculation in RFC 1624 section 4 correct. */
static void
test_rfc1624(void)
{
    /* "...an IP packet header in which a 16-bit field m = 0x5555..." */
    uint8_t data[32] = {
        0xfe, 0x8f, 0xc1, 0x14, 0x4b, 0x6f, 0x70, 0x2a,
        0x80, 0x29, 0x78, 0xc0, 0x58, 0x81, 0x77, 0xaa,
        0x66, 0x64, 0xfc, 0x96, 0x63, 0x97, 0x64, 0xee,
        0x12, 0x53, 0x1d, 0xa9, 0x2d, 0xa9, 0x55, 0x55
    };

    /* "...the one's complement sum of all other header octets is 0xCD7A." */
    assert(ntohs(csum(data, sizeof data - 2)) == 0xffff - 0xcd7a);

    /* "...the header checksum would be:

          HC = ~(0xCD7A + 0x5555)
             = ~0x22D0
             =  0xDD2F"
    */
    assert(ntohs(csum(data, sizeof data)) == 0xdd2f);

    /* "a 16-bit field m = 0x5555 changes to m' = 0x3285..." */
    data[30] = 0x32;
    data[31] = 0x85;

    /* "The new checksum via recomputation is:

          HC' = ~(0xCD7A + 0x3285)
              = ~0xFFFF
              =  0x0000"
    */
    assert(ntohs(csum(data, sizeof data)) == 0x0000);

    /* "Applying [Eqn. 3] to the example above, we get the correct result:

          HC' = ~(C + (-m) + m')
              = ~(0x22D0 + ~0x5555 + 0x3285)
              = ~0xFFFF
              =  0x0000" */
    assert(recalc_csum16(htons(0xdd2f), htons(0x5555), htons(0x3285))
           == htons(0x0000));

    mark('#');
}
Example #11
0
int send_message(int socket, char* message) {
  int result;
  char* buffer = (char*)malloc((6+strlen(message)+1)*sizeof(char));
  sprintf(buffer, "%04X%02X%s", (unsigned int)strlen(message), csum(message), message);

  result = send_string(socket, buffer);
  if (!(result == (int) strlen(message))) return -1;
  else return 0;
}
Example #12
0
/* Make sure we get the calculation in RFC 1624 section 4 correct. */
static void
test_rfc1624(void)
{
    /* "...an IP packet header in which a 16-bit field m = 0x5555..." */
    uint8_t data[32] =
        "\xfe\x8f\xc1\x14\x4b\x6f\x70\x2a\x80\x29\x78\xc0\x58\x81\x77\xaa"
        "\x66\x64\xfc\x96\x63\x97\x64\xee\x12\x53\x1d\xa9\x2d\xa9\x55\x55";

    /* "...the one's complement sum of all other header octets is 0xCD7A." */
    assert(ntohs(csum(data, sizeof data - 2)) == 0xffff - 0xcd7a);

    /* "...the header checksum would be:

          HC = ~(0xCD7A + 0x5555)
             = ~0x22D0
             =  0xDD2F"
    */
    assert(ntohs(csum(data, sizeof data)) == 0xdd2f);

    /* "a 16-bit field m = 0x5555 changes to m' = 0x3285..." */
    data[30] = 0x32;
    data[31] = 0x85;

    /* "The new checksum via recomputation is:

          HC' = ~(0xCD7A + 0x3285)
              = ~0xFFFF
              =  0x0000"
    */
    assert(ntohs(csum(data, sizeof data)) == 0x0000);

    /* "Applying [Eqn. 3] to the example above, we get the correct result:

          HC' = ~(C + (-m) + m')
              = ~(0x22D0 + ~0x5555 + 0x3285)
              = ~0xFFFF
              =  0x0000" */
    assert(recalc_csum16(htons(0xdd2f), htons(0x5555), htons(0x3285))
           == htons(0x0000));

    mark('#');
}
double w4(Point& atom){
    const int l = 4;
    const int len = 2 * l + 1;
    Comp csum(0,0);
    for(int i=0; i<WN; i++){
        Comp ctmp=WS[i];
        for(int ii = 0; ii < 3; ii++){
            ctmp *= atom.q4m[WI[i][ii] + 4];
        }
        csum += ctmp;
    }
    return csum.real() / std::pow(atom.q4, 3) / std::pow(len / 4 / Pi, 1.5);
}
static inline QString computeChecksum(const QString& s)
{
    QByteArray ba = s.toUtf8();

    QByteArray md5 = QCryptographicHash::hash(ba, QCryptographicHash::Md5);

    QString csum("");

    for(int i = 0; i < md5.size(); i++)
        csum += QString("%1").arg((int)(md5[i]&0xFF), 2, 16, QLatin1Char('0'));

    return csum;
}
Example #15
0
/*
 * the main procedure for processing the filtered packets
 */
bool process(char *packet, int pack_src)
{
    int                      diff;
    time_t                   cur_time;
    ssize_t                  send_len;
    uint16_t                 size_ip, tot_len;
    struct iphdr            *ip_header;
    struct udphdr           *udp_header;
    ip_port_pair_mapping_t  *test;

    /* TODO time update will be optimized later */
    cur_time   = time(0);
    if (last_record_time != 0) {
        diff = cur_time - last_record_time;
        if (diff > 3) {
            log_info(LOG_INFO, "udp packets captured:%llu,packets sent:%llu",
                    clt_udp_cnt, clt_udp_send_cnt);
            last_record_time = cur_time;
        }
    } else {
        last_record_time = cur_time;
    }

    ip_header  = (struct iphdr *)packet;
    size_ip    = ip_header->ihl<<2;
    tot_len    = ntohs(ip_header->tot_len);
    udp_header = (struct udphdr*)((char *)ip_header + size_ip);

    test = get_test_pair(&(clt_settings.transfer),
            ip_header->daddr, udp_header->dest);
    ip_header->daddr = test->target_ip;
    udp_header->dest = test->target_port;

    udpcsum(ip_header, udp_header);
    ip_header->check = 0;
    ip_header->check = csum((unsigned short *)ip_header, size_ip); 

    /* check if it needs fragmentation */
    if (tot_len > clt_settings.mtu) {
        ip_fragmentation(ip_header, udp_header);
    } else {
        send_len   = send_ip_packet(ip_header, tot_len);
        if (-1 == send_len) {
            log_info(LOG_ERR, "send to back error,tot_len:%d", tot_len);
            return false;
        }
        clt_udp_send_cnt++;
    }

    return true;
}
Example #16
0
void
srf_write(FILE *       const ofP,
          struct srf * const srfP) {

    uint8_t      srfCsum;    /* checksum value in SRF image */
    size_t       padLen;
    unsigned int i;
    size_t       bytesWritten;

    padLen = 1;  /* initial value */

    if (!checkHeader(&srfP->header))
        pm_error("invalid srf header");
    if (!writeHeader(ofP, &srfP->header))
        pm_error("write srf header");
    padLen += lenHeader(&srfP->header);

    for (i = 0; i < srfP->header.img_cnt; ++i) {
        if (!writeImg(ofP, i, &srfP->imgs[i]))
            pm_error("invalid srf image %u", i);
        padLen += lenImg(&srfP->imgs[i]);
    }

    /* Pad to 256 bytes */
    padLen = 256 - (padLen % 256);
    if (padLen) {
        char * d;
        size_t bytesWritten;

        MALLOCARRAY(d, padLen);

        if (!d)
            pm_error("Could not allocate memory for %u bytes of padding",
                     (unsigned)padLen);

        memset(d, 0xff, padLen);

        bytesWritten = fwrite(d, 1, padLen, ofP);

        if (bytesWritten != padLen)
            pm_error("unable to 0xff pad file");

        free(d);
    }

    /* Write out checksum byte */
    srfCsum = 0xff - csum(srfP, padLen) + 1;
    bytesWritten = fwrite(&srfCsum, 1, 1, ofP);
    if (bytesWritten != 1)
        pm_error("unable to write checksum");
}
Example #17
0
File: icmp.c Project: OPSF/uClinux
static void icmpcsum(sendip_data *icmp_hdr, sendip_data *data) {
	icmp_header *icp = (icmp_header *)icmp_hdr->data;
	u_int16_t *buf = malloc(icmp_hdr->alloc_len+data->alloc_len);
	u_int8_t *tempbuf = (u_int8_t *)buf;
	icp->check = 0;
	if(tempbuf == NULL) {
		fprintf(stderr,"Out of memory: ICMP checksum not computed\n");
		return;
	}
	memcpy(tempbuf,icmp_hdr->data,icmp_hdr->alloc_len);
	memcpy(tempbuf+icmp_hdr->alloc_len,data->data,data->alloc_len);
	icp->check = csum(buf,icmp_hdr->alloc_len+data->alloc_len);
	free(buf);
}
Example #18
0
bool icmpv4_write_checksum(uint8_t * icmpv4_segment, buffer_t * ipv4_psh)
{
    struct icmphdr * icmpv4_header = (struct icmphdr *) icmpv4_segment;

    // No pseudo header not required in ICMPv4
    if (ipv4_psh) {
        errno = EINVAL;
        return false;
    }

    // The ICMPv4 checksum must be set to 0 before its calculation
    icmpv4_header->checksum = 0;
    icmpv4_header->checksum = csum((uint16_t *) icmpv4_segment, sizeof(struct icmphdr));
    return true;
}
Example #19
0
void eeprom_save(void)
{
	struct eeprom_data e;

	e.main_pwm[0] = main_pwm[0];
	e.main_pwm[1] = main_pwm[1];
	e.main_pwm[2] = main_pwm[2];

	e.usart_pwm = usart_pwm;

	uint8_t wcsum = csum( (void *)&e, sizeof(e) );

	EEPROM_write_block( 1, (void *)&e, sizeof(e) );
	EEPROM_write( 0, wcsum );

}
static int udp_error(struct sk_buff *skb, unsigned int dataoff,
		     enum ip_conntrack_info *ctinfo,
		     int pf,
		     unsigned int hooknum,
		     int (*csum)(const struct sk_buff *, unsigned int))
{
	unsigned int udplen = skb->len - dataoff;
	struct udphdr _hdr, *hdr;

	/* Header is too small? */
	hdr = skb_header_pointer(skb, dataoff, sizeof(_hdr), &_hdr);
	if (hdr == NULL) {
		if (LOG_INVALID(IPPROTO_UDP))
			nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
				      "nf_ct_udp: short packet ");
		return -NF_ACCEPT;
	}

	/* Truncated/malformed packets */
	if (ntohs(hdr->len) > udplen || ntohs(hdr->len) < sizeof(*hdr)) {
		if (LOG_INVALID(IPPROTO_UDP))
			nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
				"nf_ct_udp: truncated/malformed packet ");
		return -NF_ACCEPT;
	}

	/* Packet with no checksum */
	if (!hdr->check)
		return NF_ACCEPT;

	/* Checksum invalid? Ignore.
	 * We skip checking packets on the outgoing path
	 * because the semantic of CHECKSUM_HW is different there
	 * and moreover root might send raw packets.
	 * FIXME: Source route IP option packets --RR */
	if (((pf == PF_INET && hooknum == NF_IP_PRE_ROUTING) ||
	     (pf == PF_INET6 && hooknum == NF_IP6_PRE_ROUTING))
	    && skb->ip_summed != CHECKSUM_UNNECESSARY
	    && csum(skb, dataoff)) {
		if (LOG_INVALID(IPPROTO_UDP))
			nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
				"nf_ct_udp: bad UDP checksum ");
		return -NF_ACCEPT;
	}

	return NF_ACCEPT;
}
Example #21
0
void eeprom_load(void)
{
	struct eeprom_data e;

	EEPROM_read_block( 1, (void *)&e, sizeof(e) );
	uint8_t rcsum = EEPROM_read( 0 );

	uint8_t ccsum = csum( (void *)&e, sizeof(e) );

	if( rcsum != ccsum )
		return;

	main_pwm[0] = e.main_pwm[0];
	main_pwm[1] = e.main_pwm[1];
	main_pwm[2] = e.main_pwm[2];

	usart_pwm = e.usart_pwm;
}
Example #22
0
void
srf_read(FILE *       const ifP,
         bool         const verbose,
         struct srf * const srfP) {

    uint8_t       trialCsum;
    size_t        padLen;
    unsigned char pad[256];
    unsigned int  i;

    if (!readHeader(ifP, &srfP->header))
        pm_error("short srf header");
    if (!checkHeader(&srfP->header))
        pm_error("invalid srf header");

    if (verbose)
        pm_message("reading srf ver %s with prod code %s and %u images",
                   srfP->header.ver.val, srfP->header.prod.val,
                   srfP->header.img_cnt);

    MALLOCARRAY(srfP->imgs, srfP->header.img_cnt);

    if (!srfP->imgs)
        pm_error("Could not allocate memory for %u images",
                 srfP->header.img_cnt);

    for (i = 0; i < srfP->header.img_cnt; ++i)
        if (!readImg(ifP, verbose, i, &srfP->imgs[i]))
            pm_error("invalid srf image %u", i);

    padLen = fread(pad, 1, sizeof(pad), ifP);
    if (!feof(ifP)) {
        pm_errormsg("excess data at end of file");
        return;
    }

    trialCsum = csum(srfP, 0);  /* initial value */
    for (i = 0; i < padLen; ++i)
        trialCsum += pad[i];
    if (trialCsum != 0)
        pm_errormsg("checksum does not match");
}
Example #23
0
static
f_pixel averagepixels(
	uint clrs,
	const hist_item achv[],
	double min_opaque_val
	)
{
	f_pixel csum(0,0,0,0);
	double sum = 0.0;
	double maxa = 0.0;
	for (uint i=0; i<clrs; ++i) {
		double weight = 1.0;
		const hist_item& hist = achv[i];
		const f_pixel px = hist.acolor;
		/* give more weight to colors that are further away from average
		 this is intended to prevent desaturation of images and fading of whites
		 */
		f_pixel tmp = f_pixel(0.5, 0.5, 0.5, 0.5) - px;
		tmp.square();
		weight += tmp.r + tmp.g + tmp.b;
		weight *= hist.adjusted_weight;
		sum += weight;
		csum += px * weight;
		
		/* find if there are opaque colors, in case we're supposed to preserve opacity exactly (ie_bug) */
		maxa = max(maxa, px.alpha);
	}
	
	/* Colors are in premultiplied alpha colorspace, so they'll blend OK
	 even if different opacities were mixed together */
	if (!sum) sum = 1.0;
	csum /= sum;

	assert(!isnan(csum.r) && !isnan(csum.g) && !isnan(csum.b) && !isnan(csum.alpha));
	
	/** if there was at least one completely opaque color, "round" final color to opaque */
	if (csum.alpha >= min_opaque_val && maxa >= (255.0/256.0)) csum.alpha = 1.0;
	
	return csum;
}
Example #24
0
//int Connect(e){
// return sockfd
int Connect(char* tgt_ip_addr, int portNum){
	destPort = portNum;	
	srand((unsigned)time(NULL));
	srcPort = 1000 + rand()%63535;
	sock2send = createRaw(IPPROTO_RAW);
	sock2recv = createRaw(IPPROTO_TCP);
	char **pptr = NULL;
	unsigned int OPTION_SIZE = 20;
	memset(datagram,0,4096);
	iph = (struct iphdr *) datagram;
	tcph = (struct TCP_header *) (datagram + sizeof(struct ip));
	struct hostent *host = NULL;

	buf = malloc(1024);
	send_addr.sin_family = AF_INET;
	send_addr.sin_port = htons(destPort);
	send_addr.sin_addr.s_addr = inet_addr(tgt_ip_addr);
	look_for_local_ip(srcaddr);
	printf("Local IP Address:\t%s\n",srcaddr); 
	// ip headG
	iph->ihl = 5;
	iph->version = 4;
	iph->tos = 0;
	iph->tot_len = sizeof(struct iphdr) + sizeof(struct TCP_header);
	iph->id = htonl(54321);
	iph->frag_off = 0;
	iph->ttl = 60;
	iph->protocol = IPPROTO_TCP;
	iph->check = 0;
	iph->saddr = inet_addr(srcaddr);
	iph->daddr = send_addr.sin_addr.s_addr;
	iph->check = csum((unsigned short*)datagram, iph->tot_len);
	three_hand_shake(sock2send,sock2recv,datagram,send_addr);

 return sock2recv;
}
Example #25
0
int UdpSocket::s_send(char* data,int size,in_addr_t srcip,int srcport,in_addr_t dstip,int dstport)
{
	int ret=0;
	int allsize=sizeof(struct udphdr)+size;
	char* datagram=new char[allsize];
	struct udphdr *udph;
	memset(datagram, 0, allsize);
	memcpy(datagram + sizeof(struct udphdr),data,size);
	udph = (struct udphdr *)(datagram);
	udph->source = htons(srcport);
	udph->dest = htons(dstport);
	udph->len = htons(sizeof(struct udphdr) + size);
	udph->check = 0;
	struct pseudo_header psh;
	psh.source_address = srcip;
	psh.dest_address = dstip;
	psh.placeholder = 0;
	psh.protocol = IPPROTO_UDP;
	psh.length = htons(allsize);
	int psize=sizeof(struct pseudo_header)+allsize;
	char* pseudogram = (char*)malloc(psize);
	memcpy(pseudogram , (char*) &psh , sizeof(struct pseudo_header));
	memcpy(pseudogram + sizeof(struct pseudo_header) , udph , allsize);
	udph->check = csum((unsigned short*) pseudogram ,psize);
	printf("SEND_UDP (%d):\n",allsize);

	for(const char* p = datagram; p<(datagram+allsize); ++p)
	{
		printf("%02X ", (char)*p);
	}

	printf("\n");
	ret=IpSocket::s_send(datagram,allsize,TYPE_UDP,srcip,dstip);
	delete[] datagram;
	return ret;
}
Example #26
0
int recv_message(int socket, char** buffer) {
  char size[6]; // we allow 4 hex bytes for size; this allows messages to be at
                // most 65536 bytes in length
  int res, length, sum;

  res = recv_string(socket,size,5);
  if (res!=6) {
    printf("only recv'd %d hex digits\n", res);
    return -1;
  }

  res = htoi(size, &sum); // parse the hex digits
  if (!(res==6)) {
    printf("only parsed %d hex digits in \"%s\"\n", res, size);
    return -1;
  }

  // now, noting that a hex digit is 4 bits, we can use bit ops instead of
  // string ones:
  length = sum >> 8; // drop the two characters off the right hand side
  sum = sum - (length << 8); // leave only the last two in sum

  *buffer = (char*) malloc((length+2)*sizeof(char));

  res = recv_string(socket, *buffer, length);
  if (!(length == res)) {
    printf("message had length %d, but said it was %d\n", res, length);
    return -1;
  }
  if (!((res = csum(*buffer)) == sum)) {
    printf("\"%s\" had checksum %x, but said it was %x\n", *buffer, res, sum);
    return -1;
  }

  return length;
}
Example #27
0
static void ipcsum(sendip_data *ip_hdr) {
	ip_header *ip = (ip_header *)ip_hdr->data;
	ip->check=0;
	ip->check=csum((u_int16_t *)ip_hdr->data, ip_hdr->alloc_len);
}
Example #28
0
int
main(void)
{
    const struct test_case *tc;
    int i;

    for (tc = test_cases; tc < &test_cases[ARRAY_SIZE(test_cases)]; tc++) {
        const uint16_t *data16 = (const uint16_t *) tc->data;
        const uint32_t *data32 = (const uint32_t *) tc->data;
        uint32_t partial;
        size_t i;

        /* Test csum(). */
        assert(ntohs(csum(tc->data, tc->size)) == tc->csum);
        mark('.');

        /* Test csum_add16(). */
        partial = 0;
        for (i = 0; i < tc->size / 2; i++) {
            partial = csum_add16(partial, data16[i]);
        }
        assert(ntohs(csum_finish(partial)) == tc->csum);
        mark('.');

        /* Test csum_add32(). */
        partial = 0;
        for (i = 0; i < tc->size / 4; i++) {
            partial = csum_add32(partial, data32[i]);
        }
        assert(ntohs(csum_finish(partial)) == tc->csum);
        mark('.');

        /* Test alternating csum_add16() and csum_add32(). */
        partial = 0;
        for (i = 0; i < tc->size / 4; i++) {
            if (i % 2) {
                partial = csum_add32(partial, data32[i]);
            } else {
                partial = csum_add16(partial, data16[i * 2]);
                partial = csum_add16(partial, data16[i * 2 + 1]);
            }
        }
        assert(ntohs(csum_finish(partial)) == tc->csum);
        mark('.');

        /* Test csum_continue(). */
        partial = 0;
        for (i = 0; i < tc->size / 4; i++) {
            if (i) {
                partial = csum_continue(partial, &data32[i], 4);
            } else {
                partial = csum_continue(partial, &data16[i * 2], 2);
                partial = csum_continue(partial, &data16[i * 2 + 1], 2);
            }
        }
        assert(ntohs(csum_finish(partial)) == tc->csum);
        mark('#');
    }

    test_rfc1624();

    /* Test recalc_csum16(). */
    for (i = 0; i < 32; i++) {
        uint16_t old_u16, new_u16;
        uint16_t old_csum;
        uint16_t data[16];
        int j, index;

        for (j = 0; j < ARRAY_SIZE(data); j++) {
            data[j] = random_uint32();
        }
        old_csum = csum(data, sizeof data);
        index = random_range(ARRAY_SIZE(data));
        old_u16 = data[index];
        new_u16 = data[index] = random_uint32();
        assert(csum(data, sizeof data)
               == recalc_csum16(old_csum, old_u16, new_u16));
        mark('.');
    }
    mark('#');

    /* Test recalc_csum32(). */
    for (i = 0; i < 32; i++) {
        uint32_t old_u32, new_u32;
        uint16_t old_csum;
        uint32_t data[16];
        int j, index;

        for (j = 0; j < ARRAY_SIZE(data); j++) {
            data[j] = random_uint32();
        }
        old_csum = csum(data, sizeof data);
        index = random_range(ARRAY_SIZE(data));
        old_u32 = data[index];
        new_u32 = data[index] = random_uint32();
        assert(csum(data, sizeof data)
               == recalc_csum32(old_csum, old_u32, new_u32));
        mark('.');
    }
    mark('#');

    putchar('\n');

    return 0;
}
Example #29
0
/* Puts into 'b' a packet that flow_extract() would parse as having the given
 * 'flow'.
 *
 * (This is useful only for testing, obviously, and the packet isn't really
 * valid. It hasn't got some checksums filled in, for one, and lots of fields
 * are just zeroed.) */
void
flow_compose(struct ofpbuf *b, const struct flow *flow)
{
    eth_compose(b, flow->dl_dst, flow->dl_src, ntohs(flow->dl_type), 0);
    if (flow->dl_type == htons(FLOW_DL_TYPE_NONE)) {
        struct eth_header *eth = b->l2;
        eth->eth_type = htons(b->size);
        return;
    }

    if (flow->vlan_tci & htons(VLAN_CFI)) {
        eth_push_vlan(b, flow->vlan_tci);
    }

    if (flow->dl_type == htons(ETH_TYPE_IP)) {
        struct ip_header *ip;

        b->l3 = ip = ofpbuf_put_zeros(b, sizeof *ip);
        ip->ip_ihl_ver = IP_IHL_VER(5, 4);
        ip->ip_tos = flow->nw_tos;
        ip->ip_ttl = flow->nw_ttl;
        ip->ip_proto = flow->nw_proto;
        put_16aligned_be32(&ip->ip_src, flow->nw_src);
        put_16aligned_be32(&ip->ip_dst, flow->nw_dst);

        if (flow->nw_frag & FLOW_NW_FRAG_ANY) {
            ip->ip_frag_off |= htons(IP_MORE_FRAGMENTS);
            if (flow->nw_frag & FLOW_NW_FRAG_LATER) {
                ip->ip_frag_off |= htons(100);
            }
        }
        if (!(flow->nw_frag & FLOW_NW_FRAG_ANY)
            || !(flow->nw_frag & FLOW_NW_FRAG_LATER)) {
            if (flow->nw_proto == IPPROTO_TCP) {
                struct tcp_header *tcp;

                b->l4 = tcp = ofpbuf_put_zeros(b, sizeof *tcp);
                tcp->tcp_src = flow->tp_src;
                tcp->tcp_dst = flow->tp_dst;
                tcp->tcp_ctl = TCP_CTL(0, 5);
            } else if (flow->nw_proto == IPPROTO_UDP) {
                struct udp_header *udp;

                b->l4 = udp = ofpbuf_put_zeros(b, sizeof *udp);
                udp->udp_src = flow->tp_src;
                udp->udp_dst = flow->tp_dst;
            } else if (flow->nw_proto == IPPROTO_SCTP) {
                struct sctp_header *sctp;

                b->l4 = sctp = ofpbuf_put_zeros(b, sizeof *sctp);
                sctp->sctp_src = flow->tp_src;
                sctp->sctp_dst = flow->tp_dst;
            } else if (flow->nw_proto == IPPROTO_ICMP) {
                struct icmp_header *icmp;

                b->l4 = icmp = ofpbuf_put_zeros(b, sizeof *icmp);
                icmp->icmp_type = ntohs(flow->tp_src);
                icmp->icmp_code = ntohs(flow->tp_dst);
                icmp->icmp_csum = csum(icmp, ICMP_HEADER_LEN);
            }
        }

        ip = b->l3;
        ip->ip_tot_len = htons((uint8_t *) b->data + b->size
                               - (uint8_t *) b->l3);
        ip->ip_csum = csum(ip, sizeof *ip);
    } else if (flow->dl_type == htons(ETH_TYPE_IPV6)) {
        /* XXX */
    } else if (flow->dl_type == htons(ETH_TYPE_ARP) ||
               flow->dl_type == htons(ETH_TYPE_RARP)) {
        struct arp_eth_header *arp;

        b->l3 = arp = ofpbuf_put_zeros(b, sizeof *arp);
        arp->ar_hrd = htons(1);
        arp->ar_pro = htons(ETH_TYPE_IP);
        arp->ar_hln = ETH_ADDR_LEN;
        arp->ar_pln = 4;
        arp->ar_op = htons(flow->nw_proto);

        if (flow->nw_proto == ARP_OP_REQUEST ||
            flow->nw_proto == ARP_OP_REPLY) {
            put_16aligned_be32(&arp->ar_spa, flow->nw_src);
            put_16aligned_be32(&arp->ar_tpa, flow->nw_dst);
            memcpy(arp->ar_sha, flow->arp_sha, ETH_ADDR_LEN);
            memcpy(arp->ar_tha, flow->arp_tha, ETH_ADDR_LEN);
        }
    }

    if (eth_type_mpls(flow->dl_type)) {
        b->l2_5 = b->l3;
        push_mpls(b, flow->dl_type, flow->mpls_lse);
    }
}
Example #30
0
void solve()
{       struct poly *d;
	float i=0,u=0 ,a,tm=0 ;
	float sum=0,sud=0,t=0,c=1,pr;
	int choice ;
	printf("Select your choice for calculation :\n") ;
	printf("1.Automatic :\n");
	printf("2.Manually :");
	scanf("%d",&choice);
	switch(choice)
	{  case 1:

			for(i=0;;i=i+c)
			{     //  temp=start;
			//	sum = 0;
				sum = csum(i,start) ;
				printf("\nfor x=%.0f SUM is:%.4f",i,sum) ;

				if(sum<0)
				{  if(sum<t)
					{ c=1;		}
					if(t>0)
					{ break;}
				}
				else if(sum>0)
				{  if(sum>t)
					{ c=-1;		}
				   if(t<0)
				   { break;}
				}
				else
				 { break ;}
				if(i<-300||i>300)
				{ printf("\n\n!!!!Out of range!!!!")  ;
					exit(0); }
				t=sum  ;
			}
			if(sum==0)
			{  printf("\n\nRoot is :%.0f",i);
				goto tag;
			}
			else{
				if(u<i)
				{  u=i;
				   i=i+c;
				}
				else
				{  u=i+c;
				}
			} break;
	case 2:
		 printf("\nEnter the range :\n");
		 printf("Enter the limit 1:");
		 scanf("%f",&u);
		 printf("Enter the limit 2:");
		scanf("%f",&i);

			if(u<i)
		{        c=u;
			u=i;
			i=c;
		}
     }

	  printf("\n\nRange %.0f",i);
	  printf("<->%.0f\n",u) ;
	   c=i+u;
	   c=c/2;
	  temp = start;
	  d = diff(temp);
	  printf("\nf'(x) :");
	  display(d) ;

	do
	{ tm++;
	 pr = c;
	  sum=csum(c,start);
	  sud=csum(c,d);
	  c = c - (sum/sud);
	 //if((c-pr))0.0001)
	 // {break;}
	 }while((pr-c)>0.0001||(pr-c)<-0.0001);
	    printf("\n\nRoot is:%f",c) ;
	  tag:

}

float csum(float i,struct poly *temp)
{       float sum=0,a=0,po=0;
	for(;temp!=NULL;)
		{  if(((i==0)||(temp->co==0))&&(temp->power!=0))
		  { a=0;
		  }
		   else
		   {    if(temp->power==0)
			{po=1;
				a = (temp->co)*po;
				   sum = sum + a ;
				   break;
			}
			else
			{po  = pow(i,(temp->power)) ;}
			a = (temp->co)*po;
		   }

		    sum = sum + a ;
		    temp=temp->link;
		 //  printf("\n%f",a) ;
		 //  printf("\n%f",po) ;
		}




	 return sum;
}