Пример #1
0
/** check EDNS at this IP and port */
static int
check_edns_ip(char* ip, int port, int info)
{
	struct sockaddr_storage addr;
	socklen_t len = 0;
	uint8_t* wire;
	size_t wlen;
	memset(&addr, 0, sizeof(addr));
	if(verb) printf("%s ", ip);
	if(!convert_addr(ip, port, &addr, &len))
		return 2;
	/* try to send 3 times to the IP address, test root key */
	if(!get_packet(&addr, len, ".", LDNS_RR_TYPE_DNSKEY, &wire, &wlen))
		return 2;
	if(!check_packet(wire, wlen, LDNS_RR_TYPE_DNSKEY))
		return 1;
	/* check support for caching type DS for chains of trust */
	if(!get_packet(&addr, len, "se.", LDNS_RR_TYPE_DS, &wire, &wlen))
		return 2;
	if(!check_packet(wire, wlen, LDNS_RR_TYPE_DS))
		return 1;
	if(verb) printf("OK\n");
	if(info) printf(" %s", ip);
	return 0;
}
Пример #2
0
int main (int argc, char ** argv){
	int i;
	signal(SIGINT, sigint_handler);
	
	if (open_log_file() != 0) {
		printf("Error opening log file\n");
		return -1;
	}

	if(create_db_comm() <0){
		LOG_MESSAGE("could not create db comm\n");
		return -1;
	}

	if(create_hist_comm() <0){
		LOG_MESSAGE("could not create hist comm\n");
		finish_with_error(con);
		return -1;
	}
	
	while(running){
		check_packet();
	}
	LOG_MESSAGE("Total Receive %d - A:%d   D:%d   E:%d (%d) | Error: %d\n", (digital_msgs+analog_msgs+events_msgs),
			analog_msgs, digital_msgs, events_msgs, should_be_type_30, error_msgs);

	close(hist_socket_receive);
	mysql_close(con);
	return 0;
}
Пример #3
0
MCSPacket *mcs_create_packet_with_dest(MCSCommand cmd, char *dest,
                            unsigned short nargs, unsigned char *args,
                            unsigned short data_size, unsigned char *data)
{
    MCSPacket *pkt;

    pkt = abs_malloc0(sizeof(*pkt));
    pkt->id = generate_id();
    pkt->type = (cmd & 0xF0000) >> 16;
    pkt->cmd = cmd & 0xFFFF;
    pkt->dest = dest;
    pkt->nargs = nargs;
    if(nargs != 0) {
        pkt->args = abs_malloccpy(args, nargs);
    }
    pkt->data_size = data_size;
    if(data_size != 0) {
        pkt->data = abs_malloccpy(data, data_size);
    }

    if(check_packet(pkt) >= 0) {
        return pkt;
    } else {
        return NULL;
    }
}
Пример #4
0
// this has its parallell in exe$alonpagvar
int exe$allocate_pool(int requestsize, int pooltype, int alignment, unsigned int * allocatedsize, void ** returnblock)
{
    int reqsize=requestsize;
    unsigned int * alosize_p=allocatedsize;
    void ** pool_p=returnblock;
    int sts=SS$_NORMAL;

    // extra from alononpaged
    if (reqsize&63)
        reqsize=((reqsize>>6)+1)<<6; // mm book said something about align 64

    *alosize_p=reqsize;

    struct _npool_data * pooldata = exe$gs_bap_npool;
    struct _lsthds * lsthd = pooldata->npool$ar_lsthds;
    struct _myhead * array = &lsthd->lsthds$q_listheads;

    if (reqsize<=8192)
    {
        *pool_p = exe$lal_remove_first(&array[reqsize>>6]);
        if (*pool_p)
        {
            check_packet(*pool_p,reqsize,0);
#if 0
            poison_packet(*pool_p,reqsize,0);
#endif
        }
    }
Пример #5
0
//----------------------------------------------------------------------------
//ETH get data
void eth_get_data (void)
{ 	
	if(eth.timer)
	{
		tcp_timer_call();
		arp_timer_call();
		eth.timer = 0;
	}	
	if(eth.data_present)
	{
		while( (PINB &(1<<PB2)) == 0)
		{	
				unsigned int packet_lenght;
				  
				packet_lenght = ETH_PACKET_RECEIVE(MTU_SIZE,eth_buffer);
				/*Wenn ein Packet angekommen ist, ist packet_lenght =! 0*/
				packet_lenght = packet_lenght - 4;
				eth_buffer[packet_lenght+1] = 0;
				check_packet();
		}
		eth.data_present = 0;
		ETH_INT_ENABLE;
	}
	return;
}
Пример #6
0
/*
 *	Handle a BOOTP received packet.
 */
static void bootp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
			  unsigned src, unsigned len)
{
	struct bootp_hdr *bp;

	debug("got BOOTP packet (src=%d, dst=%d, len=%d want_len=%zu)\n",
	      src, dest, len, sizeof(struct bootp_hdr));

	bp = (struct bootp_hdr *)pkt;

	/* Filter out pkts we don't want */
	if (check_packet(pkt, dest, src, len))
		return;

	/*
	 *	Got a good BOOTP reply.	 Copy the data into our variables.
	 */
#ifdef CONFIG_STATUS_LED
	status_led_set(STATUS_LED_BOOT, STATUS_LED_OFF);
#endif

	store_net_params(bp);		/* Store net parameters from reply */

	/* Retrieve extended information (we must parse the vendor area) */
	if (net_read_u32((u32 *)&bp->bp_vend[0]) == htonl(BOOTP_VENDOR_MAGIC))
		bootp_process_vendor((uchar *)&bp->bp_vend[4], len);

	net_set_timeout_handler(0, (thand_f *)0);
	bootstage_mark_name(BOOTSTAGE_ID_BOOTP_STOP, "bootp_stop");

	debug("Got good BOOTP\n");

	net_auto_load();
}
Пример #7
0
Файл: mux.c Проект: pigoz/libav
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
{
    int ret;

    ret = check_packet(s, pkt);
    if (ret < 0)
        return ret;

    if (!pkt) {
        if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
            return s->oformat->write_packet(s, pkt);
        return 1;
    }

    ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);

    if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
        return ret;

    ret = write_packet(s, pkt);

    if (ret >= 0)
        s->streams[pkt->stream_index]->nb_frames++;
    return ret;
}
void
test_ofp_bucket_counter_list_encode_bucket_counter_list_empty(void) {
  lagopus_result_t ret;

  bucket_cnt_num = 0;
  ret = check_packet(ofp_bucket_counter_list_encode_wrap,
                     "");
  TEST_ASSERT_EQUAL_MESSAGE(LAGOPUS_RESULT_OK, ret,
                            "ofp_bucket_counter_list_encode(bucket_counter_list empty) error.");
}
/**
* Sends a two part command to the device.
* @param opcode contains the opcode to send.
* @param operand contains the operand to send.
*/
static void send_2part_command(unsigned opcode, unsigned operand)
{
	non_zero_bit_scan_sequence(opcode);
	non_zero_bit_scan_sequence(operand);

	/* If we are currently in oscan1 mode... */
	if (tycJtagScanFormat == oscan1) {
		/* ...send a checkpacket. */
		check_packet();
	}
}
/**
*  Enters oscan1 mode.
*/
static void enter_oscan1(void)
{
	/* Enter the command STFMT MODE
	   where :
	   parameter STFMT    = 5'h03;  Store Format
	   parameter TAP7_OSCAN1 = 5'h9; */
	send_2part_command(STFMT,OSCAN1);
	/* After the command, must send a check packet */
	check_packet();
	/* Now in oscan1.  Port must know this. */
	set_format(oscan1);
}
Пример #11
0
int exe_std$alononpaged (int reqsize, int *alosize_p, void **pool_p)
{
    int sts=SS$_NORMAL;
#if 0
    if (reqsize<=srpsize)
    {
        if (rqempty(&ioc$gq_srpiq))
            goto var;
        int addr=remqti(&ioc$gq_srpiq,addr);
        *alosize_p=reqsize;
        *pool_p=addr;
        return sts;
    }
    if (reqsize<=irpsize)
    {
        if (rqempty(&ioc$gq_irpiq))
            goto var;
        int addr=remqti(&ioc$gq_irpiq,addr);
        *alosize_p=reqsize;
        *pool_p=addr;
        return sts;
    }
    if (reqsize >= lrpmin && reqsize<=srpsize)
    {
        if (rqempty(&ioc$gq_lrpiq))
            goto var;
        int addr=remqti(&ioc$gq_srpiq,addr);
        *alosize_p=reqsize;
        *pool_p=addr;
        return sts;
    }
#endif
    if (reqsize&63)
        reqsize=((reqsize>>6)+1)<<6; // mm book said something about align 64

    *alosize_p=reqsize;

    struct _npool_data * pooldata = exe$gs_npp_npool;
    struct _lsthds * lsthd = pooldata->npool$ar_lsthds;
    struct _myhead * array = &lsthd->lsthds$q_listheads;

    if (reqsize<=8192)
    {
        *pool_p = exe$lal_remove_first(&array[reqsize>>6]);
        if (*pool_p)
        {
            check_packet(*pool_p,reqsize,0);
#if 0
            poison_packet(*pool_p,reqsize,0);
#endif
        }
    }
Пример #12
0
void
test_ofp_bucket_counter_list_encode(void) {
  lagopus_result_t ret;

  bucket_cnt_num = 2;
  ret = check_packet(ofp_bucket_counter_list_encode_wrap,
                     "00 00 00 00 00 00 00 01"
                     "00 00 00 00 00 00 00 02"
                     "00 00 00 00 00 00 00 02"
                     "00 00 00 00 00 00 00 03");
  TEST_ASSERT_EQUAL_MESSAGE(LAGOPUS_RESULT_OK, ret,
                            "ofp_bucket_counter_list_encode(normal) error.");
}
Пример #13
0
static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
{
    int ret;

    ret = check_packet(s, pkt);
    if (ret < 0)
        return ret;

#if !FF_API_COMPUTE_PKT_FIELDS2
    /* sanitize the timestamps */
    if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
        AVStream *st = s->streams[pkt->stream_index];

        /* when there is no reordering (so dts is equal to pts), but
         * only one of them is set, set the other as well */
        if (!st->internal->reorder) {
            if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
                pkt->pts = pkt->dts;
            if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
                pkt->dts = pkt->pts;
        }

        /* check that the timestamps are set */
        if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
            av_log(s, AV_LOG_ERROR,
                   "Timestamps are unset in a packet for stream %d\n", st->index);
            return AVERROR(EINVAL);
        }

        /* check that the dts are increasing (or at least non-decreasing,
         * if the format allows it */
        if (st->cur_dts != AV_NOPTS_VALUE &&
            ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
             st->cur_dts > pkt->dts)) {
            av_log(s, AV_LOG_ERROR,
                   "Application provided invalid, non monotonically increasing "
                   "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
                   st->index, st->cur_dts, pkt->dts);
            return AVERROR(EINVAL);
        }

        if (pkt->pts < pkt->dts) {
            av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
                   pkt->pts, pkt->dts, st->index);
            return AVERROR(EINVAL);
        }
    }
