示例#1
0
static void proc_sync_set_req(struct mcap_mcl *mcl, uint8_t *cmd, uint32_t len)
{
	mcap_md_sync_set_req *req;
	uint32_t sched_btclock, cur_btclock;
	uint16_t btres;
	uint8_t update;
	uint64_t timestamp;
	struct sync_set_data *set_data;
	int phase2_delay, ind_freq, when;

	if (len != sizeof(mcap_md_sync_set_req)) {
		send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE, 0, 0, 0);
		return;
	}

	req = (mcap_md_sync_set_req *) cmd;
	sched_btclock = ntohl(req->btclock);
	update = req->timestui;
	timestamp = ntoh64(req->timestst);

	if (sched_btclock != MCAP_BTCLOCK_IMMEDIATE &&
			!valid_btclock(sched_btclock)) {
		send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE, 0, 0, 0);
		return;
	}

	if (update > 1) {
		send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE, 0, 0, 0);
		return;
	}

	if (!mcl->csp->remote_caps) {
		/* Remote side did not ask our capabilities yet */
		send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE, 0, 0, 0);
		return;
	}

	if (!caps(mcl)) {
		send_sync_set_rsp(mcl, MCAP_UNSPECIFIED_ERROR, 0, 0, 0);
		return;
	}

	if (!read_btclock_retry(mcl, &cur_btclock, &btres)) {
		send_sync_set_rsp(mcl, MCAP_UNSPECIFIED_ERROR, 0, 0, 0);
		return;
	}

	if (sched_btclock == MCAP_BTCLOCK_IMMEDIATE)
		phase2_delay = 0;
	else {
		phase2_delay = btdiff(cur_btclock, sched_btclock);

		if (phase2_delay < 0) {
			/* can not reset in the past tense */
			send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE,
						0, 0, 0);
			return;
		}

		/* Convert to miliseconds */
		phase2_delay = bt2ms(phase2_delay);

		if (phase2_delay > 61*1000) {
			/* More than 60 seconds in the future */
			send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE,
						0, 0, 0);
			return;
		} else if (phase2_delay < caps(mcl)->latency / 1000) {
			/* Too fast for us to do in time */
			send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE,
						0, 0, 0);
			return;
		}
	}

	if (update) {
		/* Indication frequency: required accuracy divided by ours */
		/* Converted to milisseconds */
		ind_freq = (1000 * mcl->csp->rem_req_acc) / caps(mcl)->ts_acc;

		if (ind_freq < MAX(caps(mcl)->latency * 2 / 1000, 100)) {
			/* Too frequent, we can't handle */
			send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE,
						0, 0, 0);
			return;
		}

		DBG("CSP: indication every %dms", ind_freq);
	} else
		ind_freq = 0;

	if (mcl->csp->ind_timer) {
		/* Old indications are no longer sent */
		g_source_remove(mcl->csp->ind_timer);
		mcl->csp->ind_timer = 0;
	}

	if (!mcl->csp->set_data)
		mcl->csp->set_data = g_new0(struct sync_set_data, 1);

	set_data = (struct sync_set_data *) mcl->csp->set_data;

	set_data->update = update;
	set_data->sched_btclock = sched_btclock;
	set_data->timestamp = timestamp;
	set_data->ind_freq = ind_freq;
	set_data->role = get_btrole(mcl);

	/* TODO is there some way to schedule a call based directly on
	 * a BT clock value, instead of this estimation that uses
	 * the SO clock? */

	if (phase2_delay > 0) {
		when = phase2_delay + caps(mcl)->syncleadtime_ms;
		mcl->csp->set_timer = g_timeout_add(when,
						proc_sync_set_req_phase2,
						mcl);
	} else
		proc_sync_set_req_phase2(mcl);

	/* First indication is immediate */
	if (update)
		sync_send_indication(mcl);
}
ofl_err
ofl_structs_instructions_unpack(struct ofp_instruction *src, size_t *len, struct ofl_instruction_header **dst, struct ofl_exp *exp) {
    size_t ilen;
    struct ofl_instruction_header *inst = NULL;

    if (*len < sizeof(struct ofp_instruction)) {
        OFL_LOG_WARN(LOG_MODULE, "Received instruction is too short (%zu).", *len);
        return ofl_error(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
    }

    if (*len < ntohs(src->len)) {
        OFL_LOG_WARN(LOG_MODULE, "Received instruction has invalid length (set to %u, but only %zu received).", ntohs(src->len), *len);
        return ofl_error(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
    }
    ilen = ntohs(src->len);

    switch (ntohs(src->type)) {
        case OFPIT_GOTO_TABLE: {
            struct ofp_instruction_goto_table *si;
            struct ofl_instruction_goto_table *di;

            if (ilen < sizeof(struct ofp_instruction_goto_table)) {
                OFL_LOG_WARN(LOG_MODULE, "Received GOTO_TABLE instruction has invalid length (%zu).", *len);
                return ofl_error(OFPET_BAD_ACTION, OFPBRC_BAD_LEN);
            }

            si = (struct ofp_instruction_goto_table *)src;

            if (si->table_id >= PIPELINE_TABLES) {
                if (OFL_LOG_IS_WARN_ENABLED(LOG_MODULE)) {
                    char *ts = ofl_table_to_string(si->table_id);
                    OFL_LOG_WARN(LOG_MODULE, "Received GOTO_TABLE instruction has invalid table_id (%s).", ts);
                    free(ts);
                }
                return ofl_error(OFPET_BAD_INSTRUCTION, OFPBIC_BAD_TABLE_ID);
            }

            di = (struct ofl_instruction_goto_table *)malloc(sizeof(struct ofl_instruction_goto_table));

            di->table_id = si->table_id;

            inst = (struct ofl_instruction_header *)di;
            ilen -= sizeof(struct ofp_instruction_goto_table);
            break;
        }

        case OFPIT_WRITE_METADATA: {
            struct ofp_instruction_write_metadata *si;
            struct ofl_instruction_write_metadata *di;

            if (ilen < sizeof(struct ofp_instruction_write_metadata)) {
                OFL_LOG_WARN(LOG_MODULE, "Received WRITE_METADATA instruction has invalid length (%zu).", *len);
                return ofl_error(OFPET_BAD_ACTION, OFPBRC_BAD_LEN);
            }

            si = (struct ofp_instruction_write_metadata *)src;
            di = (struct ofl_instruction_write_metadata *)malloc(sizeof(struct ofl_instruction_write_metadata));

            di->metadata =      ntoh64(si->metadata);
            di->metadata_mask = ntoh64(si->metadata_mask);

            inst = (struct ofl_instruction_header *)di;
            ilen -= sizeof(struct ofp_instruction_write_metadata);
            break;
        }
        case OFPIT_WRITE_ACTIONS:
        case OFPIT_APPLY_ACTIONS: {
            struct ofp_instruction_actions *si;
            struct ofl_instruction_actions *di;
            struct ofp_action_header *act;
            ofl_err error;
            size_t i;

            if (ilen < sizeof(struct ofp_instruction_actions)) {
                OFL_LOG_WARN(LOG_MODULE, "Received *_ACTIONS instruction has invalid length (%zu).", *len);
                return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
            }
            ilen -= sizeof(struct ofp_instruction_actions);

            si = (struct ofp_instruction_actions *)src;
            di = (struct ofl_instruction_actions *)malloc(sizeof(struct ofl_instruction_actions));

            error = ofl_utils_count_ofp_actions((uint8_t *)si->actions, ilen, &di->actions_num);
            if (error) {
                free(di);
                return error;
            }
            di->actions = (struct ofl_action_header **)malloc(di->actions_num * sizeof(struct ofl_action_header *));

            act = si->actions;
            for (i = 0; i < di->actions_num; i++) {
                error = ofl_actions_unpack(act, &ilen, &(di->actions[i]), exp);
                if (error) {
                    *len = *len - ntohs(src->len) + ilen;
                    OFL_UTILS_FREE_ARR_FUN2(di->actions, i,
                                            ofl_actions_free, exp);
                    free(di);
                    return error;
                }
                act = (struct ofp_action_header *)((uint8_t *)act + ntohs(act->len));
            }

            inst = (struct ofl_instruction_header *)di;
            break;
        }
        case OFPIT_CLEAR_ACTIONS: {
            if (ilen < sizeof(struct ofp_instruction_actions)) {
                OFL_LOG_WARN(LOG_MODULE, "Received CLEAR_ACTIONS instruction has invalid length (%zu).", *len);
                return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
            }

            inst = (struct ofl_instruction_header *)malloc(sizeof(struct ofl_instruction_header));
            inst->type = (enum ofp_instruction_type)ntohs(src->type);

            ilen -= sizeof(struct ofp_instruction_actions);
            break;
        }
        case OFPIT_METER: {
            struct ofp_instruction_meter *si;
            struct ofl_instruction_meter *di;
            
            if (ilen < sizeof(struct ofp_instruction_meter)) {
                OFL_LOG_WARN(LOG_MODULE, "Received METER instruction has invalid length (%zu).", *len);
                return ofl_error(OFPET_BAD_ACTION, OFPBRC_BAD_LEN);
            }
            si = (struct ofp_instruction_meter*)src;
            di = (struct ofl_instruction_meter *)malloc(sizeof(struct ofl_instruction_meter));

            di->meter_id = ntohl(si->meter_id);

            inst = (struct ofl_instruction_header *)di;
            ilen -= sizeof(struct ofp_instruction_meter);
            break; 
        }
        case OFPIT_EXPERIMENTER: {
            ofl_err error;

            if (exp == NULL || exp->inst == NULL || exp->inst->unpack == NULL) {
                OFL_LOG_WARN(LOG_MODULE, "Received EXPERIMENTER instruction, but no callback was given.");
                return ofl_error(OFPET_BAD_INSTRUCTION, OFPBIC_UNSUP_INST);
            }
            error = exp->inst->unpack(src, &ilen, &inst);
            if (error) {
                return error;
            }
            break;
        }
        default:
            OFL_LOG_WARN(LOG_MODULE, "The received instruction type (%zu) is invalid.", ntohs(src->type));
            return ofl_error(OFPET_BAD_INSTRUCTION, OFPBIC_UNKNOWN_INST);
    }

    // must set type before check, so free works correctly
    inst->type = (enum ofp_instruction_type)ntohs(src->type);

    if (ilen != 0) {
        *len = *len - ntohs(src->len) + ilen;
        OFL_LOG_WARN(LOG_MODULE, "The received instruction contained extra bytes (%zu).", ilen);
        ofl_structs_free_instruction(inst, exp);
        return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
    }

    *len -= ntohs(src->len);
    (*dst) = inst;

    return 0;
}
示例#3
0
static ofl_err
ofl_msg_unpack_flow_mod(struct ofp_header *src, size_t *len, struct ofl_msg_header **msg, struct ofl_exp *exp, char *errbuf) {
    struct ofp_flow_mod *sm;
    struct ofl_msg_flow_mod *dm;
    struct ofp_instruction *inst;
    ofl_err error;
    size_t i;

    if (*len < (sizeof(struct ofp_flow_mod) - sizeof(struct ofp_match))) {
        if (errbuf != NULL) {
            snprintf(errbuf, OFL_ERRBUF_SIZE, "Received FLOW_MOD message has invalid length (%zu).", *len);
        }
        return ofl_error(OFPET_BAD_ACTION, OFPBRC_BAD_LEN);
    }
    *len -= (sizeof(struct ofp_flow_mod) - sizeof(struct ofp_match));

    sm = (struct ofp_flow_mod *)src;
    dm = (struct ofl_msg_flow_mod *)malloc(sizeof(struct ofl_msg_flow_mod));

    dm->cookie =       ntoh64(sm->cookie);
    dm->cookie_mask =  ntoh64(sm->cookie_mask);
    dm->table_id =            sm->table_id;
    dm->command =             (enum ofp_flow_mod_command)sm->command;
    dm->idle_timeout = ntohs( sm->idle_timeout);
    dm->hard_timeout = ntohs( sm->hard_timeout);
    dm->priority =     ntohs( sm->priority);
    dm->buffer_id =    ntohl( sm->buffer_id);
    dm->out_port =     ntohl( sm->out_port);
    dm->out_group =    ntohl( sm->out_group);
    dm->flags =        ntohs( sm->flags);

    error = ofl_structs_match_unpack(&(sm->match), len, &(dm->match), exp, errbuf);
    if (error) {
        free(dm);
        return error;
    }

    error = ofl_utils_count_ofp_instructions(&(sm->instructions), *len, &dm->instructions_num, errbuf);
    if (error) {
        ofl_structs_free_match(dm->match, exp, NULL);
        free(dm);
        return error;
    }

    dm->instructions = (struct ofl_instruction_header **)malloc(dm->instructions_num * sizeof(struct ofl_instruction_header *));
    inst = sm->instructions;
    for (i = 0; i < dm->instructions_num; i++) {
        error = ofl_structs_instructions_unpack(inst, len, &(dm->instructions[i]), exp, errbuf);
        if (error) {
            OFL_UTILS_FREE_ARR_FUN3(dm->instructions, i,
                    ofl_structs_free_instruction, exp, errbuf);
            ofl_structs_free_match(dm->match, exp, NULL);
            free(dm);
            return error;
        }
        inst = (struct ofp_instruction *)((uint8_t *)inst + ntohs(inst->len));
    }

    *msg = (struct ofl_msg_header *)dm;
    return 0;
}
示例#4
0
文件: fe_mad.c 项目: nirmoy/opa-fm
uint32_t fe_unsolicited(FE_ConnList *clist, uint32_t *conn_state) { 
    uint32_t i, rc = FE_SUCCESS; 
    uint32_t found = 0, count = 0; 
    int32_t len = 0;
    STL_NOTICE connStateTrap; 
    STL_NOTICE *noticep;
    FE_ConnList *tlist; 
    FE_Trap_t traps, *curr; 
#ifndef IB_STACK_OPENIB
    FE_Trap_t *temp;
#endif
    uint64_t tid; 
    ManagerInfo_t *mi; 
    SA_MAD *noticeMad; 
    OOBPacket *packet; 
    
    IB_ENTER(__func__, conn_state, 0, 0, 0); 
    tlist = clist; 
    
#ifdef IB_STACK_OPENIB
    // early sanity check on OFED to avoid locking the trap thread
    if (!fe_trap_thread_get_trapcount()
        && *conn_state != CONN_LOST && *conn_state != CONN_ESTABLISH) {
        IB_EXIT(__func__, rc); 
        return (rc);
    }
    
    // stop the trap thread and grab the traps.  due to the non-OFED semantics
    // of this function, we store the first trap on the stack
    {
        FE_Trap_t *ptraps; 
        fe_trap_thread_pause(); 
        fe_trap_thread_get_traplist(&ptraps, &found); 
        if (found) {
            memcpy(&traps, ptraps, sizeof(FE_Trap_t));
        }
    }
#else
    (void)fe_if3_get_traps(&traps, &found); 
#endif
    
    if (*conn_state == CONN_LOST) {
        count++;
    }
    
    if (*conn_state == CONN_ESTABLISH) {
        count++;
    }
    
    if (rc == FE_SUCCESS) {
        count = count + found;
    }
    
    if (count == 0) {
        /* no Notices to send */
#ifdef IB_STACK_OPENIB
        fe_trap_thread_resume(); 
#endif
        IB_EXIT(__func__, rc); 
        return (rc);
    }
    

    // find the handle stuff
    if ((rc = if3_mngr_locate_minfo(fdsa, &mi))) {
        IB_EXIT(__func__, rc); 
        return rc;
    }

    // allocate a tid
    ; 
    if ((rc = mai_alloc_tid(mi->fds, mi->mclass, &tid))) {
        IB_LOG_ERRORRC("unable to allocate tid rc:", rc);
        IB_EXIT(__func__, rc); 
        return rc;
    }
    
    //    
    // process the traps
    if (found) {
        curr = &traps;
        
        for (i = 0; i < found; i++, tid = mai_increment_tid(tid)) {
#ifndef IB_STACK_OPENIB
            temp = curr; 
#endif
            
            // build the out of band packet and copy the response into it.
            // there's no need to bswap the data, as that will be done by
            // the FEC on the other side
            packet = (OOBPacket *)g_fe_oob_send_buf; 
            memset(packet, 0, sizeof(OOBPacket)); 
            noticeMad = (SA_MAD *)&(packet->MadData); 
            
            // initialize SA MAD header fields    
            SA_MAD_SET_HEADER(noticeMad, SM_KEY, 0);             
            // initialize the commom mad header fields
            packet->Header.HeaderVersion = STL_BASE_VERSION; 
            MAD_SET_VERSION_INFO(noticeMad, STL_BASE_VERSION, MCLASS_SUBN_ADM, STL_SA_CLASS_VERSION); 
            MAD_SET_METHOD_TYPE(noticeMad, MAD_CM_REPORT); 
            MAD_SET_ATTRIB_ID(noticeMad, SA_NOTICE); 
            MAD_SET_TRANSACTION_ID(noticeMad, tid);             
            // initialize RMPP fields
            noticeMad->RmppHdr.RmppVersion = 1;
                         
            // copy the notice data into our packet and convert to network byte order.
            // Byte swapping to network byte order for the rest of the packet, will
            // be done by the fe_send_packet() routine.  
            (void)BSWAPCOPY_STL_NOTICE(&curr->notice, (STL_NOTICE *)noticeMad->Data);
            
            len = sizeof(OOBHeader) + IBA_SUBN_ADM_HDRSIZE + sizeof(STL_NOTICE);

            // send the notice to all FECs
            while (tlist) {
                if ((rc = fe_send_packet(tlist->conn, g_fe_oob_send_buf, len))) {
                    IB_LOG_ERROR("fe_send_packet fail in fe_unsolicited rc:", rc);
                }

                // the fe_send_packet() routine byte swaps the headers of the
                // OOB packet, so convert them back to host byte order before
                // sending packet again.
                BSWAP_OOB_PACKET(packet);
                
                tlist = tlist->next;
            }
            
            curr = curr->next;             
            // relegate memory management to trap thread functions on OFED
#ifndef IB_STACK_OPENIB
            if (i > 0) {
                vs_pool_free(&fe_pool, (void *)temp);
            }
#endif
        }
    }

    switch (*conn_state) {
    case CONN_LOST:
    case CONN_ESTABLISH:
        tlist = clist;
         
        // use 64/65 trap to notify the FEC that the connection to the SM/SA
        // has gone down/reestablished
        tid = mai_increment_tid(tid);

        // build the out of band packet and copy the response into it.
        // there's no need to bswap the data, as that will be done by
        // the FEC on the other side
        memset(&connStateTrap, 0, sizeof(connStateTrap));
        packet = (OOBPacket *)g_fe_oob_send_buf; 
        memset(packet, 0, sizeof(OOBPacket)); 
        noticeMad = (SA_MAD *)&(packet->MadData); 

        // initialize SA MAD header fields    
        SA_MAD_SET_HEADER(noticeMad, SM_KEY, 0);
                     
        // initialize the commom mad header fields
        packet->Header.HeaderVersion = STL_BASE_VERSION; 
        MAD_SET_VERSION_INFO(noticeMad, STL_BASE_VERSION, MCLASS_SUBN_ADM, STL_SA_CLASS_VERSION); 
        MAD_SET_METHOD_TYPE(noticeMad, MAD_CM_REPORT); 
        MAD_SET_ATTRIB_ID(noticeMad, SA_NOTICE); 
        MAD_SET_TRANSACTION_ID(noticeMad, tid);             
        // initialize RMPP fields
        noticeMad->RmppHdr.RmppVersion = 1;

        // initialize the notice fields
        connStateTrap.Attributes.Generic.u.s.IsGeneric = 1;
        connStateTrap.Attributes.Generic.u.s.Type = NOTICE_TYPE_INFO;
        connStateTrap.Attributes.Generic.u.s.ProducerType = NOTICE_PRODUCERTYPE_CLASSMANAGER;
        connStateTrap.Attributes.Generic.TrapNumber = (*conn_state == CONN_LOST) ? MAD_SMT_PORT_DOWN: MAD_SMT_PORT_UP;
        connStateTrap.IssuerLID	= mi->saLid;
        connStateTrap.Stats.s.Toggle = 0;
        connStateTrap.Stats.s.Count = 0;

        // copy the notice data into our packet and convert to network byte order.
        // Byte swapping to network byte order for the rest of the packet, will
        // be done by the fe_send_packet() routine.  
        (void)BSWAPCOPY_STL_NOTICE(&connStateTrap, (STL_NOTICE *)noticeMad->Data);

        // Now construct IssurerGID
        // 
        // Note, we don't copy the GIDs till after we bswap the rest of the notice.
        // This is done in order to remain consistant with the unique handling of
        // GIDs throughout the FM (GIDs are stored in network byte order).
        noticep = (STL_NOTICE *)noticeMad->Data;
		(void) memcpy((void *) &noticep->IssuerGID.Raw[0], (void *) &mi->gidPrefix, 8);
		(void) memcpy((void *) &noticep->IssuerGID.Raw[8], (void *) &mi->guid, 8);
		*(uint64_t *) &noticep->IssuerGID.Raw[0] = ntoh64(*(uint64_t *) &noticep->IssuerGID.Raw[0]);
		*(uint64_t *) &noticep->IssuerGID.Raw[8] = ntoh64(*(uint64_t *) &noticep->IssuerGID.Raw[8]);

        len = sizeof(OOBHeader) + IBA_SUBN_ADM_HDRSIZE + sizeof(STL_NOTICE);

        // send the notice to all FECs
        while (tlist) {
            if ((rc = fe_send_packet(tlist->conn, g_fe_oob_send_buf, len))) {
                IB_LOG_ERROR("fe_send_packet fail in fe_unsolicited rc:", rc);
            }
            // the fe_send_packet() routine byte swaps the headers of the
            // OOB packet, so convert them back to host byte order before
            // sending packet again.
            BSWAP_OOB_PACKET(packet);

            tlist = tlist->next;
        }
        break;

    default:
        break;
    }
    
    PCHK(rc, FAILED, "fe_unsolicited"); 
    
    *conn_state = CONN_UNCHANGED; 
    
#ifdef IB_STACK_OPENIB
    fe_trap_thread_free_traps(); 
    fe_trap_thread_resume(); 
#endif
    
    IB_EXIT(__func__, rc); 
    return (rc);
}
示例#5
0
文件: kvblock.c 项目: alex8866/kvdb
uint64_t kv_block_create(kvdb * db, uint64_t next_block_offset, uint32_t hash_value,
                         const char * key, size_t key_size,
                         const char * value, size_t value_size)
{
    uint64_t block_size = block_size_round_up(key_size + value_size);
    uint8_t log2_size = log2_round_up(block_size);
    uint64_t offset = ntoh64(db->kv_free_blocks[log2_size]);
    int use_new_block = 0;
    //fprintf(stderr, "key, value: %i %i\n", (int) key_size, (int) value_size);
    if (offset != 0) {
        // Use free block.
        uint64_t next_free_offset;
        //fprintf(stderr, "Use free block %i %i %i\n", (int) offset, (int) log2_size, (int)block_size);
        // keep it in network order.
        pread(db->kv_fd, &next_free_offset, sizeof(next_free_offset), offset);
        db->kv_free_blocks[log2_size] = next_free_offset;
    }
    else {
        // Use new block.
        offset = ntoh64(* db->kv_filesize);
        use_new_block = 1;
    }
    
    uint64_t current_key_size = key_size;
    uint64_t current_value_size = value_size;
    char * data;
    char * allocated = NULL;
    if (8 + 4 + 8 + 8 + block_size > 4096) {
        allocated = calloc(1, 8 + 4 + 8 + 8 + (size_t) block_size);
        data = allocated;
    }
    else {
        data = alloca(8 + 4 + 8 + 8 + (size_t) block_size);
        bzero(data, 8 + 4 + 8 + 8 + (size_t) block_size);
    }
    char * p = data;
    next_block_offset = hton64(next_block_offset);
    memcpy(p, &next_block_offset, sizeof(next_block_offset));
    p += sizeof(next_block_offset);
    hash_value = htonl(hash_value);
    memcpy(p, &hash_value, sizeof(hash_value));
    p += sizeof(hash_value);
    memcpy(p, &log2_size, sizeof(log2_size));
    p += sizeof(log2_size);
    current_key_size = hton64(current_key_size);
    memcpy(p, &current_key_size, sizeof(current_key_size));
    p += sizeof(current_key_size);
    memcpy(p, key, key_size);
    p += key_size;
    current_value_size = hton64(current_value_size);
    memcpy(p, &current_value_size, sizeof(current_value_size));
    p += sizeof(current_value_size);
    memcpy(p, value, value_size);
    p += value_size;
    pwrite(db->kv_fd, data, (size_t) (8 + 4 + 8 + 8 + block_size), offset);
    if (allocated != NULL) {
        free(allocated);
    }
    if (use_new_block) {
        uint64_t filesize = ntoh64(* db->kv_filesize);
        filesize += 8 + 4 + 8 + 8 + block_size;
        (* db->kv_filesize) = hton64(filesize);
    }
    
    return offset;
}
示例#6
0
int mcp_decode_int64(uint64_t *num, uint8_t *buf) {
	*num = ntoh64(*(uint64_t*) buf);
	return sizeof(num);
}
示例#7
0
文件: Socket.cpp 项目: bgs100/ping
Uint64 Socket::getUint64() {
    char buffer[8];
    if (SDLNet_TCP_Recv(sock, buffer, 8) < 8)
        error = true;
    return ntoh64(*(Uint64 *)buffer);
}
ofl_err
ofl_structs_port_stats_unpack(struct ofp_port_stats *src, size_t *len, struct ofl_port_stats **dst) {
    struct ofl_port_stats *p;

    if (*len < sizeof(struct ofp_port_stats)) {
        OFL_LOG_WARN(LOG_MODULE, "Received port stats has invalid length (%zu).", *len);
        return ofl_error(OFPET_BAD_ACTION, OFPBRC_BAD_LEN);
    }
    if (ntohl(src->port_no) == 0 ||
        (ntohl(src->port_no) > OFPP_MAX && ntohl(src->port_no) != OFPP_LOCAL)) {
        if (OFL_LOG_IS_WARN_ENABLED(LOG_MODULE)) {
            char *ps = ofl_port_to_string(ntohl(src->port_no));
            OFL_LOG_WARN(LOG_MODULE, "Received port stats has invalid port_id (%s).", ps);
            free(ps);
        }
        return ofl_error(OFPET_BAD_ACTION, OFPBRC_BAD_LEN);
    }
    *len -= sizeof(struct ofp_port_stats);

    p = (struct ofl_port_stats *)malloc(sizeof(struct ofl_port_stats));

    p->port_no      = ntohl(src->port_no);
    p->rx_packets   = ntoh64(src->rx_packets);
    p->tx_packets   = ntoh64(src->tx_packets);
    p->rx_bytes     = ntoh64(src->rx_bytes);
    p->tx_bytes     = ntoh64(src->tx_bytes);
    p->rx_dropped   = ntoh64(src->rx_dropped);
    p->tx_dropped   = ntoh64(src->tx_dropped);
    p->rx_errors    = ntoh64(src->rx_errors);
    p->tx_errors    = ntoh64(src->tx_errors);
    p->rx_frame_err = ntoh64(src->rx_frame_err);
    p->rx_over_err  = ntoh64(src->rx_over_err);
    p->rx_crc_err   = ntoh64(src->rx_crc_err);
    p->collisions   = ntoh64(src->collisions);
    p->duration_sec = ntohl(src->duration_sec);
    p->duration_nsec = ntohl(src->duration_nsec);
    *dst = p;
    return 0;
}
	inline void read(std::streambuf & istrm, Int64 & val)
	{
		BinarySerialization::read(istrm, &val, sizeof(val));
		val = ntoh64(val);
	}
示例#10
0
文件: netsync.c 项目: squadette/vlc
/*****************************************************************************
 * Run: interface thread
 *****************************************************************************/
static void Run( intf_thread_t *p_intf )
{
#define MAX_MSG_LENGTH (2 * sizeof(int64_t))

    input_thread_t *p_input = NULL;
    char p_data[MAX_MSG_LENGTH];
    int i_socket;
    int canc = vlc_savecancel();

    /* High priority thread */
    vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_INPUT );

    while( vlc_object_alive( p_intf ) )
    {
        /* Update the input */
        if( p_input == NULL )
            p_input =
                (input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT,
                                                   FIND_ANYWHERE );
        else if( p_input->b_dead )
        {
            vlc_object_release( p_input );
            p_input = NULL;
        }

        if( p_input == NULL )
        {
            /* Wait a bit */
            msleep( INTF_IDLE_SLEEP );
            continue;
        }

        /*
         * We now have an input
         */

        /* Initialize file descriptor set and timeout (0.5s) */
        /* FIXME: arbitrary tick */
        struct pollfd ufd = { .fd = i_socket, .events = POLLIN, };

        if( b_master )
        {
            struct sockaddr_storage from;
            mtime_t i_date, i_clockref, i_master_clockref;
            int i_struct_size, i_read, i_ret;

            /* Don't block */
            i_ret = poll( &ufd, 1, 500 );
            if( i_ret == 0 ) continue;
            if( i_ret < 0 )
            {
                /* Wait a bit */
                msleep( INTF_IDLE_SLEEP );
                continue;
            }

            /* We received something */
            i_struct_size = sizeof( from );
            i_read = recvfrom( i_socket, p_data, MAX_MSG_LENGTH, 0,
                               (struct sockaddr*)&from,
                               (unsigned int *)&i_struct_size );

            i_clockref = ntoh64(*(int64_t *)p_data);

            i_date = mdate();
            *(int64_t *)p_data = hton64( i_date );

            i_master_clockref = GetClockRef( p_intf, i_clockref );
            *(((int64_t *)p_data)+1) = hton64( i_master_clockref );

            /* Reply to the sender */
            sendto( i_socket, p_data, 2 * sizeof(int64_t), 0,
                    (struct sockaddr *)&from, i_struct_size );

#if 0
            msg_Dbg( p_intf, "Master clockref: %"PRId64" -> %"PRId64", from %s "
                     "(date: %"PRId64")", i_clockref, i_master_clockref,
                     from.ss_family == AF_INET
                     ? inet_ntoa(((struct sockaddr_in *)&from)->sin_addr)
                     : "non-IPv4", i_date );
#endif
        }
        else
        {
            mtime_t i_send_date, i_receive_date, i_master_date, i_diff_date;
            mtime_t i_master_clockref, i_client_clockref, i_drift;
            mtime_t i_clockref = 0;
            int i_sent, i_read, i_ret;

            /* Send clock request to the master */
            *(int64_t *)p_data = hton64( i_clockref );
            i_send_date = mdate();

            i_sent = send( i_socket, p_data, sizeof(int64_t), 0 );
            if( i_sent <= 0 )
            {
                /* Wait a bit */
                msleep( INTF_IDLE_SLEEP );
                continue;
            }

            /* Don't block */
            i_ret = poll( &ufd, 1, 500 );
            if( i_ret == 0 ) continue;
            if( i_ret < 0 )
            {
                /* Wait a bit */
                msleep( INTF_IDLE_SLEEP );
                continue;
            }

            i_receive_date = mdate();

            i_read = recv( i_socket, p_data, MAX_MSG_LENGTH, 0 );
            if( i_read <= 0 )
            {
                /* Wait a bit */
                msleep( INTF_IDLE_SLEEP );
                continue;
            }

            i_master_date = ntoh64(*(int64_t *)p_data);
            i_master_clockref = ntoh64(*(((int64_t *)p_data)+1));

            i_diff_date = i_receive_date -
                          ((i_receive_date - i_send_date) / 2 + i_master_date);

            i_client_clockref = i_drift = 0;
            if( p_input && i_master_clockref )
            {
                i_client_clockref = GetClockRef( p_intf, i_clockref );
                i_drift = i_client_clockref - i_master_clockref - i_diff_date;

                /* Update our clock to match the master's one */
                if( i_client_clockref )
                    p_input->i_pts_delay -= i_drift;
            }

#if 0
            msg_Dbg( p_intf, "Slave clockref: %"PRId64" -> %"PRId64" -> %"PRId64", "
                     "clock diff: %"PRId64" drift: %"PRId64,
                     i_clockref, i_master_clockref,
                     i_client_clockref, i_diff_date, i_drift );
#endif

            /* Wait a bit */
            msleep( INTF_IDLE_SLEEP );
        }
    }

    if( p_input ) vlc_object_release( p_input );
    vlc_restorecancel( canc );
}
示例#11
0
static void read_dump(int fd)
{
	struct hcidump_hdr dh;
	struct btsnoop_pkt dp;
	struct pktlog_hdr ph;
	struct frame frm;
	uint8_t pkt_type;
	int err;

	frm.data = malloc(HCI_MAX_FRAME_SIZE);
	if (!frm.data) {
		perror("Can't allocate data buffer");
		exit(1);
	}

	while (1) {
		if (parser.flags & DUMP_PKTLOG)
			err = read_n(fd, (void *) &ph, PKTLOG_HDR_SIZE);
		else if (parser.flags & DUMP_BTSNOOP)
			err = read_n(fd, (void *) &dp, BTSNOOP_PKT_SIZE);
		else
			err = read_n(fd, (void *) &dh, HCIDUMP_HDR_SIZE);

		if (err < 0)
			goto failed;
		if (!err)
			return;

		if (parser.flags & DUMP_PKTLOG) {
			switch (ph.type) {
			case 0x00:
				((uint8_t *) frm.data)[0] = HCI_COMMAND_PKT;
				frm.in = 0;
				break;
			case 0x01:
				((uint8_t *) frm.data)[0] = HCI_EVENT_PKT;
				frm.in = 1;
				break;
			case 0x02:
				((uint8_t *) frm.data)[0] = HCI_ACLDATA_PKT;
				frm.in = 0;
				break;
			case 0x03:
				((uint8_t *) frm.data)[0] = HCI_ACLDATA_PKT;
				frm.in = 1;
				break;
			default:
				lseek(fd, ntohl(ph.len) - 9, SEEK_CUR);
				continue;
			}

			frm.data_len = ntohl(ph.len) - 8;
			err = read_n(fd, frm.data + 1, frm.data_len - 1);
		} else if (parser.flags & DUMP_BTSNOOP) {
			switch (btsnoop_type) {
			case 1001:
				if (ntohl(dp.flags) & 0x02) {
					if (ntohl(dp.flags) & 0x01)
						pkt_type = HCI_EVENT_PKT;
					else
						pkt_type = HCI_COMMAND_PKT;
				} else
					pkt_type = HCI_ACLDATA_PKT;

				((uint8_t *) frm.data)[0] = pkt_type;

				frm.data_len = ntohl(dp.len) + 1;
				err = read_n(fd, frm.data + 1, frm.data_len - 1);
				break;

			case 1002:
				frm.data_len = ntohl(dp.len);
				err = read_n(fd, frm.data, frm.data_len);
				break;
			}
		} else {
			frm.data_len = btohs(dh.len);
			err = read_n(fd, frm.data, frm.data_len);
		}

		if (err < 0)
			goto failed;
		if (!err)
			return;

		frm.ptr = frm.data;
		frm.len = frm.data_len;

		if (parser.flags & DUMP_PKTLOG) {
			uint64_t ts;
			ts = ntoh64(ph.ts);
			frm.ts.tv_sec = ts >> 32;
			frm.ts.tv_usec = ts & 0xffffffff;
		} else if (parser.flags & DUMP_BTSNOOP) {
示例#12
0
			goto failed;
		if (!err)
			return;

		frm.ptr = frm.data;
		frm.len = frm.data_len;

		if (parser.flags & DUMP_PKTLOG) {
			uint64_t ts;
			ts = ntoh64(ph.ts);
			frm.ts.tv_sec = ts >> 32;
			frm.ts.tv_usec = ts & 0xffffffff;
		} else if (parser.flags & DUMP_BTSNOOP) {
			uint64_t ts;
			frm.in = ntohl(dp.flags) & 0x01;
			ts = ntoh64(dp.ts) - 0x00E03AB44A676000ll;
			frm.ts.tv_sec = (ts / 1000000ll) + 946684800ll;
			frm.ts.tv_usec = ts % 1000000ll;
		} else {
			frm.in = dh.in;
			frm.ts.tv_sec  = btohl(dh.ts_sec);
			frm.ts.tv_usec = btohl(dh.ts_usec);
		}

		parse(&frm);
	}

failed:
	perror("Read failed");
	exit(1);
}
示例#13
0
//Read Address Prefix Block data
bool ReadAddressPrefixBlock(
	const uint16_t Protocol, 
	std::string OriginalData, 
	const size_t DataOffset, 
	ADDRESS_PREFIX_BLOCK * const AddressPrefix, 
	const std::vector<FILE_DATA> &FileList, 
	const size_t FileIndex, 
	const size_t Line)
{
	std::string Data(OriginalData, DataOffset);

//Check data format.
	if (Data.find("/") == std::string::npos || Data.rfind("/") < ADDRESS_STRING_IPV6_MINSIZE || Data.at(Data.length() - 1U) == ASCII_SLASH)
	{
		PrintError(LOG_LEVEL_TYPE::LEVEL_1, LOG_ERROR_TYPE::PARAMETER, L"Address Prefix Block format error", 0, FileList.at(FileIndex).FileName.c_str(), Line);
		return false;
	}
	for (const auto &StringIter:Data)
	{
		if (StringIter < ASCII_PERIOD || (StringIter > ASCII_COLON && StringIter < ASCII_UPPERCASE_A) || 
			(StringIter > ASCII_UPPERCASE_F && StringIter < ASCII_LOWERCASE_A) || StringIter > ASCII_LOWERCASE_F)
		{
			PrintError(LOG_LEVEL_TYPE::LEVEL_1, LOG_ERROR_TYPE::PARAMETER, L"Address Prefix Block format error", 0, FileList.at(FileIndex).FileName.c_str(), Line);
			return false;
		}
	}

//Initialization
	std::array<uint8_t, ADDRESS_STRING_MAXSIZE + MEMORY_RESERVED_BYTES> AddrBuffer{};
	memcpy_s(AddrBuffer.data(), ADDRESS_STRING_MAXSIZE, Data.c_str(), Data.find("/"));
	Data.erase(0, Data.find("/") + 1U);
	ssize_t SignedResult = 0;
	size_t UnsignedResult = 0;

//IPv6
	if (Protocol == AF_INET6)
	{
	//Prefix check and convert address.
		if (Data.find(ASCII_MINUS) != std::string::npos || 
			!AddressStringToBinary(AF_INET6, AddrBuffer.data(), &reinterpret_cast<sockaddr_in6 *>(&AddressPrefix->first)->sin6_addr, &SignedResult))
		{
			PrintError(LOG_LEVEL_TYPE::LEVEL_1, LOG_ERROR_TYPE::PARAMETER, L"IPv6 address format error", SignedResult, FileList.at(FileIndex).FileName.c_str(), Line);
			return false;
		}

	//Mark network prefix.
		_set_errno(0);
		UnsignedResult = strtoul(Data.c_str(), nullptr, 0);
		if (UnsignedResult == 0 || UnsignedResult > sizeof(in6_addr) * BYTES_TO_BITS)
		{
			PrintError(LOG_LEVEL_TYPE::LEVEL_1, LOG_ERROR_TYPE::PARAMETER, L"IPv6 prefix error", errno, FileList.at(FileIndex).FileName.c_str(), Line);
			return false;
		}
		else {
			AddressPrefix->second = UnsignedResult;

		//Mark prefix block.
			if (AddressPrefix->second < sizeof(in6_addr) * BYTES_TO_BITS / 2U)
			{
				*reinterpret_cast<uint64_t *>(&reinterpret_cast<sockaddr_in6 *>(&AddressPrefix->first)->sin6_addr) = hton64(ntoh64(*reinterpret_cast<uint64_t *>(&reinterpret_cast<sockaddr_in6 *>(&AddressPrefix->first)->sin6_addr)) & (UINT64_MAX << (sizeof(in6_addr) * BYTES_TO_BITS / 2U - AddressPrefix->second))); //Mark high 64 bits.
				*reinterpret_cast<uint64_t *>(reinterpret_cast<uint8_t *>(&reinterpret_cast<sockaddr_in6 *>(&AddressPrefix->first)->sin6_addr) + sizeof(in6_addr) / 2U) = 0; //Remove low 64 bits.
			}
			else {
				*reinterpret_cast<uint64_t *>(reinterpret_cast<uint8_t *>(&reinterpret_cast<sockaddr_in6 *>(&AddressPrefix->first)->sin6_addr) + sizeof(in6_addr) / 2U) = hton64(ntoh64(*reinterpret_cast<uint64_t *>(reinterpret_cast<uint8_t *>(&reinterpret_cast<sockaddr_in6 *>(&AddressPrefix->first)->sin6_addr) + sizeof(in6_addr) / 2U)) & (UINT64_MAX << (sizeof(in6_addr) * BYTES_TO_BITS - AddressPrefix->second))); //Mark low 64 bits.
			}
		}

		AddressPrefix->first.ss_family = AF_INET6;
	}
//IPv4
	else if (Protocol == AF_INET)
	{
	//Prefix check and convert address.
		if (Data.find(ASCII_MINUS) != std::string::npos || 
			!AddressStringToBinary(AF_INET, AddrBuffer.data(), &reinterpret_cast<sockaddr_in *>(&AddressPrefix->first)->sin_addr, &SignedResult))
		{
			PrintError(LOG_LEVEL_TYPE::LEVEL_1, LOG_ERROR_TYPE::PARAMETER, L"IPv4 address format error", SignedResult, FileList.at(FileIndex).FileName.c_str(), Line);
			return false;
		}

	//Mark network prefix.
		_set_errno(0);
		UnsignedResult = strtoul(Data.c_str(), nullptr, 0);
		if (UnsignedResult == 0 || UnsignedResult > sizeof(in_addr) * BYTES_TO_BITS)
		{
			PrintError(LOG_LEVEL_TYPE::LEVEL_1, LOG_ERROR_TYPE::PARAMETER, L"IPv4 prefix error", errno, FileList.at(FileIndex).FileName.c_str(), Line);
			return false;
		}
		else {
			AddressPrefix->second = UnsignedResult;

		//Mark prefix block.
			reinterpret_cast<sockaddr_in *>(&AddressPrefix->first)->sin_addr.s_addr = htonl(ntohl(reinterpret_cast<sockaddr_in *>(&AddressPrefix->first)->sin_addr.s_addr) & (UINT32_MAX << (sizeof(in_addr) * BYTES_TO_BITS - AddressPrefix->second)));
		}

		AddressPrefix->first.ss_family = AF_INET;
	}
	else {
		PrintError(LOG_LEVEL_TYPE::LEVEL_1, LOG_ERROR_TYPE::PARAMETER, L"Data format error", 0, FileList.at(FileIndex).FileName.c_str(), Line);
		return false;
	}

	return true;
}
ofl_err
ofl_structs_flow_stats_unpack(struct ofp_flow_stats *src, uint8_t *buf, size_t *len, struct ofl_flow_stats **dst, struct ofl_exp *exp) {
    struct ofl_flow_stats *s;
    struct ofp_instruction *inst;
    ofl_err error;
    size_t slen;
    size_t i;
    int match_pos;
    if (*len < ( (sizeof(struct ofp_flow_stats) - sizeof(struct ofp_match)) + ROUND_UP(ntohs(src->match.length),8))) {
        OFL_LOG_WARN(LOG_MODULE, "Received flow stats has invalid length (%zu).", *len);
        return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
    }

    if (*len < ntohs(src->length)) {
        OFL_LOG_WARN(LOG_MODULE, "Received flow stats reply has invalid length (set to %u, but only %zu received).", ntohs(src->length), *len);
        return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
    }

    if (src->table_id >= PIPELINE_TABLES) {
        if (OFL_LOG_IS_WARN_ENABLED(LOG_MODULE)) {
            char *ts = ofl_table_to_string(src->table_id);
            OFL_LOG_WARN(LOG_MODULE, "Received flow stats has invalid table_id (%s).", ts);
            free(ts);
        }
        return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_TABLE_ID);
    }

    slen = ntohs(src->length) - (sizeof(struct ofp_flow_stats) - sizeof(struct ofp_match));

    s = (struct ofl_flow_stats *)malloc(sizeof(struct ofl_flow_stats));
    s->table_id =             src->table_id;
    s->duration_sec =  ntohl( src->duration_sec);
    s->duration_nsec = ntohl( src->duration_nsec);
    s->priority =      ntohs( src->priority);
    s->idle_timeout =  ntohs( src->idle_timeout);
    s->hard_timeout =  ntohs( src->hard_timeout);
    s->cookie =        ntoh64(src->cookie);
    s->packet_count =  ntoh64(src->packet_count);
    s->byte_count =    ntoh64(src->byte_count);

    match_pos = sizeof(struct ofp_flow_stats) - 4;

    error = ofl_structs_match_unpack(&(src->match),buf + match_pos , &slen, &(s->match), exp);
    if (error) {
        free(s);
        return error;
    }
    error = ofl_utils_count_ofp_instructions((struct ofp_instruction *) (buf + ROUND_UP(match_pos + s->match->length,8)), 
                                            slen, &s->instructions_num);
    
    if (error) {
        ofl_structs_free_match(s->match, exp);
        free(s);
        return error;
    }
   s->instructions = (struct ofl_instruction_header **)malloc(s->instructions_num * sizeof(struct ofl_instruction_header *));

   inst = (struct ofp_instruction *) (buf + ROUND_UP(match_pos + s->match->length,8));
   for (i = 0; i < s->instructions_num; i++) {
        error = ofl_structs_instructions_unpack(inst, &slen, &(s->instructions[i]), exp);
        if (error) {
            OFL_UTILS_FREE_ARR_FUN2(s->instructions, i,
                                    ofl_structs_free_instruction, exp);
            free(s);
            return error;
        }
        inst = (struct ofp_instruction *)((uint8_t *)inst + ntohs(inst->len));
    }

    if (slen != 0) {
        *len = *len - ntohs(src->length) + slen;
        OFL_LOG_WARN(LOG_MODULE, "The received flow stats contained extra bytes (%zu).", slen);
        ofl_structs_free_flow_stats(s, exp);
        return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
    }
    *len -= ntohs(src->length);
    *dst = s;
    return 0;
}
示例#15
0
int main(void)
{
  long rc;

  ///////////////////////////////////////////////////
  //         Test of changing byte order
  ///////////////////////////////////////////////////
  uint64_t data64 = 0x0102030405060708;
  printf("u64 (host):0x%016lx\n", data64);
  print_bytes64(data64);

  data64 = hton64(data64);
  printf("u64 (net):0x%016lx\n", data64);
  print_bytes64(data64);

  data64 = ntoh64(data64);
  printf("u64 (host):0x%016lx\n", data64);
  print_bytes64(data64);

  printf("\n");

  data64 = 0xcafedeca01020304;
  printf("u64 (host):0x%016lx\n", data64);
  print_bytes64(data64);

  hton64(&data64);
  printf("u64 (net):0x%016lx\n", data64);
  print_bytes64(data64);

  ntoh64(&data64);
  printf("u64 (host):0x%016lx\n", data64);
  print_bytes64(data64);

  printf("\n");

  uint32_t data32 = 0xdeadbeef;
  printf("u32 (host):0x%08x\n", data32);
  print_bytes32(data32);

  hton32(&data32);
  printf("u32 (net):0x%08x\n", data32);
  print_bytes32(data32);

  ntoh32(&data32);
  printf("u32 (host):0x%08x\n", data32);
  print_bytes32(data32);

  printf("\n");

  ///////////////////////////////////////////////////
  //         Test of address transformation
  ///////////////////////////////////////////////////

  uint32_t net_addr;
  char ip_address[20];  

  to_net_address("192.168.100.17", &net_addr);
  printf("Net-address (classic)  : 0x%08x\n", net_addr);

  to_net_address(ANY_IP_ADDRESS, &net_addr);
  printf("Net-address (any)      : 0x%08x\n", net_addr);

  to_net_address(LOOPBACK_IP_ADDRESS, &net_addr);
  printf("Net-address (loopback) : 0x%08x\n", net_addr);

  to_net_address(BROADCAST_IP_ADDRESS, &net_addr);
  printf("Net-address (broadcast): 0x%08x\n", net_addr);

  net_addr = 0xc0a86411; // 192.168.100.17
  to_ip_address(net_addr, ip_address, 20);
  printf("IP-address (classic)  : %s\n", ip_address);

  net_addr = 0x0; // 0.0.0.0
  to_ip_address(net_addr, ip_address, 20);
  printf("IP-address (any)      : %s\n", ip_address);

  net_addr = 0x7f000001; // 127.0.0.1
  to_ip_address(net_addr, ip_address, 20);
  printf("IP-address (loopback) : %s\n", ip_address);

  net_addr = 0xffffffff; // 255.255.255.255
  to_ip_address(net_addr, ip_address, 20);
  printf("IP-address (broadcast): %s\n", ip_address);

  printf("\n");

  ///////////////////////////////////////////////////
  //         Test of resolving hostname
  ///////////////////////////////////////////////////

  resolve_element resolve_list[10];
  unsigned actual;

  bzero(resolve_list, sizeof(resolve_list));
  rc = resolve_hostname("www.google.com", 80, resolve_list, 10, &actual);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (resolve_hostname)");
    return 1;
  }
  for (unsigned i=0; i < actual; i++) {
    to_ip_address(resolve_list[i].net_addr, ip_address, 20);
    printf("Net-addr=0x%08x (%s),\tprotocol=%04d, socktype=%04d\n",
	   resolve_list[i].net_addr,
	   ip_address,
	   resolve_list[i].protocol,
	   resolve_list[i].socktype);
  }

  printf("\n");

  ///////////////////////////////////////////////////
  //         Test of connected UDP socket
  ///////////////////////////////////////////////////

  int udp_socket;
  socket_address udp_local_sa;
  socket_address udp_dest_sa;

  rc = create_udp_socket(&udp_socket);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (create_udp_socket)");
    return 1;
  }

  to_net_address(ANY_IP_ADDRESS, &udp_local_sa.net_addr);
  udp_local_sa.port = 14000;

  rc = bind_socket(udp_socket, udp_local_sa);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (bind_socket)");
    return 1;
  }

  to_net_address("192.168.0.1", &udp_dest_sa.net_addr);
  udp_dest_sa.port = 25000;

  rc = connect_socket(udp_socket, udp_dest_sa);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (connect_socket)");
    return 1;
  }

  bzero(&udp_local_sa, sizeof(udp_local_sa));
  bzero(&udp_dest_sa, sizeof(udp_dest_sa));

  get_socket_local_address(udp_socket, &udp_local_sa);
  get_socket_peer_address(udp_socket, &udp_dest_sa);

  to_ip_address(udp_local_sa.net_addr, ip_address, 20);
  printf("(UDP) Local IP : %s, port = %d\n", ip_address, udp_local_sa.port);

  to_ip_address(udp_dest_sa.net_addr, ip_address, 20);
  printf("(UDP) Dest IP  : %s, port = %d\n", ip_address, udp_dest_sa.port);

  rc = close_socket(udp_socket);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (close_socket)");
    return 1;
  }

  return 0;
}
ofl_err
ofl_structs_group_stats_unpack(struct ofp_group_stats *src, size_t *len, struct ofl_group_stats **dst) {
    struct ofl_group_stats *s;
    struct ofp_bucket_counter *c;
    ofl_err error;
    size_t slen;
    size_t i;

    if (*len < sizeof(struct ofp_group_stats)) {
        OFL_LOG_WARN(LOG_MODULE, "Received group desc stats reply is too short (%zu).", *len);
        return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
    }

    if (*len < ntohs(src->length)) {
        OFL_LOG_WARN(LOG_MODULE, "Received group stats reply has invalid length (set to %u, but only %zu received).", ntohs(src->length), *len);
        return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
    }

    if (ntohl(src->group_id) > OFPG_MAX) {
        if (OFL_LOG_IS_WARN_ENABLED(LOG_MODULE)) {
            char *gs = ofl_group_to_string(ntohl(src->group_id));
            OFL_LOG_WARN(LOG_MODULE, "Received group stats has invalid group_id (%s).", gs);
            free(gs);
        }
        return ofl_error(OFPET_BAD_ACTION, OFPBRC_BAD_LEN);
    }
    slen = ntohs(src->length) - sizeof(struct ofp_group_stats);

    s = (struct ofl_group_stats *)malloc(sizeof(struct ofl_group_stats));
    s->group_id = ntohl(src->group_id);
    s->ref_count = ntohl(src->ref_count);
    s->packet_count = ntoh64(src->packet_count);
    s->byte_count = ntoh64(src->byte_count);
    s->duration_sec =  htonl(src->duration_sec);
    s->duration_nsec =  htonl(src->duration_nsec);

    error = ofl_utils_count_ofp_bucket_counters(src->bucket_stats, slen, &s->counters_num);
    if (error) {
        free(s);
        return error;
    }
    s->counters = (struct ofl_bucket_counter **)malloc(s->counters_num * sizeof(struct ofl_bucket_counter *));

    c = src->bucket_stats;
    for (i = 0; i < s->counters_num; i++) {
        error = ofl_structs_bucket_counter_unpack(c, &slen, &(s->counters[i]));
        if (error) {
            OFL_UTILS_FREE_ARR(s->counters, i);
            free(s);
            return error;
        }
        c = (struct ofp_bucket_counter *)((uint8_t *)c + sizeof(struct ofp_bucket_counter));
    }

    if (slen != 0) {
        *len = *len - ntohs(src->length) + slen;
        OFL_LOG_WARN(LOG_MODULE, "The received group stats contained extra bytes (%zu).", slen);
        ofl_structs_free_group_stats(s);
        return ofl_error(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
    }

    *len -= ntohs(src->length);
    *dst = s;
    return 0;
}
示例#17
0
status_t SampleTable::setSampleDescParams(uint32_t count, off64_t offset, size_t size)
{
    // avcC atom will start after 78 bytes in avC1 atom
    const uint32_t avcC_offset = 78;

    for(uint32_t i = 0; i < count; ++i) {
        uint32_t hdr[2];
        if (mDataSource->readAt(offset, hdr, 8) < 8) {
            return ERROR_IO;
        }
        uint64_t avc1_chunk_size = ntohl(hdr[0]);
        uint32_t avc1_chunk_type = ntohl(hdr[1]);
        off64_t avc1_data_offset = offset + 8;

        if(avc1_chunk_size == 0)
            return ERROR_MALFORMED;

        if (avc1_chunk_size == 1) {
            if (mDataSource->readAt(offset + 8, &avc1_chunk_size, 8) < 8) {
                return ERROR_IO;
            }
            avc1_chunk_size = ntoh64(avc1_chunk_size);
            if (avc1_chunk_size == 0)
                return ERROR_MALFORMED;
            avc1_data_offset += 8;

            if (avc1_chunk_size < 16) {
                // The smallest valid chunk is 16 bytes long in this case.
                return ERROR_MALFORMED;
            }
        } else if (avc1_chunk_size < 8) {
            // The smallest valid chunk is 8 bytes long.
            return ERROR_MALFORMED;
        }

        off64_t avc1_chunk_data_size = offset + avc1_chunk_size - avc1_data_offset;
        LOGV("parsing chunk %c%c%c%c", ((char *)&avc1_chunk_type)[3],
                                                   ((char *)&avc1_chunk_type)[2],
                                                   ((char *)&avc1_chunk_type)[1],
                                                   ((char *)&avc1_chunk_type)[0]);

        if (avc1_chunk_type != FOURCC('a', 'v', 'c', '1')) {
            LOGE("Multiple Non AVC Sample Entries are not supported");
            return ERROR_MALFORMED;
        }

        uint8_t *buffer = new uint8_t[(ssize_t)avc1_chunk_data_size];
        if (mDataSource->readAt(avc1_data_offset, buffer, (ssize_t)avc1_chunk_data_size) < (ssize_t)avc1_chunk_data_size) {
              return ERROR_IO;
        }
        uint16_t data_ref_index = U16_AT(&buffer[6]);
        uint16_t width = U16_AT(&buffer[6 + 18]);
        uint16_t height = U16_AT(&buffer[6 + 20]);
        LOGE("data_ref_index : %d width : %d height: %d", data_ref_index, width, height);

        /* parse AVCC atom */
        uint64_t avcc_chunk_size = U32_AT(&buffer[avcC_offset]);
        uint32_t avcc_chunk_type = U32_AT(&buffer[avcC_offset+4]);;
        if((avcc_chunk_size == 0)|| (avcc_chunk_size == 1)) {
            LOGE("chunk size error while reading avCC atom");
            return ERROR_MALFORMED;
        }

        LOGV("parsing chunk %c%c%c%c",
               ((char *)&avcc_chunk_type)[3],
               ((char *)&avcc_chunk_type)[2],
               ((char *)&avcc_chunk_type)[1],
               ((char *)&avcc_chunk_type)[0]);

        if (avcc_chunk_type != FOURCC('a', 'v', 'c', 'C')) {
            LOGE("'avcC' atom expected, but not found");
            return ERROR_MALFORMED;
        }

        off64_t avcc_chunk_data_size = avc1_chunk_data_size - avcC_offset - 8;
        SampleDescAtom *sda = new SampleDescAtom;
        uint8_t *avccBuffer = new uint8_t[avcc_chunk_data_size];
        memcpy(avccBuffer, buffer+avcC_offset+8,avcc_chunk_data_size);
        sda->ptr = avccBuffer;
        sda->size =  avcc_chunk_data_size;
        mSampleDescAtoms.push_back(sda);

        delete[] buffer;

        offset += avc1_chunk_size;
    }
    return OK;
}
示例#18
0
文件: netsync.c 项目: forthyen/SDesk
/*****************************************************************************
 * Run: interface thread
 *****************************************************************************/
static void Run( intf_thread_t *p_intf )
{
#define MAX_MSG_LENGTH (2 * sizeof(int64_t))

    vlc_bool_t b_master = config_GetInt( p_intf, "netsync-master" );
    char *psz_master = NULL;
    char p_data[MAX_MSG_LENGTH];
    int i_socket;

    if( !b_master )
    {
        psz_master = config_GetPsz( p_intf, "netsync-master-ip" );
        if( psz_master == NULL )
        {
            msg_Err( p_intf, "master address not specified" );
            return;
        }
    }

    i_socket = net_OpenUDP( p_intf, NULL,
                   b_master ? NETSYNC_PORT_MASTER : NETSYNC_PORT_SLAVE,
                   b_master ? NULL : psz_master,
                   b_master ? 0 : NETSYNC_PORT_MASTER );

    if( psz_master ) free( psz_master );

    if( i_socket < 0 )
    {
        msg_Err( p_intf, "failed opening UDP socket." );
        return;
    }

    /* High priority thread */
    vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_INPUT );

    while( !p_intf->b_die )
    {
        struct timeval timeout;
        fd_set fds_r;

        /* Update the input */
        if( p_intf->p_sys->p_input == NULL )
        {
            p_intf->p_sys->p_input =
                (input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT,
                                                   FIND_ANYWHERE );
        }
        else if( p_intf->p_sys->p_input->b_dead )
        {
            vlc_object_release( p_intf->p_sys->p_input );
            p_intf->p_sys->p_input = NULL;
        }

        if( p_intf->p_sys->p_input == NULL )
        {
            /* Wait a bit */
            msleep( INTF_IDLE_SLEEP );
            continue;
        }

        /*
         * We now have an input
         */

        /* Initialize file descriptor set and timeout (0.5s) */
        FD_ZERO( &fds_r );
        FD_SET( i_socket, &fds_r );
        timeout.tv_sec = 0;
        timeout.tv_usec = 500000;

        if( b_master )
        {
            struct sockaddr_storage from;
            mtime_t i_date, i_clockref, i_master_clockref;
            int i_struct_size, i_read, i_ret;

            /* Don't block */
            i_ret = select( i_socket + 1, &fds_r, 0, 0, &timeout );
            if( i_ret == 0 ) continue;
            if( i_ret < 0 )
            {
                /* Wait a bit */
                msleep( INTF_IDLE_SLEEP );
                continue;
            }

            /* We received something */
            i_struct_size = sizeof( from );
            i_read = recvfrom( i_socket, p_data, MAX_MSG_LENGTH, 0,
                               (struct sockaddr*)&from, &i_struct_size );

            i_clockref = ntoh64(*(int64_t *)p_data);

            i_date = mdate();
            *(int64_t *)p_data = hton64( i_date );

            i_master_clockref = GetClockRef( p_intf, i_clockref );
            *(((int64_t *)p_data)+1) = hton64( i_master_clockref );

            /* Reply to the sender */
            sendto( i_socket, p_data, 2 * sizeof(int64_t), 0,
                    (struct sockaddr *)&from, i_struct_size );

#if 0
            msg_Dbg( p_intf, "Master clockref: "I64Fd" -> "I64Fd", from %s "
                     "(date: "I64Fd")", i_clockref, i_master_clockref,
                     from.ss_family == AF_INET
                     ? inet_ntoa(((struct sockaddr_in *)&from)->sin_addr)
                     : "non-IPv4", i_date );
#endif
        }
        else
        {
            mtime_t i_send_date, i_receive_date, i_master_date, i_diff_date;
            mtime_t i_master_clockref, i_client_clockref, i_drift;
            mtime_t i_clockref = 0;
            int i_sent, i_read, i_ret;

            /* Send clock request to the master */
            *(int64_t *)p_data = hton64( i_clockref );
            i_send_date = mdate();

            i_sent = send( i_socket, p_data, sizeof(int64_t), 0 );
            if( i_sent <= 0 )
            {
                /* Wait a bit */
                msleep( INTF_IDLE_SLEEP );
                continue;
            }

            /* Don't block */
            i_ret = select(i_socket + 1, &fds_r, 0, 0, &timeout);
            if( i_ret == 0 ) continue;
            if( i_ret < 0 )
            {
                /* Wait a bit */
                msleep( INTF_IDLE_SLEEP );
                continue;
            }

            i_receive_date = mdate();

            i_read = recv( i_socket, p_data, MAX_MSG_LENGTH, 0 );
            if( i_read <= 0 )
            {
                /* Wait a bit */
                msleep( INTF_IDLE_SLEEP );
                continue;
            }

            i_master_date = ntoh64(*(int64_t *)p_data);
            i_master_clockref = ntoh64(*(((int64_t *)p_data)+1));

            i_diff_date = i_receive_date -
                          ((i_receive_date - i_send_date) / 2 + i_master_date);

            i_client_clockref = i_drift = 0;
            if( p_intf->p_sys->p_input && i_master_clockref )
            {
                i_client_clockref = GetClockRef( p_intf, i_clockref );
                i_drift = i_client_clockref - i_master_clockref - i_diff_date;

                /* Update our clock to match the master's one */
                if( i_client_clockref )
                    p_intf->p_sys->p_input->i_pts_delay -= i_drift;
            }

#if 0
            msg_Dbg( p_intf, "Slave clockref: "I64Fd" -> "I64Fd" -> "I64Fd", "
                     "clock diff: "I64Fd" drift: "I64Fd,
                     i_clockref, i_master_clockref, 
                     i_client_clockref, i_diff_date, i_drift );
#endif

            /* Wait a bit */
            msleep( INTF_IDLE_SLEEP );
        }
    }

    if( p_intf->p_sys->p_input ) vlc_object_release( p_intf->p_sys->p_input );
    net_Close( i_socket );
}
示例#19
0
文件: ws.c 项目: odmanV2/freecenter
ssize_t ws_read_frame(wsh_t *wsh, ws_opcode_t *oc, uint8_t **data)
{
	
	ssize_t need = 2;
	char *maskp;
	int ll = 0;
	int frag = 0;
	int blen;

	wsh->body = wsh->bbuffer;
	wsh->packetlen = 0;

 again:
	need = 2;
	maskp = NULL;
	*data = NULL;

	ll = establish_logical_layer(wsh);

	if (ll < 0) {
		return ll;
	}

	if (wsh->down) {
		return -1;
	}

	if (!wsh->handshake) {
		return ws_close(wsh, WS_PROTO_ERR);
	}

	if ((wsh->datalen = ws_raw_read(wsh, wsh->buffer, 9, wsh->block)) < 0) {
		if (wsh->datalen == -2) {
			return -2;
		}
		return ws_close(wsh, WS_PROTO_ERR);
	}
	
	if (wsh->datalen < need) {
		if ((wsh->datalen += ws_raw_read(wsh, wsh->buffer + wsh->datalen, 9 - wsh->datalen, WS_BLOCK)) < need) {
			/* too small - protocol err */
			return ws_close(wsh, WS_PROTO_ERR);
		}
	}

	*oc = *wsh->buffer & 0xf;

	switch(*oc) {
	case WSOC_CLOSE:
		{
			wsh->plen = wsh->buffer[1] & 0x7f;
			*data = (uint8_t *) &wsh->buffer[2];
			return ws_close(wsh, 1000);
		}
		break;
	case WSOC_CONTINUATION:
	case WSOC_TEXT:
	case WSOC_BINARY:
	case WSOC_PING:
	case WSOC_PONG:
		{
			int fin = (wsh->buffer[0] >> 7) & 1;
			int mask = (wsh->buffer[1] >> 7) & 1;
			

			if (!fin && *oc != WSOC_CONTINUATION) {
				frag = 1;
			} else if (fin && *oc == WSOC_CONTINUATION) {
				frag = 0;
			}

			if (mask) {
				need += 4;
				
				if (need > wsh->datalen) {
					/* too small - protocol err */
					*oc = WSOC_CLOSE;
					return ws_close(wsh, WS_PROTO_ERR);
				}
			}

			wsh->plen = wsh->buffer[1] & 0x7f;
			wsh->payload = &wsh->buffer[2];
			
			if (wsh->plen == 127) {
				uint64_t *u64;
				int more = 0;

				need += 8;

				if (need > wsh->datalen) {
					/* too small - protocol err */
					//*oc = WSOC_CLOSE;
					//return ws_close(wsh, WS_PROTO_ERR);

					more = ws_raw_read(wsh, wsh->buffer + wsh->datalen, need - wsh->datalen, WS_BLOCK);

					if (more < need - wsh->datalen) {
						*oc = WSOC_CLOSE;
						return ws_close(wsh, WS_PROTO_ERR);
					} else {
						wsh->datalen += more;
					}


				}
				
				u64 = (uint64_t *) wsh->payload;
				wsh->payload += 8;
				wsh->plen = ntoh64(*u64);
			} else if (wsh->plen == 126) {
				uint16_t *u16;

				need += 2;

				if (need > wsh->datalen) {
					/* too small - protocol err */
					*oc = WSOC_CLOSE;
					return ws_close(wsh, WS_PROTO_ERR);
				}

				u16 = (uint16_t *) wsh->payload;
				wsh->payload += 2;
				wsh->plen = ntohs(*u16);
			}

			if (mask) {
				maskp = (char *)wsh->payload;
				wsh->payload += 4;
			}

			need = (wsh->plen - (wsh->datalen - need));

			if (need < 0) {
				/* invalid read - protocol err .. */
				*oc = WSOC_CLOSE;
				return ws_close(wsh, WS_PROTO_ERR);
			}

			blen = wsh->body - wsh->bbuffer;

			if (need + blen > (ssize_t)wsh->bbuflen) {
				void *tmp;
				
				wsh->bbuflen = need + blen + wsh->rplen;

				if ((tmp = realloc(wsh->bbuffer, wsh->bbuflen))) {
					wsh->bbuffer = tmp;
				} else {
					abort();
				}

				wsh->body = wsh->bbuffer + blen;
			}

			wsh->rplen = wsh->plen - need;
			
			if (wsh->rplen) {
				memcpy(wsh->body, wsh->payload, wsh->rplen);
			}
			
			while(need) {
				ssize_t r = ws_raw_read(wsh, wsh->body + wsh->rplen, need, WS_BLOCK);

				if (r < 1) {
					/* invalid read - protocol err .. */
					*oc = WSOC_CLOSE;
					return ws_close(wsh, WS_PROTO_ERR);
				}

				wsh->datalen += r;
				wsh->rplen += r;
				need -= r;
			}
			
			if (mask && maskp) {
				ssize_t i;

				for (i = 0; i < wsh->datalen; i++) {
					wsh->body[i] ^= maskp[i % 4];
				}
			}
			

			if (*oc == WSOC_PING) {
				ws_write_frame(wsh, WSOC_PONG, wsh->body, wsh->rplen);
				goto again;
			}

			*(wsh->body+wsh->rplen) = '\0';
			wsh->packetlen += wsh->rplen;
			wsh->body += wsh->rplen;

			if (frag) {
				goto again;
			}

			*data = (uint8_t *)wsh->bbuffer;
			
			//printf("READ[%ld][%d]-----------------------------:\n[%s]\n-------------------------------\n", wsh->packetlen, *oc, (char *)*data);


			return wsh->packetlen;
		}
		break;
	default:
		{
			/* invalid op code - protocol err .. */
			*oc = WSOC_CLOSE;
			return ws_close(wsh, WS_PROTO_ERR);
		}
		break;
	}
}