#endif

    return 0;
}
Пример #14
0
Файл: mux.c Проект: pigoz/libav
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
{
    int ret, flush = 0;

    ret = check_packet(s, pkt);
    if (ret < 0)
        goto fail;

    if (pkt) {
        AVStream *st = s->streams[pkt->stream_index];

        av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
                pkt->size, pkt->dts, pkt->pts);
        if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
            goto fail;

        if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
            ret = AVERROR(EINVAL);
            goto fail;
        }
    } else {
        av_dlog(s, "av_interleaved_write_frame FLUSH\n");
        flush = 1;
    }

    for (;; ) {
        AVPacket opkt;
        int ret = interleave_packet(s, &opkt, pkt, flush);
        if (pkt) {
            memset(pkt, 0, sizeof(*pkt));
            av_init_packet(pkt);
            pkt = NULL;
        }
        if (ret <= 0) //FIXME cleanup needed for ret<0 ?
            return ret;

        ret = write_packet(s, &opkt);
        if (ret >= 0)
            s->streams[opkt.stream_index]->nb_frames++;

        av_free_packet(&opkt);

        if (ret < 0)
            return ret;
    }
fail:
    av_packet_unref(pkt);
    return ret;
}
Пример #15
0
//----------------------------------------------------------------------------
//ETH get data
void eth_get_data (void)
{
	unsigned int packet_lenght;

	packet_lenght = ETH_PACKET_RECEIVE(MTU_SIZE,eth_buffer);
	/*Wenn ein Packet angekommen ist, ist packet_lenght =! 0*/
	if(packet_lenght > 0)
	{
		packet_lenght = packet_lenght - 4;
		eth_buffer[packet_lenght+1] = 0;
		eth_len = packet_lenght;			// remember length for global access
		check_packet();
	}


}
Пример #16
0
void dhcp_ack()
{
	if (next_state != ACK) {
		fprintf(err, "State is not ACK!\n");
		return;
	}
	
	struct dhcp_packet *packet = malloc(sizeof(struct dhcp_packet));
	memset(packet, 0, sizeof(struct dhcp_packet));
	int valid = 0;
	while (!valid) {
		int len = recv_packet((char*)packet, sizeof(struct dhcp_packet));
		if (len < 0) {/* timeout */
			free_socket();
			if (timeout_count--) {
				next_state = REQUEST;
				dhcp_request();
				return;
			} else {
				if (renew) {
					fprintf(err, "Failed to renew, try to re-allocate\n");
					timeout_count = TIMEOUT_RETRY_TIMES;
					next_state = DISCOVER;
					dhcp_discover();
					return;
				} else {
					//fprintf(err, "give up...\n");
					//exit(0);
					fprintf(err, "Error in dhcp_ack, sleep 60s...\n");
					sleep(60);
					timeout_count = TIMEOUT_RETRY_TIMES;
					next_state = DISCOVER;
					dhcp_discover();
					return;
				}
			}
		}
		valid = check_packet(packet);
	}
	process_lease(&ack_lease, packet);
		
	free(packet);
	free_socket();
	
	configure_interface(&ack_lease);
}
Пример #17
0
json_t* send_users_logout(char *url, char* session){
  json_t *root, *json_status;
  json_error_t error;

  char *query = (char*)malloc(1024*sizeof(char));
  strcpy(query,"query={\"session\":\"");
  strcat(query,session);
  strcat(query, "\",\"cmd\":\"users/logout\"}");

  char *response;
  response = curl_send_query(url, query);
  root = json_loads(response, 0, &error); 
  free(response);
  free(query);

  if (check_packet(root,__FUNCTION__)) return(root); else return NULL;
}
Пример #18
0
json_t* send_users_login(char *url, char *username, char *password){
  json_t *root;
  json_error_t error;

  char *query = (char*)malloc(1024*sizeof(char));
  strcpy(query, "query={\"cmd\":\"users/login\",\"params\":{\"device\":\"351863048093054\",\"passwd\":\"");
  strcat(query, password);
  strcat(query, "\",\"login\":\"");
  strcat(query,username);
  strcat(query, "\",\"version\":\"9.0.9\"}}");
  
  char *response;
  response = curl_send_query(url, query);
  root = json_loads(response, 0, &error); 
  free(response); 
  free(query);
  if (check_packet(root,__FUNCTION__)) return(root); else return NULL;
}
Пример #19
0
json_t* send_chats_get_all_unread_message(char *url, char* session){
  json_t *root, *json_status;
  json_error_t error;

  char *query = (char*)malloc(1024*sizeof(char));
  strcpy(query,"query={\"session\":\"");
  strcat(query,session);
  strcat(query,"\",\"gps\":{\"rssi\":99,\"long\":0.0,\"alt\":0.0,\"lat\":0.0,\"cell\":\"12345\"},");
  strcat(query, "\"cmd\":\"chats/get_all_unread_message\"");
  strcat(query, ",\"params\":{\"date\":\"2012-12-11 00:18:25 +0900\"}}");;

  char *response;
  response = curl_send_query(url, query);
  root = json_loads(response, 0, &error); 
  free(response);
  free(query);

  if (check_packet(root,__FUNCTION__)) return(root); else return NULL;
}
Пример #20
0
void dhcp_offer()
{
	if (next_state != OFFER) {
		fprintf(err, "State is not OFFER!\n");
		return;
	}
	
	struct dhcp_packet *packet = malloc(sizeof(struct dhcp_packet));
	memset(packet, 0, sizeof(struct dhcp_packet));
	int valid = 0;
	while (!valid) {
		int len = recv_packet((char*)packet, sizeof(struct dhcp_packet));
		if (len < 0) {/* timeout */
			free_socket();
			if (timeout_count--) {
				next_state = DISCOVER;
				dhcp_discover();
				return;
			} else {
				//fprintf(err, "give up...\n");
				//exit(0);
				fprintf(err, "Error in dhcp_offer, sleep 60s...\n");
				sleep(60);
				timeout_count = TIMEOUT_RETRY_TIMES;
				next_state = DISCOVER;
				dhcp_discover();
				return;
			}
		}
		valid = check_packet(packet);
	}
	process_lease(&offer_lease, packet);
		
	free(packet);
	free_socket();
	
	timeout_count = TIMEOUT_RETRY_TIMES;
	next_state = REQUEST;
	dhcp_request();
}
Пример #21
0
json_t* send_shift(char *url, char* session){
  json_t *root, *json_status;
  json_error_t error;

  char *query = (char*)malloc(1024*sizeof(char));
  strcpy(query,"query={\"session\":\"");
  strcat(query,session);
  strcat(query,"\",\"gps\":{\"rssi\":99,\"long\":0.0,\"alt\":0.0,\"lat\":0.0,\"cell\":\"12345\"}");
  strcat(query, ",\"cmd\":\"shift\"");
  strcat(query, ",\"params\":{\"status\":\"true\"}}");

  // {"session":"ALU609fvz6bUglQgb0ihoQGMOpy4tUu3","gps":{"rssi":99,"long":0,"alt":0,"lat":0,"cell":"131486"},"cmd":"shift","params":{"status":"true"}}

  char *response;
  // = (char*)malloc(10240*sizeof(char));
  response = curl_send_query(url, query);
  root = json_loads(response, 0, &error); 
  free(response); 
  free(query);

  if (check_packet(root,__FUNCTION__)) return(root); else return NULL;
}
Пример #22
0
json_t* send_event_list_light(char *url, char* session){
  json_t *root, *json_status;
  json_error_t error;

  char *query = (char*)malloc(1024*sizeof(char));
  strcpy(query,"query={\"session\":\"");
  strcat(query,session);
  strcat(query,"\",\"gps\":{\"rssi\":99,\"long\":0.0,\"alt\":0.0,\"lat\":0.0,\"cell\":\"12345\"},");
  strcat(query, "\"cmd\":\"events/list/light\"");
  strcat(query, ",\"params\":{\"date\":\"2012-12-11 00:18:25 +0900\"}}");

  //fprintf(stdout,"\n\n\n%s\n\n\n",query);
  //exit(0);


  char *response;
  response = curl_send_query(url, query);
  root = json_loads(response, 0, &error); 
  free(response);
  free(query);

  if (check_packet(root,__FUNCTION__)) return(root); else return NULL;
}
Пример #23
0
//----------------------------------------------------------------------------
//ETH get data
void eth_get_data (void)
{ 	
	if(eth.timer)
	{
		tcp_timer_call();
		arp_timer_call();
		eth.timer = 0;
	}	
	if(eth.data_present)
	{
	#if USE_ENC28J60
		while(ETH_INT_ACTIVE)
		{	
	#endif

	#if USE_RTL8019
		if ( (ReadRTL(RTL_ISR)&(1<<OVW)) != 0)
			{
			DEBUG ("Overrun!\n");
			}

		if ( (ReadRTL(RTL_ISR) & (1<<PRX)) != 0)
		{
			unsigned char ByteH = 0;
			unsigned char ByteL = 1;
		
			while (ByteL != ByteH) //(!= bedeutet ungleich)
			{	
	#endif	
				unsigned int packet_length;
				  
				packet_length = ETH_PACKET_RECEIVE(MTU_SIZE,eth_buffer);
				if(packet_length > 0)
				{
					eth_buffer[packet_length+1] = 0;
					check_packet();
				}
			
	#if USE_RTL8019
				//auslesen des Empfangsbuffer BNRY = CURR
				ByteL = ReadRTL(BNRY); //auslesen NIC Register bnry
				WriteRTL ( CR ,(1<<STA|1<<RD2|1<<PS0));
			
				ByteH = ReadRTL(CURR); //auslesen NIC Register curr
				WriteRTL ( CR ,(1<<STA|1<<RD2));
			}
	#endif
		}
	#if USE_RTL8019
		Networkcard_INT_RES();
		Networkcard_Start();
	#endif
		eth.data_present = 0;
		ETH_INT_ENABLE;
	}
	return;
}
//----------------------------------------------------------------------------
//Check Packet and call Stack for TCP or UDP
void check_packet (void)
{
    struct Ethernet_Header *ethernet;    //Pointer auf Ethernet_Header
    struct IP_Header       *ip;          //Pointer auf IP_Header
    struct TCP_Header      *tcp;         //Pointer auf TCP_Header
    struct ICMP_Header     *icmp;        //Pointer auf ICMP_Header

    ethernet = (struct Ethernet_Header *)&eth_buffer[ETHER_OFFSET];
    ip       = (struct IP_Header       *)&eth_buffer[IP_OFFSET];
    tcp      = (struct TCP_Header      *)&eth_buffer[TCP_OFFSET];
    icmp     = (struct ICMP_Header     *)&eth_buffer[ICMP_OFFSET];
    
    if(ethernet->EnetPacketType == HTONS(0x0806) )     //ARP
    {
        arp_reply(); // check arp packet request/reply
    }
    else
    {
        if( ethernet->EnetPacketType == HTONS(0x0800) )  // if IP
        {              
            if( ip->IP_Destaddr == *((unsigned long*)&myip[0]) )  // if my IP address 
            {
                arp_entry_add();  ///Refresh des ARP Eintrages
                if(ip->IP_Proto == PROT_ICMP)
                {
                    switch ( icmp->ICMP_Type )
                    {
                        case (8): //Ping reqest
                            icmp_send(ip->IP_Srcaddr,0,0,icmp->ICMP_SeqNum,icmp->ICMP_Id); 
                            break;
                            
                        case (0): //Ping reply
                            if ((*((unsigned long*)&ping.ip1[0])) == ip->IP_Srcaddr)
                            {
                                ping.result |= 0x01;
                            }
                            DEBUG("%i",    (ip->IP_Srcaddr&0x000000FF)     );
                            DEBUG(".%i",  ((ip->IP_Srcaddr&0x0000FF00)>>8 ));
                            DEBUG(".%i",  ((ip->IP_Srcaddr&0x00FF0000)>>16));
                            DEBUG(".%i :",((ip->IP_Srcaddr&0xFF000000)>>24));
                            break;
                    }
                    return;
                }
                else
                {
                    if( ip->IP_Proto == PROT_TCP ) tcp_socket_process();
                    if( ip->IP_Proto == PROT_UDP ) udp_socket_process();
                }
            }
            else
            if (ip->IP_Destaddr == (unsigned long)0xffffffff || ip->IP_Destaddr == *((unsigned long*)&broadcast_ip[0]) ) // if broadcast
            {
                if( ip->IP_Proto == PROT_UDP ) udp_socket_process();
            }
        }
Пример #24
0
int mcs_write_command(MCSPacket *pkt, int fd)
{
    size_t common_size, dest_size;
    size_t tot_size;
    char *raw, *raw_act;

    if(check_packet(pkt) < 0) {
        return EUNDEF;
    }

    common_size = sizeof(pkt->id) + sizeof(char);

    switch(pkt->type) {
        case MCS_TYPE_ERR:
            tot_size = common_size + pkt->data_size;
            raw = malloc(tot_size);
            memcpy(raw, (char *)&pkt->id, common_size);
            memcpy(raw + common_size, pkt->data, pkt->data_size);
            break;

        case MCS_TYPE_OK_DATA:
            tot_size = common_size + sizeof(pkt->data_size) + pkt->data_size;
            raw = malloc(tot_size);
            raw_act = raw;
            memcpy(raw_act, (char *)&pkt->id, common_size);
            raw_act += common_size;
            memcpy(raw_act, &pkt->data_size, sizeof(pkt->data_size));
            raw_act += sizeof(pkt->data_size);
            memcpy(raw_act, pkt->data, pkt->data_size);
            raw_act += pkt->data_size;

#ifdef DEBUG
            if((size_t)(raw_act - raw) != tot_size) {
                printf_dbg("Real size is not expected size\n");
                return EUNDEF;
            }
#endif

            break;

        case MCS_TYPE_OK:
            tot_size = common_size;
            raw = malloc(tot_size);
            memcpy(raw, (char *)&pkt->id, common_size);
            break;

        default:
            tot_size = common_size + sizeof(pkt->cmd) + pkt->nargs;

            if(pkt->dest != NULL) {
                tot_size += sizeof(unsigned char);
                tot_size += strlen(pkt->dest);
            }

            if(pkt->data_size != 0) {
                tot_size += sizeof(pkt->data_size) + pkt->data_size;
            }

            raw = malloc(tot_size);
            raw_act = raw;

            memcpy(raw_act, (char *)&pkt->id, common_size);
            raw_act += common_size;
            memcpy(raw_act, &pkt->cmd, sizeof(pkt->cmd));
            raw_act += sizeof(pkt->cmd);
            if(pkt->nargs != 0) {
                memcpy(raw_act, pkt->args, pkt->nargs);
                raw_act += pkt->nargs;
            }

            if(pkt->dest != NULL) {
                dest_size = strlen(pkt->dest);
                memcpy(raw_act, (unsigned char *)&dest_size,
                                                    sizeof(unsigned char));
                raw_act += sizeof(unsigned char);
                memcpy(raw_act, pkt->dest, dest_size);
                raw_act += dest_size;
            }

            if(pkt->data_size != 0) {
                memcpy(raw_act, &pkt->data_size, sizeof(pkt->data_size));
                raw_act += sizeof(pkt->data_size);
                memcpy(raw_act, pkt->data, pkt->data_size);
                raw_act += pkt->data_size;
            }

#ifdef DEBUG
            if((size_t)(raw_act - raw) != tot_size) {
                printf_dbg("Real size is not expected size\n");
                return EUNDEF;
            }
#endif
            break;
    }

    if(abs_write(fd, raw, tot_size) < (int)tot_size) {
        return EUNDEF;
    }

    free(raw);

    return 0;
}