Esempio n. 1
0
int main()
{
  /* Initialize the configuration */
  config_init(&cfg);

  /* Load the file */
  printf("loading [sample.cfg]..");
  if (!config_read_file(&cfg, "sample.cfg"))
    printf("failed\n");
  else
  {
    printf("ok\n");
    
    /* Display the "values" array */
    printf("display \"values\"..");
    config_setting_t *array = config_lookup(&cfg, "values");
    if (!array)
      printf("failed\n");
    else
    {
      long value1,value2;
      value1 = config_setting_get_int_elem(array, 0);
      value2 = config_setting_get_int_elem(array, 1);
      printf("[%lu %lu]..ok\n", value1, value2);

      printf("Done!\n");
    }

  }

  /* Free the configuration */
  config_destroy(&cfg);

  return 0;
}
Esempio n. 2
0
/**
 * Load uint16 array.
 * @param[in] option Configuration option.
 * @param[in,out] array Resulting array.
 * @return <0 - error. 0 - success. >0 - not found.
 */
static int zcfg_load_uint16_array(const config_setting_t *option, UT_array *array)
{
    utarray_init(array, &ut_uint16_icd);

    if (!option) {
        return 1;
    }

    if (CONFIG_TYPE_ARRAY != option->type) {
        return -1;
    }

    int count = config_setting_length(option);

    for (int i = 0; i < count; i++) {
        int item = config_setting_get_int_elem(option, i);

        if ((item < 0) || (item > UINT16_MAX)) {
            ZLOG(LOG_ERR, "config:%s:%s: invalid port: %d", option->parent->name, option->name, item);
            utarray_done(array);
            return -1;
        }

        uint16_t port = (uint16_t) item;
        utarray_push_back(array, &port);
    }

    if (utarray_len(array)) {
        utarray_sort(array, uint16_cmp);
    }

    return 0;
}
Esempio n. 3
0
/**
 * Attempt to create a global channel from the channel config
 * @param chan: Channel list
 * @param tmp_chan: Temporary channel data
 * @param i: Index
 * @return True on success or false on failure
 */
bool channel_read_sub(config_setting_t *chan, struct Channel *tmp_chan, uint8 i) {
	config_setting_t  *group_list = NULL;
	int delay = 1000, autojoin = 0, leave = 1, chat = 1, color_override = 0,
		self_notif = 1, join_notif = 0, leave_notif = 0;
	int type = CHAN_TYPE_PUBLIC, group_count = 0;
	const char *name = NULL, *password = NULL, *alias = NULL, *color_str = "Default", *type_str = NULL;

	if (tmp_chan == NULL)
		return false;

	if (!config_setting_lookup_string(chan, "name", &name)) {
		ShowError("Please input channel 'name' at '%s' line '%d'! Skipping...\n", chan->file, chan->line);
		return false;
	}
	if (config_setting_lookup_string(chan, "type", &type_str) && !script_get_constant(type_str, &type)) {
		ShowError("Invalid channel type %s at '%s' line '%d'! Skipping...\n", type_str, chan->file, chan->line);
		return false;
	}
	config_setting_lookup_string(chan, "password", &password);
	config_setting_lookup_string(chan, "alias", &alias);
	config_setting_lookup_string(chan, "color", &color_str);
	config_setting_lookup_int(chan, "delay", &delay);
	config_setting_lookup_bool(chan, "autojoin", &autojoin);
	config_setting_lookup_bool(chan, "leave", &leave);
	config_setting_lookup_bool(chan, "chat", &chat);
	config_setting_lookup_bool(chan, "color_override", &color_override);
	config_setting_lookup_bool(chan, "self_notif", &self_notif);
	config_setting_lookup_bool(chan, "join_notif", &join_notif);
	config_setting_lookup_bool(chan, "leave_notif", &leave_notif);

	safestrncpy(tmp_chan->name,name+1,sizeof(tmp_chan->name));
	if (password)
		safestrncpy(tmp_chan->pass,password,sizeof(tmp_chan->pass));
	else
		tmp_chan->pass[0] = '\0';
	safestrncpy(tmp_chan->alias,alias?alias:name,sizeof(tmp_chan->alias));
	tmp_chan->msg_delay = delay;
	tmp_chan->type = (enum Channel_Type)type;
	tmp_chan->color = channel_getColor(color_str);

	tmp_chan->opt = (autojoin ? CHAN_OPT_AUTOJOIN : 0) |
		(leave ? CHAN_OPT_CAN_LEAVE : 0) |
		(chat ? CHAN_OPT_CAN_CHAT : 0) |
		(color_override ? CHAN_OPT_COLOR_OVERRIDE : 0) |
		(self_notif ? CHAN_OPT_ANNOUNCE_SELF : 0) |
		(join_notif ? CHAN_OPT_ANNOUNCE_JOIN : 0) |
		(leave_notif ? CHAN_OPT_ANNOUNCE_LEAVE : 0);

	if ((group_list = config_setting_get_member(chan, "groupid")) && (group_count = config_setting_length(group_list)) > 0) {
		int j;
		CREATE(tmp_chan->groups, unsigned short, group_count);
		tmp_chan->group_count = group_count;
		for (j = 0; j < group_count; j++) {
			int groupid = config_setting_get_int_elem(group_list, j);
			tmp_chan->groups[j] = groupid;
		}
	}
Esempio n. 4
0
/**
 * Load uint16 array from config.
 * @param[in] cfg Configuration option.
 * @param[in] option Option name.
 * @param[in,out] array Resulting array.
 * @return Zero on success.
 */
static int load_uint16_list(const config_setting_t *cfg, const char *option, UT_array *array)
{
    config_setting_t *cfg_list = config_setting_get_member(cfg, option);

    if (!cfg_list) {
        ZERO_LOG(LOG_ERR, "config: missing %s entry", option);
        return 0;
    }

    if (config_setting_type(cfg_list) != CONFIG_TYPE_LIST) {
        ZERO_LOG(LOG_ERR, "config: invalid %s entry", option);
        return -1;
    }

    int count = config_setting_length(cfg_list);

    if (0 >= count) {
        return 0;
    }

    utarray_init(array, &ut_uint16_icd);

    for (int i = 0; i < count; i++) {
        int entry = config_setting_get_int_elem(cfg_list, i);

        if (!entry) {
            ZERO_LOG(LOG_ERR, "config: failed to get next %s record", option);
            continue;
        }

        if (entry < UINT16_MAX) {
            uint16_t port = entry;
            utarray_push_back(array, &port);
            continue;
        }

        // if we here, then entry is invalid
        ZERO_LOG(LOG_ERR, "config: invalid %s item: %d", option, entry);
        utarray_done(array);
        return -1;
    }

    utarray_sort(array, uint16_cmp);

    return 0;
}
Esempio n. 5
0
int config_get_int_elem(config_t *config, char *setting, int element, int initial)
{
	int value = 0;
	config_setting_t *config_setting = config_lookup(config,setting);

	PRINT_SETTING;
	if (config_setting == NULL)
	{
		PRINT_NOT_FOUND;
		value = initial;
	}
	else
	{
		value = config_setting_get_int_elem(config_setting,element);
	}

	PRINT_VALUE_NUM;

	return value;
}
Esempio n. 6
0
static int ioctl_get_hwaddr(int d, int request, ...) {
	assert(request == SIOCGIFHWADDR);

	va_list ap;
	va_start(ap, request);
	struct ifreq *ifreq = va_arg(ap, struct ifreq *);
	va_end(ap);

	int ret = real_ioctl(d, request, ifreq);
	if (ret != 0) {
		return ret;
	}

	config_setting_t *mac_array = mac_array_for_if(ifreq->ifr_name);
	if (mac_array == NULL) return ret;
	for (int i = 0; i < config_setting_length(mac_array); i++) {
		int val = config_setting_get_int_elem(mac_array, i);
		if (val != -1) ifreq->ifr_hwaddr.sa_data[i] = val;
	}

	return ret;
}
/*
 *Parsea la configuracion y obtiene los grupos
 *que estan inhabilitados para crear o eliminar directorios
 */
Ruta_t* obtenerUsuariosInhabilitados( config_t* cf, Ruta_t* estructura_ruta){


    const config_setting_t *usuarios;
	
    //formo la ruta que uso en la config
    char tag_ruta_usuarios[4+4+4+24] = "confRuta";
    char aux[3];
    sprintf(aux, "%d",estructura_ruta->id_ruta);
    strncat(tag_ruta_usuarios, aux, 3);
    strncat(tag_ruta_usuarios, ".usuarios_deshabilitados", 24);
    
	//Obtengo los usuarios parseados
	usuarios = config_lookup(cf, tag_ruta_usuarios);
	//obtengo la cantidad de usuarios
	estructura_ruta->usuarios_cantidad = config_setting_length(usuarios);
    
	//Agrego los usuarios del archivo
	for (int n = 0; n < estructura_ruta->usuarios_cantidad ; n++)
		estructura_ruta->usuarios[n] = ((int) config_setting_get_int_elem(usuarios, n));
	
	return estructura_ruta;

}//obtenerUsuariosInhabilitados
Esempio n. 8
0
void core_main() {
	PRINT_IMPORTANT("Entered");

	register_to_signal(SIGRTMIN);

	sem_init(&control_serial_sem, 0, 1); //TODO remove after gen_control_serial_num() converted to RNG

	signal(SIGINT, core_termination_handler); //register termination handler

	int status;
	int i, j, k;
	metadata_element *list_elem;
	int list_num;
	metadata_element *elem;
	metadata_element *ip_elem;
	uint32_t ip_num;

	//######################################################################
	overall = (struct fins_overall *) secure_malloc(sizeof(struct fins_overall));
	sem_init(&overall->sem, 0, 1);

	//######################################################################
	overall->envi = (struct envi_record *) secure_malloc(sizeof(struct envi_record));

	PRINT_IMPORTANT("loading environment");
	metadata *meta_envi = (metadata *) secure_malloc(sizeof(metadata));
	metadata_create(meta_envi);

	status = config_read_file(meta_envi, "envi.cfg");
	if (status == META_FALSE) {
		PRINT_ERROR("%s:%d - %s\n", config_error_file(meta_envi), config_error_line(meta_envi), config_error_text(meta_envi));
		metadata_destroy(meta_envi);
		PRINT_ERROR("todo error");
		exit(-1);
	}

	//############# if_list
	PRINT_IMPORTANT("interface list");
	overall->envi->if_list = list_create(MAX_INTERFACES);

	list_elem = config_lookup(meta_envi, "environment.interfaces");
	if (list_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	list_num = config_setting_length(list_elem);

	uint32_t if_index;
	uint8_t *name;
	uint64_t mac;
	uint32_t type;
	uint32_t if_status;
	uint32_t mtu;
	uint32_t flags;

	struct if_record *ifr;

	for (i = 0; i < list_num; i++) {
		elem = config_setting_get_elem(list_elem, i);
		if (elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "index", (int *) &if_index);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_string(elem, "name", (const char **) &name);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int64(elem, "mac", (long long *) &mac);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "type", (int *) &type);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "status", (int *) &if_status);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "mtu", (int *) &mtu);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "flags", (int *) &flags);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		//#############
		ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index);
		if (ifr == NULL) {
			ifr = (struct if_record *) secure_malloc(sizeof(struct if_record));
			ifr->index = if_index;
			strcpy((char *) ifr->name, (char *) name);
			ifr->mac = mac;
			ifr->type = (uint16_t) type;

			ifr->status = (uint8_t) if_status;
			ifr->mtu = mtu;
			ifr->flags = flags;

			ifr->addr_list = list_create(MAX_FAMILIES);

			if (list_has_space(overall->envi->if_list)) {
				list_append(overall->envi->if_list, ifr);
			} else {
				//TODO error
				PRINT_ERROR("todo error");
				exit(-1);
			}

			if (flags & IFF_LOOPBACK) {
				overall->envi->if_loopback = ifr;
			}
		} else {
			PRINT_ERROR("todo error");
			exit(-1);
		}
	}

	//############# if_main
	PRINT_IMPORTANT("main interface");
	uint32_t if_main;

	status = config_lookup_int(meta_envi, "environment.main_interface", (int *) &if_main);
	if (status == META_FALSE) {
		PRINT_ERROR("todo error");
		exit(-1);
	}

	overall->envi->if_main = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_main);
	if (overall->envi->if_main == NULL) {
		PRINT_ERROR("todo");
	}

	//############# addr_list
	PRINT_IMPORTANT("address list");
	//overall->envi->addr_list = list_create(MAX_INTERFACES * MAX_FAMILIES); //TODO use?

	list_elem = config_lookup(meta_envi, "environment.addresses");
	if (list_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	list_num = config_setting_length(list_elem);

	uint32_t family; //atm only AF_INET, but eventually also AF_INET6
	uint32_t ip[4]; //SIOCGIFADDR //ip
	uint32_t mask[4]; //SIOCGIFNETMASK //mask
	uint32_t gw[4]; //? //(ip & mask) | 1;
	uint32_t bdc[4]; //SIOCGIFBRDADDR //(ip & mask) | ~mask
	uint32_t dst[4]; //SIOCGIFDSTADDR //dst

	struct addr_record *addr;

	for (i = 0; i < list_num; i++) {
		elem = config_setting_get_elem(list_elem, i);
		if (elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "if_index", (int *) &if_index);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "family", (int *) &family);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		ip_elem = config_setting_get_member(elem, "ip");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			ip[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "mask");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			mask[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "gw");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			gw[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "bdc");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			bdc[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "dst");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			dst[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		//############
		ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index);
		if (ifr != NULL) {
			if (ifr->flags & IFF_RUNNING) {
				if (family == AF_INET) {
					addr = (struct addr_record *) list_find(ifr->addr_list, addr_is_v4);
				} else {
					addr = (struct addr_record *) list_find(ifr->addr_list, addr_is_v6);
				}

				if (addr == NULL) {
					addr = (struct addr_record *) secure_malloc(sizeof(struct addr_record));
					addr->if_index = if_index;
					addr->family = AF_INET;

					if (family == AF_INET) {
						addr4_set_addr(&addr->ip, IP4_ADR_P2H(ip[0], ip[1], ip[2],ip[3]));
						addr4_set_addr(&addr->mask, IP4_ADR_P2H(mask[0], mask[1], mask[2],mask[3]));
						addr4_set_addr(&addr->gw, IP4_ADR_P2H(gw[0], gw[1], gw[2], gw[3]));
						addr4_set_addr(&addr->bdc, IP4_ADR_P2H(bdc[0], bdc[1], bdc[2], bdc[3]));
						addr4_set_addr(&addr->dst, IP4_ADR_P2H(dst[0], dst[1], dst[2], dst[3]));
					} else if (family == AF_INET6) {
						//TODO
						//addr_set_addr6(&addr->ip, ip);
						PRINT_ERROR("todo");
					} else {
						//TODO error?
						PRINT_ERROR("todo error");
						exit(-1);
					}

					if (list_has_space(ifr->addr_list)) {
						list_append(ifr->addr_list, addr);
					} else {
						//TODO error
						PRINT_ERROR("todo error");
						exit(-1);
					}
				} else {
					//TODO error
					PRINT_ERROR("todo: replace or add new?");
				}
			} else {
				//TODO error
				PRINT_ERROR("todo: decide just drop or add?");
			}
		} else {
			//TODO error
			PRINT_ERROR("todo error");
			exit(-1);
		}
	}

	//############# route_list
	PRINT_IMPORTANT("route list");
	overall->envi->route_list = list_create(MAX_ROUTES);

	list_elem = config_lookup(meta_envi, "environment.routes");
	if (list_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	list_num = config_setting_length(list_elem);

	uint32_t metric; //SIOCGIFMETRIC
	uint32_t timeout;
	//struct timeval route_stamp;

	struct route_record *route;

	for (i = 0; i < list_num; i++) {
		elem = config_setting_get_elem(list_elem, i);
		if (elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "if_index", (int *) &if_index);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "family", (int *) &family);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		ip_elem = config_setting_get_member(elem, "dst");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			dst[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "mask");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			mask[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "gw");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			gw[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}
		////ip = IP4_ADR_P2H(192,168,1,5);

		status = config_setting_lookup_int(elem, "metric", (int *) &metric);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "timeout", (int *) &timeout);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		//############
		ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index);
		if (ifr != NULL) {
			if (ifr->flags & IFF_RUNNING) {
				route = (struct route_record *) secure_malloc(sizeof(struct route_record));
				route->if_index = if_index;
				route->family = family;

				if (family == AF_INET) {
					addr4_set_addr(&route->dst, IP4_ADR_P2H(dst[0], dst[1], dst[2], dst[3]));
					addr4_set_addr(&route->mask, IP4_ADR_P2H(mask[0], mask[1], mask[2],mask[3]));
					addr4_set_addr(&route->gw, IP4_ADR_P2H(gw[0], gw[1], gw[2], gw[3]));
					//addr4_set_addr(&route->ip, IP4_ADR_P2H(ip[0], ip[1], ip[2],ip[3]));
				} else if (family == AF_INET6) {
					//TODO
					//addr_set_addr6(&route->ip, ip);
				} else {
					//TODO error?
				}

				route->metric = metric;
				route->timeout = timeout;

				if (list_has_space(overall->envi->route_list)) {
					list_append(overall->envi->route_list, route);
				} else {
					//TODO error
					PRINT_ERROR("todo error");
					exit(-1);
				}
			} else {
				//TODO error
				PRINT_ERROR("todo: decide just drop or add?");
			}
		}
	}
	metadata_destroy(meta_envi);

	//######################################################################
	PRINT_IMPORTANT("loading stack");
	metadata *meta_stack = (metadata *) secure_malloc(sizeof(metadata));
	metadata_create(meta_stack);

	status = config_read_file(meta_stack, "stack.cfg");
	if (status == META_FALSE) {
		PRINT_ERROR("%s:%d - %s\n", config_error_file(meta_stack), config_error_line(meta_stack), config_error_text(meta_stack));
		metadata_destroy(meta_stack);
		PRINT_ERROR("todo error");
		exit(-1);
	}

	//############# module_list
	PRINT_IMPORTANT("module list");
	overall->lib_list = list_create(MAX_MODULES);
	memset(overall->modules, 0, MAX_MODULES * sizeof(struct fins_module *));
	overall->admin_list = list_create(MAX_MODULES);

	uint8_t base_path[100];
	memset((char *) base_path, 0, 100);
	strcpy((char *) base_path, ".");

	metadata_element *mods_elem = config_lookup(meta_stack, "stack.modules");
	if (mods_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	int mods_num = config_setting_length(mods_elem);

	metadata_element *mod_elem;
	uint32_t mod_id;
	uint8_t *mod_lib;
	uint8_t *mod_name;
	metadata_element *flows_elem;
	uint32_t mod_flows[MAX_MOD_FLOWS];
	uint32_t mod_flows_num;
	metadata_element *mod_params;
	metadata_element *mod_admin;

	struct fins_library *library;
	struct fins_module *module;

	for (i = 0; i < mods_num; i++) {
		mod_elem = config_setting_get_elem(mods_elem, i);
		if (mod_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(mod_elem, "id", (int *) &mod_id);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_string(mod_elem, "lib", (const char **) &mod_lib);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_string(mod_elem, "name", (const char **) &mod_name);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		flows_elem = config_setting_get_member(mod_elem, "flows");
		if (flows_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		mod_flows_num = config_setting_length(flows_elem);

		for (j = 0; j < mod_flows_num; j++) {
			mod_flows[j] = (uint32_t) config_setting_get_int_elem(flows_elem, j);
		}

		mod_params = config_setting_get_member(mod_elem, "params");
		if (mod_params == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		mod_admin = config_setting_get_member(mod_elem, "admin");
		PRINT_DEBUG("admin=%u", mod_admin != NULL)

		//############
		library = (struct fins_library *) list_find1(overall->lib_list, lib_name_test, mod_lib);
		if (library == NULL) {
			library = library_load(mod_lib, base_path);
			if (library == NULL) {
				PRINT_ERROR("todo error");
				exit(-1);
			}

			if (list_has_space(overall->lib_list)) {
				list_append(overall->lib_list, library);
			} else {
				PRINT_ERROR("todo error");
				exit(-1);
			}
		}

		module = library->create(i, mod_id, mod_name);
		if (module == NULL) {
			//TODO error
			PRINT_ERROR("todo error");
			exit(-1);
		}
		library->num_mods++;

		//TODO move flow to update? or links here?
		status = module->ops->init(module, mod_flows_num, mod_flows, mod_params, overall->envi); //TODO merge init into create?
		if (status != 0) {
			overall->modules[i] = module;

			if (mod_admin != NULL) {
				list_append(overall->admin_list, module);
			}
		} else {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		//free(mod_lib); //don't free, string from libconfig points to metadata memory
		//free(mod_name);
	}

	//############# admin_list //TODO change to admin_list?
	//list_for_each(overall->admin_list, register_all);
	list_for_each1(overall->admin_list, assign_overall, overall);

	//############# linking_list
	PRINT_IMPORTANT("link list");
	overall->link_list = list_create(MAX_TABLE_LINKS);

	metadata_element *links_elem = config_lookup(meta_stack, "stack.links");
	if (links_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	int links_num = config_setting_length(links_elem);

	metadata_element *link_elem;
	uint32_t link_id;
	uint32_t link_src;
	metadata_element *dsts_elem;
	uint32_t link_dsts[MAX_MODULES];
	int link_dsts_num;

	struct link_record *link;

	for (i = 0; i < links_num; i++) {
		link_elem = config_setting_get_elem(links_elem, i);
		if (link_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(link_elem, "id", (int *) &link_id);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(link_elem, "src", (int *) &link_src);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		dsts_elem = config_setting_get_member(link_elem, "dsts");
		if (dsts_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		link_dsts_num = config_setting_length(dsts_elem);

		for (j = 0; j < link_dsts_num; j++) {
			link_dsts[j] = (uint32_t) config_setting_get_int_elem(dsts_elem, j);
		}

		//############
		link = (struct link_record *) secure_malloc(sizeof(struct link_record));
		link->id = link_id;

		//module = (struct fins_module *) list_find1(overall->envi->module_list, mod_id_test, &link_src);
		link->src_index = -1;
		for (j = 0; j < MAX_MODULES; j++) {
			if (overall->modules[j] != NULL && overall->modules[j]->id == link_src) {
				link->src_index = overall->modules[j]->index;
			}
		}
		if (link->src_index == -1) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		link->dsts_num = link_dsts_num;
		for (j = 0; j < link_dsts_num; j++) {
			//module = (struct fins_module *) list_find1(overall->envi->module_list, mod_id_test, &link_dsts[j]);
			link->dsts_index[j] = -1;
			for (k = 0; k < MAX_MODULES; k++) {
				if (overall->modules[k] != NULL && overall->modules[k]->id == link_dsts[j]) {
					link->dsts_index[j] = overall->modules[k]->index;
				}
			}
			if (link->dsts_index[j] == (uint32_t) -1) {
				PRINT_ERROR("todo error");
				exit(-1);
			}
		}

		if (list_has_space(overall->link_list)) {
			list_append(overall->link_list, link);
		} else {
			//TODO error
			PRINT_ERROR("todo error");
			exit(-1);
		}
	}
	metadata_destroy(meta_stack);

	//######################################################################
	PRINT_IMPORTANT("update modules");
	//send out subset of linking table to each module as update
	//TODO table subset update

	struct linked_list *link_subset_list;
	metadata *meta_update;
	struct finsFrame *ff_update;

	for (i = 0; i < MAX_MODULES; i++) {
		if (overall->modules[i] != NULL) {
			link_subset_list = list_filter1(overall->link_list, link_involved_test, &overall->modules[i]->index, link_clone); //TODO is mem leak
			PRINT_IMPORTANT("i=%d, link_subset_list=%p, len=%d", i, link_subset_list, link_subset_list->len);

			meta_update = (metadata *) secure_malloc(sizeof(metadata));
			metadata_create(meta_update);

			//TODO decide on metadata params?
			//uint32_t host_ip = IP4_ADR_P2H(192,168,1,8);
			//secure_metadata_writeToElement(meta_update, "send_src_ip", &host_ip, META_TYPE_INT32);

			ff_update = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame));
			ff_update->dataOrCtrl = FF_CONTROL;
			ff_update->destinationID = i;
			ff_update->metaData = meta_update;

			ff_update->ctrlFrame.sender_id = 0;
			ff_update->ctrlFrame.serial_num = gen_control_serial_num();
			ff_update->ctrlFrame.opcode = CTRL_SET_PARAM;
			ff_update->ctrlFrame.param_id = MOD_SET_PARAM_LINKS;

			ff_update->ctrlFrame.data_len = sizeof(struct linked_list);
			ff_update->ctrlFrame.data = (uint8_t *) link_subset_list;

			module_to_switch(overall->modules[0], ff_update);
		}
	}

	//############ say by this point envi var completely init'd
	//assumed always connect/init to switch first

	pthread_attr_t attr;
	pthread_attr_init(&attr);

	PRINT_IMPORTANT("modules: run");

	for (i = 0; i < MAX_MODULES; i++) {
		if (overall->modules[i] != NULL) {
			overall->modules[i]->ops->run(overall->modules[i], &attr);
		}
	}

	//############ mini test
	//sleep(5);
	char recv_data[4000];

	//while (1) {
	PRINT_IMPORTANT("waiting...");
	gets(recv_data);

	if (0) {
		metadata *meta = (metadata *) secure_malloc(sizeof(metadata));
		metadata_create(meta);

		uint32_t host_ip = IP4_ADR_P2H(192,168,1,8);
		uint32_t host_port = 55454;
		uint32_t dst_ip = IP4_ADR_P2H(192,168,1,3);
		uint32_t dst_port = 44444;
		uint32_t ttl = 64;
		uint32_t tos = 64;

		secure_metadata_writeToElement(meta, "send_src_ip", &host_ip, META_TYPE_INT32);
		secure_metadata_writeToElement(meta, "send_src_port", &host_port, META_TYPE_INT32);
		secure_metadata_writeToElement(meta, "send_dst_ip", &dst_ip, META_TYPE_INT32);
		secure_metadata_writeToElement(meta, "send_dst_port", &dst_port, META_TYPE_INT32);
		secure_metadata_writeToElement(meta, "send_ttl", &ttl, META_TYPE_INT32);
		secure_metadata_writeToElement(meta, "send_tos", &tos, META_TYPE_INT32);

		struct finsFrame *ff = (struct finsFrame *) secure_malloc(sizeof(struct finsFrame));
		ff->dataOrCtrl = FF_DATA;
		ff->destinationID = 1;
		ff->metaData = meta;

		ff->dataFrame.directionFlag = DIR_UP;
		ff->dataFrame.pduLength = 10;
		ff->dataFrame.pdu = (uint8_t *) secure_malloc(10);

		PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff, meta, overall->modules[0]->name, overall->modules[1]->name);
		module_to_switch(overall->modules[0], ff);
	}

	if (0) {
		PRINT_DEBUG("Sending ARP req");

		metadata *meta_req = (metadata *) secure_malloc(sizeof(metadata));
		metadata_create(meta_req);

		uint32_t dst_ip = IP4_ADR_P2H(192, 168, 1, 1);
		//uint32_t dst_ip = IP4_ADR_P2H(172, 31, 54, 169);
		uint32_t src_ip = IP4_ADR_P2H(192, 168, 1, 20);
		//uint32_t src_ip = IP4_ADR_P2H(172, 31, 50, 160);

		secure_metadata_writeToElement(meta_req, "dst_ip", &dst_ip, META_TYPE_INT32);
		secure_metadata_writeToElement(meta_req, "src_ip", &src_ip, META_TYPE_INT32);

		struct finsFrame *ff_req = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame));
		ff_req->dataOrCtrl = FF_CONTROL;
		ff_req->destinationID = 1; //arp
		ff_req->metaData = meta_req;

		ff_req->ctrlFrame.sender_id = 4; //ipv4
		ff_req->ctrlFrame.serial_num = gen_control_serial_num();
		ff_req->ctrlFrame.opcode = CTRL_EXEC;
		ff_req->ctrlFrame.param_id = 0; //EXEC_ARP_GET_ADDR;

		ff_req->ctrlFrame.data_len = 0;
		ff_req->ctrlFrame.data = NULL;

		PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff_req, meta_req, overall->modules[0]->name, overall->modules[1]->name);
		module_to_switch(overall->modules[0], ff_req);
	}

	if (0) {
		PRINT_DEBUG("Sending data");

		metadata *meta_req = (metadata *) secure_malloc(sizeof(metadata));
		metadata_create(meta_req);

		uint32_t ether_type = 0x0800; //ipv4
		if_index = 3; //wlan0
		uint32_t src_ip = IP4_ADR_P2H(192, 168, 1, 5); //wlan0
		uint32_t dst_ip = IP4_ADR_P2H(192, 168, 1, 1); //gw

		secure_metadata_writeToElement(meta_req, "send_ether_type", &ether_type, META_TYPE_INT32);
		secure_metadata_writeToElement(meta_req, "send_if_index", &if_index, META_TYPE_INT32);
		secure_metadata_writeToElement(meta_req, "send_src_ipv4", &src_ip, META_TYPE_INT32);
		secure_metadata_writeToElement(meta_req, "send_dst_ipv4", &dst_ip, META_TYPE_INT32);

		struct finsFrame *ff = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame));
		ff->dataOrCtrl = FF_DATA;
		ff->destinationID = 1; //arp
		ff->metaData = meta_req;

		ff->dataFrame.directionFlag = DIR_DOWN;
		ff->dataFrame.pduLength = 100;
		ff->dataFrame.pdu = (uint8_t *) secure_malloc(ff->dataFrame.pduLength);
		memset(ff->dataFrame.pdu, 59, ff->dataFrame.pduLength);

		PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff, meta_req, overall->modules[0]->name, overall->modules[1]->name);
		module_to_switch(overall->modules[0], ff);
	}

	if (0) {
		PRINT_DEBUG("Sending data");

		metadata *meta = (metadata *) secure_malloc(sizeof(metadata));
		metadata_create(meta);

		uint32_t src_ip = IP4_ADR_P2H(192, 168, 1, 5); //wlan0
		uint32_t src_port = 6666;
		uint32_t dst_ip = IP4_ADR_P2H(192, 168, 1, 1); //gw
		uint32_t dst_port = 5555;

		secure_metadata_writeToElement(meta, "send_src_ipv4", &src_ip, META_TYPE_INT32);
		secure_metadata_writeToElement(meta, "send_src_port", &src_port, META_TYPE_INT32);
		secure_metadata_writeToElement(meta, "send_dst_ipv4", &dst_ip, META_TYPE_INT32);
		secure_metadata_writeToElement(meta, "send_dst_port", &dst_port, META_TYPE_INT32);

		uint32_t dst_index = 4;
		struct finsFrame *ff = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame));
		ff->dataOrCtrl = FF_DATA;
		ff->destinationID = dst_index; //arp
		ff->metaData = meta;

		ff->dataFrame.directionFlag = DIR_DOWN;
		ff->dataFrame.pduLength = 10;
		ff->dataFrame.pdu = (uint8_t *) secure_malloc(ff->dataFrame.pduLength);
		memset(ff->dataFrame.pdu, 65, ff->dataFrame.pduLength);

		PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff, meta, overall->modules[0]->name, overall->modules[dst_index]->name);
		module_to_switch(overall->modules[0], ff);
	}

	if (1) {
		PRINT_DEBUG("Sending data");

		metadata *meta = (metadata *) secure_malloc(sizeof(metadata));
		metadata_create(meta);

		uint32_t src_ip = IP4_ADR_P2H(192, 168, 1, 5); //wlan0
		uint32_t dst_ip = IP4_ADR_P2H(192, 168, 1, 1); //gw

		secure_metadata_writeToElement(meta, "send_src_ipv4", &src_ip, META_TYPE_INT32);
		secure_metadata_writeToElement(meta, "send_dst_ipv4", &dst_ip, META_TYPE_INT32);

		uint32_t dst_index = 4;
		struct finsFrame *ff = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame));
		ff->dataOrCtrl = FF_DATA;
		ff->destinationID = dst_index;
		ff->metaData = meta;

		ff->dataFrame.directionFlag = DIR_DOWN;
		ff->dataFrame.pduLength = 10;
		ff->dataFrame.pdu = (uint8_t *) secure_malloc(ff->dataFrame.pduLength);
		memset(ff->dataFrame.pdu, 65, ff->dataFrame.pduLength);

		PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff, meta, overall->modules[0]->name, overall->modules[dst_index]->name);
		module_to_switch(overall->modules[0], ff);
	}

	while (1)
		;

	sleep(5);
	PRINT_IMPORTANT("waiting...");
	char recv_data2[4000];
	gets(recv_data2);

	//############ terminating
	core_termination_handler(0);
}
Esempio n. 9
0
void core_main(uint8_t *envi_name, uint8_t *stack_name, uint32_t seed) {
	PRINT_IMPORTANT("Core Initiation: Starting ************");

#ifdef BUILD_FOR_ANDROID
	library_dummies();
#endif

	register_to_signal(SIGRTMIN);
	if (seed == DEFAULT_SEED_NUM) {
		srand((unsigned int) time(NULL));
	} else {
		srand(seed);
	}

	sem_init(&global_control_serial_sem, 0, 1); //TODO remove after gen_control_serial_num() converted to RNG

	signal(SIGINT, core_termination_handler); //register termination handler

	int status;
	int i, j, k;
	metadata_element *list_elem;
	int list_num;
	metadata_element *elem;
	metadata_element *ip_elem;
	uint32_t ip_num;

	//######################################################################
	overall = (struct fins_overall *) secure_malloc(sizeof(struct fins_overall));
	sem_init(&overall->sem, 0, 1);

	//######################################################################
	overall->envi = (struct envi_record *) secure_malloc(sizeof(struct envi_record));

	PRINT_IMPORTANT("########################## loading environment: '%s'", (char *) envi_name);
	metadata *meta_envi = (metadata *) secure_malloc(sizeof(metadata));
	metadata_create(meta_envi);

	status = config_read_file(meta_envi, (char *) envi_name);
	if (status == META_FALSE) {
		PRINT_ERROR("file='%s', %s:%d - %s\n", envi_name, config_error_file(meta_envi), config_error_line(meta_envi), config_error_text(meta_envi));
		metadata_destroy(meta_envi);
		PRINT_ERROR("todo error");
		exit(-1);
	}

	//############# if_list
	PRINT_IMPORTANT("############# Configuring List of Interfaces");
	overall->envi->if_list = list_create(MAX_INTERFACES);

	list_elem = config_lookup(meta_envi, "environment.interfaces");
	if (list_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	list_num = config_setting_length(list_elem);

	int32_t if_index;
	uint8_t *name;
	uint64_t mac;
	uint32_t mode;
	uint32_t mtu;
	uint32_t flags;

	struct if_record *ifr;

	for (i = 0; i < list_num; i++) {
		elem = config_setting_get_elem(list_elem, i);
		if (elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "index", (int *) &if_index);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_string(elem, "name", (const char **) &name);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int64(elem, "mac", (long long *) &mac);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "mode", (int *) &mode);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "mtu", (int *) &mtu);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "flags", (int *) &flags);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		//#############
		ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index);
		if (ifr == NULL) {
			ifr = (struct if_record *) secure_malloc(sizeof(struct if_record));
			ifr->index = if_index;
			strcpy((char *) ifr->name, (char *) name);
			ifr->mac = mac;

			ifr->mode = (uint8_t) mode;
			ifr->mtu = mtu;
			ifr->flags = flags;

			ifr->addr_list = list_create(MAX_FAMILIES);

			if (list_has_space(overall->envi->if_list)) {
				PRINT_IMPORTANT("Adding interface: ifr=%p, index=%u, name='%s', mac=0x%012llx", ifr, ifr->index, ifr->name, ifr->mac);
				list_append(overall->envi->if_list, ifr);
			} else {
				//TODO error
				PRINT_ERROR("todo error");
				exit(-1);
			}

			if (flags & IFF_LOOPBACK) {
				overall->envi->if_loopback = ifr;
			}
		} else {
			PRINT_ERROR("todo error");
			exit(-1);
		}
	}
	PRINT_IMPORTANT("if_list: list=%p, max=%u, len=%u", overall->envi->if_list, overall->envi->if_list->max, overall->envi->if_list->len);

	//############# if_loopback
	PRINT_IMPORTANT("############# Configuring Loopback Interface");
	if (overall->envi->if_loopback != NULL) {
		PRINT_IMPORTANT("loopback: name='%s', addr_list->len=%u", overall->envi->if_loopback->name, overall->envi->if_loopback->addr_list->len);
	} else {
		PRINT_WARN("todo error");
	}

	//############# if_main
	PRINT_IMPORTANT("############# Configuring Main Interface");
	uint32_t if_main;

	status = config_lookup_int(meta_envi, "environment.main_interface", (int *) &if_main);
	if (status == META_FALSE) {
		PRINT_ERROR("todo error");
		exit(-1);
	}

	overall->envi->if_main = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_main);
	if (overall->envi->if_main != NULL) {
		PRINT_IMPORTANT("main interface: name='%s', addr_list->len=%u", overall->envi->if_main->name, overall->envi->if_main->addr_list->len);
		if (!ifr_running_test(overall->envi->if_main)) {
			PRINT_WARN("!!!!Selected main interface is NOT running: name='%s', flagx->len=0x%x", overall->envi->if_main->name, overall->envi->if_main->flags);
		}
	} else {
		PRINT_WARN("todo error");
	}

	//############# addr_list
	PRINT_IMPORTANT("############# Configuring List of Host Addresses");
	//overall->envi->addr_list = list_create(MAX_INTERFACES * MAX_FAMILIES); //TODO use?

	list_elem = config_lookup(meta_envi, "environment.addresses");
	if (list_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	list_num = config_setting_length(list_elem);

	uint32_t family; //atm only AF_INET, but eventually also AF_INET6
	uint32_t ip[4]; //SIOCGIFADDR //ip
	uint32_t mask[4]; //SIOCGIFNETMASK //mask
	uint32_t gw[4]; //? //(ip & mask) | 1;
	uint32_t bdc[4]; //SIOCGIFBRDADDR //(ip & mask) | ~mask
	uint32_t dst[4]; //SIOCGIFDSTADDR //dst

	struct addr_record *addr;

	for (i = 0; i < list_num; i++) {
		elem = config_setting_get_elem(list_elem, i);
		if (elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "if_index", (int *) &if_index);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "family", (int *) &family);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		ip_elem = config_setting_get_member(elem, "ip");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			ip[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "mask");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			mask[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "gw");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			gw[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "bdc");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			bdc[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "dst");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			dst[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		//############
		ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index);
		if (ifr != NULL) {
			if (ifr_running_test(ifr)) {
				if (family == AF_INET) {
					addr = (struct addr_record *) list_find(ifr->addr_list, addr_is_v4);
				} else {
					addr = (struct addr_record *) list_find(ifr->addr_list, addr_is_v6);
				}

				if (addr == NULL) {
					addr = (struct addr_record *) secure_malloc(sizeof(struct addr_record));
					addr->if_index = if_index;
					addr->family = AF_INET;

					if (family == AF_INET) {
						addr4_set_ip(&addr->ip, IP4_ADR_P2H(ip[0], ip[1], ip[2],ip[3]));
						addr4_set_ip(&addr->mask, IP4_ADR_P2H(mask[0], mask[1], mask[2],mask[3]));
						addr4_set_ip(&addr->gw, IP4_ADR_P2H(gw[0], gw[1], gw[2], gw[3]));
						addr4_set_ip(&addr->bdc, IP4_ADR_P2H(bdc[0], bdc[1], bdc[2], bdc[3]));
						addr4_set_ip(&addr->dst, IP4_ADR_P2H(dst[0], dst[1], dst[2], dst[3]));
					} else if (family == AF_INET6) {
						//TODO
						//addr_set_addr6(&addr->ip, ip);
						PRINT_WARN("todo");
					} else {
						//TODO error?
						PRINT_ERROR("todo error");
						exit(-1);
					}

					if (list_has_space(ifr->addr_list)) {
						PRINT_IMPORTANT(
								"Adding address: if_index=%d, family=%u, ip='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', bdc='%u.%u.%u.%u', dst='%u.%u.%u.%u'",
								if_index, family, ip[0], ip[1], ip[2], ip[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], bdc[0], bdc[1], bdc[2], bdc[3], dst[0], dst[1], dst[2], dst[3]);
						list_append(ifr->addr_list, addr);
					} else {
						//TODO error
						PRINT_ERROR("todo error");
						exit(-1);
					}
				} else {
					//TODO error
					PRINT_ERROR("todo: previous address found, replace or add new?");
				}
			} else {
				if (family == AF_INET) {
					PRINT_WARN(
							"Ignoring address, no active interface: if_index=%d, family=%u, ip='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', bdc='%u.%u.%u.%u', dst='%u.%u.%u.%u'",
							if_index, family, ip[0], ip[1], ip[2], ip[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], bdc[0], bdc[1], bdc[2], bdc[3], dst[0], dst[1], dst[2], dst[3]);
				} else if (family == AF_INET6) {
					//TODO
					PRINT_WARN("todo");
				} else {
					//TODO error?
					PRINT_ERROR("todo error");
					exit(-1);
				}
			}
		} else {
			//TODO error
			PRINT_ERROR("todo error");
			exit(-1);
		}
	}

	//############# route_list
	PRINT_IMPORTANT("############# Configuring List of Routes");
	overall->envi->route_list = list_create(MAX_ROUTES);

	list_elem = config_lookup(meta_envi, "environment.routes");
	if (list_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	list_num = config_setting_length(list_elem);

	uint32_t metric; //SIOCGIFMETRIC
	uint32_t timeout;
	//struct timeval route_stamp;

	struct route_record *route;

	for (i = 0; i < list_num; i++) {
		elem = config_setting_get_elem(list_elem, i);
		if (elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "if_index", (int *) &if_index);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "family", (int *) &family);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		ip_elem = config_setting_get_member(elem, "dst");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			dst[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "mask");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			mask[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "gw");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			gw[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		status = config_setting_lookup_int(elem, "metric", (int *) &metric);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "timeout", (int *) &timeout);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		//############
		ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index);
		if (ifr != NULL) {
			if (ifr_running_test(ifr)) {
				route = (struct route_record *) secure_malloc(sizeof(struct route_record));
				route->if_index = if_index;
				route->family = family;

				if (family == AF_INET) {
					addr4_set_ip(&route->dst, IP4_ADR_P2H(dst[0], dst[1], dst[2], dst[3]));
					addr4_set_ip(&route->mask, IP4_ADR_P2H(mask[0], mask[1], mask[2],mask[3]));
					addr4_set_ip(&route->gw, IP4_ADR_P2H(gw[0], gw[1], gw[2], gw[3]));
					//addr4_set_addr(&route->ip, IP4_ADR_P2H(ip[0], ip[1], ip[2],ip[3]));
				} else if (family == AF_INET6) {
					//TODO
					//addr_set_addr6(&route->ip, ip);
				} else {
					//TODO error?
				}

				route->metric = metric;
				route->timeout = timeout;

				if (list_has_space(overall->envi->route_list)) {
					PRINT_IMPORTANT( "Adding route: if_index=%d, family=%u, dst='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', metric=%u, timeout=%u",
							route->if_index, route->family, dst[0], dst[1], dst[2], dst[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], metric, timeout);
					list_append(overall->envi->route_list, route);
				} else {
					//TODO error
					PRINT_ERROR("todo error");
					exit(-1);
				}
			} else {
				if (family == AF_INET) {
					PRINT_WARN(
							"Ignoring route, no active interface: if_index=%d, family=%u, dst='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', metric=%u, timeout=%u",
							if_index, family, dst[0], dst[1], dst[2], dst[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], metric, timeout);
				} else if (family == AF_INET6) {
					//TODO
					PRINT_WARN("todo");
				} else {
					//TODO error?
					PRINT_ERROR("todo error");
				}
			}
		}
	}
	PRINT_IMPORTANT("route_list: list=%p, max=%u, len=%u", overall->envi->route_list, overall->envi->route_list->max, overall->envi->route_list->len);
	metadata_destroy(meta_envi);

	//######################################################################
	PRINT_IMPORTANT("########################## loading stack: '%s'", (char *) stack_name);
	metadata *meta_stack = (metadata *) secure_malloc(sizeof(metadata));
	metadata_create(meta_stack);

	status = config_read_file(meta_stack, (char *) stack_name);
	if (status == META_FALSE) {
		PRINT_ERROR("file='%s', %s:%d - %s\n", stack_name, config_error_file(meta_stack), config_error_line(meta_stack), config_error_text(meta_stack));
		metadata_destroy(meta_stack);
		PRINT_ERROR("todo error");
		exit(-1);
	}

	//############# module_list
	PRINT_IMPORTANT("############# Configuring List of Modules");
	overall->lib_list = list_create(MAX_MODULES);
	memset(overall->modules, 0, MAX_MODULES * sizeof(struct fins_module *));
	overall->admin_list = list_create(MAX_MODULES);
	struct linked_list *mt_list = list_create(MAX_MODULES);

	uint8_t base_path[100];
	memset((char *) base_path, 0, 100);
#ifdef BUILD_FOR_ANDROID
	strcpy((char *) base_path, FINS_TMP_ROOT);
	//strcpy((char *) base_path, ".");
#else
	strcpy((char *) base_path, ".");
#endif

	metadata_element *mods_elem = config_lookup(meta_stack, "stack.modules");
	if (mods_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	int mods_num = config_setting_length(mods_elem);

	metadata_element *mod_elem;
	uint32_t mod_id;
	uint8_t *mod_lib;
	uint8_t *mod_name;
	metadata_element *flows_elem;
	uint32_t mod_flows[MAX_MOD_FLOWS];
	uint32_t mod_flows_num;
	metadata_element *mod_params;
	metadata_element *mod_admin;

	struct fins_library *library;
	struct fins_module *module;
	struct fins_module_table *mt;

	for (i = 0; i < mods_num; i++) {
		mod_elem = config_setting_get_elem(mods_elem, i);
		if (mod_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(mod_elem, "id", (int *) &mod_id);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_string(mod_elem, "lib", (const char **) &mod_lib);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_string(mod_elem, "name", (const char **) &mod_name);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		flows_elem = config_setting_get_member(mod_elem, "flows");
		if (flows_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		mod_flows_num = config_setting_length(flows_elem);

		for (j = 0; j < mod_flows_num; j++) {
			mod_flows[j] = (uint32_t) config_setting_get_int_elem(flows_elem, j);
		}

		mod_params = config_setting_get_member(mod_elem, "params");
		if (mod_params == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		mod_admin = config_setting_get_member(mod_elem, "admin");
		PRINT_DEBUG("admin=%u", mod_admin != NULL);

		//############
		library = (struct fins_library *) list_find1(overall->lib_list, library_name_test, mod_lib);
		if (library == NULL) {
#ifdef BUILD_FOR_ANDROID
			library = library_fake_load(mod_lib, base_path);
#else
			//library = library_load(mod_lib, base_path);
			library = library_fake_load(mod_lib, base_path);
#endif
			if (library == NULL) {
				PRINT_ERROR("Failed in loading library: lib='%s', base_path='%s'", mod_lib, base_path);
				exit(-1);
			}

			if (list_has_space(overall->lib_list)) {
				PRINT_IMPORTANT("Adding library: library=%p, name='%s'", library, library->name);
				list_append(overall->lib_list, library);
			} else {
				PRINT_ERROR("Failed in init sequence, too many libraries: lib_list->len=%u", overall->lib_list->len);
				exit(-1);
			}
		}

		module = library->create(i, mod_id, mod_name);
		if (module == NULL) {
			//TODO error
			PRINT_ERROR("Failed to create module: library=%p, index=%u, id=%u, name='%s'", library, i, mod_id, mod_name);
			exit(-1);
		}
		library->num_mods++;

		//TODO move flow to update? or links here?
		status = module->ops->init(module, mod_params, overall->envi); //TODO merge init into create?
		if (status != 0) {
			overall->modules[i] = module;

			if (module->flows_max < mod_flows_num) {
				PRINT_ERROR("Loading module parameters failed, too many flows for this library: specified=%u, max=%u", mod_flows_num, module->flows_max);
				exit(-1);
			}

			mt = (struct fins_module_table *) secure_malloc(sizeof(struct fins_module_table));
			mt->flows_num = mod_flows_num;

			for (j = 0; j < mt->flows_num; j++) {
				mt->flows[j].link_id = mod_flows[j];
			}
			list_append(mt_list, mt);

			if (mod_admin != NULL) {
				PRINT_IMPORTANT("Adding admin module: module=%p, lib='%s', name='%s', id=%d, index=%u",
						module, module->lib, module->name, module->id, module->index);
				list_append(overall->admin_list, module);
			} else {
				PRINT_IMPORTANT("Adding module: module=%p, lib='%s', name='%s', id=%d, index=%u", module, module->lib, module->name, module->id, module->index);
			}
		} else {
			PRINT_ERROR("Initialization of module failed: module=%p, lib='%s', name='%s', flows_num=%u, flows=%p, params=%p, envi=%p",
					module, module->lib, module->name, mod_flows_num, mod_flows, mod_params, overall->envi);
			exit(-1);
		}

		//free(mod_lib); //don't free, string from libconfig points to metadata memory
		//free(mod_name);
	}

	//############# admin_list //TODO change to admin_list?
	list_for_each1(overall->admin_list, assign_overall, overall);

	//############# linking_list
	PRINT_IMPORTANT("############# Configuring Linking Table");
	overall->link_list = list_create(MAX_TABLE_LINKS);

	metadata_element *links_elem = config_lookup(meta_stack, "stack.links");
	if (links_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	int links_num = config_setting_length(links_elem);

	metadata_element *link_elem;
	uint32_t link_id;
	uint32_t link_src;
	metadata_element *dsts_elem;
	uint32_t link_dsts[MAX_MODULES];
	int link_dsts_num;

	struct link_record *link;

	for (i = 0; i < links_num; i++) {
		link_elem = config_setting_get_elem(links_elem, i);
		if (link_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(link_elem, "id", (int *) &link_id);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(link_elem, "src", (int *) &link_src);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		dsts_elem = config_setting_get_member(link_elem, "dsts");
		if (dsts_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		link_dsts_num = config_setting_length(dsts_elem);

		for (j = 0; j < link_dsts_num; j++) {
			link_dsts[j] = (uint32_t) config_setting_get_int_elem(dsts_elem, j);
		}

		//############
		link = (struct link_record *) secure_malloc(sizeof(struct link_record));
		link->id = link_id;

		//module = (struct fins_module *) list_find1(overall->envi->module_list, mod_id_test, &link_src);
		link->src_index = -1;
		for (j = 0; j < MAX_MODULES; j++) {
			if (overall->modules[j] != NULL && overall->modules[j]->id == link_src) {
				link->src_index = overall->modules[j]->index;
			}
		}
		if (link->src_index == -1) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		link->dsts_num = link_dsts_num;
		for (j = 0; j < link_dsts_num; j++) {
			//module = (struct fins_module *) list_find1(overall->envi->module_list, mod_id_test, &link_dsts[j]);
			link->dsts_index[j] = -1;
			for (k = 0; k < MAX_MODULES; k++) {
				if (overall->modules[k] != NULL && overall->modules[k]->id == link_dsts[j]) {
					link->dsts_index[j] = overall->modules[k]->index;
				}
			}
			if (link->dsts_index[j] == (uint32_t) -1) {
				PRINT_ERROR("todo error");
				exit(-1);
			}
		}

		if (list_has_space(overall->link_list)) {
			uint8_t buf[1000];
			uint8_t *pt = buf;
			int ret;
			int i;
			for (i = 0; i < link->dsts_num; i++) {
				ret = sprintf((char *) pt, "%u, ", link->dsts_index[i]);
				pt += ret;
			}
			*pt = '\0';

			PRINT_IMPORTANT("Adding link: link=%p, id=%u, src_index=%u, dsts_num=%u, ['%s']", link, link->id, link->src_index, link->dsts_num, buf);
			list_append(overall->link_list, link);
		} else {
			//TODO error
			PRINT_ERROR("todo error");
			exit(-1);
		}
	}
	metadata_destroy(meta_stack);

	//######################################################################
	PRINT_IMPORTANT("############# Updating modules with correct flows & links");
	//send out subset of linking table to each module as update
	//TODO table subset update

	metadata *meta_update;
	struct finsFrame *ff_update;

	for (i = 0; i < MAX_MODULES; i++) {
		if (overall->modules[i] != NULL) {
			mt = (struct fins_module_table *) list_remove_front(mt_list);
			mt->link_list = list_filter1(overall->link_list, link_src_test, &overall->modules[i]->index, link_clone); //was link_involved_test, decide which better?
			PRINT_IMPORTANT("Module link table subset: name='%s' index=%d, link_list=%p, len=%d",
					overall->modules[i]->name, i, mt->link_list, mt->link_list->len);

			for (j = 0; j < mt->flows_num; j++) {
				mt->flows[j].link = (struct link_record *) list_find1(mt->link_list, link_id_test, &mt->flows[j].link_id);
			}

//#ifdef DEBUG
			uint8_t buf[1000];
			uint8_t *pt = buf;
			int ret;
			for (j = 0; j < mt->flows_num; j++) {
				ret = sprintf((char *) pt, "%u (%p), ", mt->flows[j].link_id, mt->flows[j].link);
				pt += ret;
			}
			*pt = '\0';
			PRINT_IMPORTANT("Module flows: num=%u, ['%s']", mt->flows_num, buf);

			list_for_each(mt->link_list, link_print);
//#endif

			meta_update = (metadata *) secure_malloc(sizeof(metadata));
			metadata_create(meta_update);

			ff_update = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame));
			ff_update->dataOrCtrl = FF_CONTROL;
			ff_update->destinationID = i;
			ff_update->metaData = meta_update;

			ff_update->ctrlFrame.sender_id = 0;
			ff_update->ctrlFrame.serial_num = gen_control_serial_num();
			ff_update->ctrlFrame.opcode = CTRL_SET_PARAM;
			ff_update->ctrlFrame.param_id = MOD_SET_PARAM_DUAL;

			ff_update->ctrlFrame.data_len = sizeof(struct fins_module_table);
			ff_update->ctrlFrame.data = (uint8_t *) mt;

			module_to_switch(overall->modules[0], ff_update);
			//module_set_param_dual(overall->modules[i], ff_update);
		}
	}
	list_free(mt_list, free);

	//############ say by this point envi var completely init'd
	//assumed always connect/init to switch first

	pthread_attr_init(&overall->attr);
	pthread_attr_setdetachstate(&overall->attr, PTHREAD_CREATE_JOINABLE);

	PRINT_IMPORTANT("############# Calling run() for modules");

	for (i = 0; i < MAX_MODULES; i++) {
		if (overall->modules[i] != NULL) {
			overall->modules[i]->ops->run(overall->modules[i], &overall->attr);
		}
	}

	PRINT_IMPORTANT("Core Initiation: Finished ************");
}
Esempio n. 10
0
int centernode_config (centernode_t *cn)
{
    const char *tmp = 0;
    config_setting_t *item = 0;

#define CONFIGITEM(x, config, path) \
    do {\
        if ((item = config_lookup(config, path)) == 0) {\
            fprintf(stderr, "Not found configuration item: [%s].\n", path);\
            return -1;\
        }\
        if ((tmp = config_setting_get_string(item))) {\
            memset(x, 0, sizeof(x));\
            memcpy(x, tmp, strlen(tmp));\
        }\
    } while (0)
    CONFIGITEM(cn->mongoString,cn->config, "system.mongo.string");
    CONFIGITEM(cn->nodeid,     cn->config, "system.node.id");
    CONFIGITEM(cn->homepath,   cn->config, "system.node.home");
    CONFIGITEM(cn->dbhost,     cn->config, "system.db.host");
    CONFIGITEM(cn->dbname,     cn->config, "system.db.name");
    CONFIGITEM(cn->dbuser,     cn->config, "system.db.username");
    CONFIGITEM(cn->dbpasswd,   cn->config, "system.db.passwd");
    CONFIGITEM(cn->rdb_host,   cn->config, "system.db.redis.host");
    CONFIGITEM(cn->rdb_pswd,   cn->config, "system.db.redis.password");
#ifdef REDISBAK
    CONFIGITEM(cn->rdb_bakhost,   cn->config, "system.db.redisbak.host");
    CONFIGITEM(cn->rdb_bakpswd,   cn->config, "system.db.redisbak.password");
#endif

#undef CONFIGITEM

#define CONFIGITEM(x, config, path) \
    do {\
        if (!(item = config_lookup(config, path))) {\
            fprintf(stderr, "Not found configuration item: [%s].\n", path);\
            return -1;\
        }\
        x = config_setting_get_int(item);\
    } while (0)
    CONFIGITEM(cn->threads,  cn->config, "system.node.threads");
    CONFIGITEM(cn->syncdelay,  cn->config, "system.node.sync-cycle");
    CONFIGITEM(cn->dbport,     cn->config, "system.db.port");
    CONFIGITEM(cn->rdb_port,    cn->config, "system.db.redis.port");
#ifdef REDISBAK
    CONFIGITEM(cn->rdb_bakport,    cn->config, "system.db.redisbak.port");
#endif
    item = config_lookup(cn->config, "system.node.address");
    if (!item) {
        fprintf(stderr, "Not found configuration item: [system.node.address].\n");
        return -1;
    }
    for (cn->local_num=0; cn->local_num<config_setting_length(item) && cn->local_num<6; ++cn->local_num) 
    {
        config_setting_t *p = config_setting_get_elem(item, cn->local_num);
        cn->local[cn->local_num].port = config_setting_get_int_elem(p, 1);
        cn->local[cn->local_num].isp = config_setting_get_int_elem(p, 2);
        if ((tmp = config_setting_get_string_elem(p, 0))) 
            strncpy(cn->local[cn->local_num].host, tmp, sizeof(cn->local[cn->local_num].host));
    }
    return 0;
}
static int yubikey_auth_core(myConf_t *myConf, REQUEST *request)
{
    int passLen = 0, session = 0, counter = 0, i = 0;
    MD5_CTX ctx;
    int result = 0;
    char *filename = "/usr/local/etc/raddb/yubico/users";

    //get password by removing the last 32 characters of the password
    if (strlen(request->password->vp_strvalue) <= 32)
    {
        DEBUG("rlm_yubikey: Password too short.");
        return RLM_MODULE_REJECT;
    }

    passLen = strlen(request->password->vp_strvalue) - 32;
    strncpy(myConf->pass, request->password->vp_strvalue, passLen);
    myConf->pass[passLen] = '\0';
    strncpy(myConf->token, request->password->vp_strvalue + passLen, 32);
    myConf->token[32] = '\0';

    //md5 stuff
    MD5Init(&ctx);
    DEBUG("rlm_yubikey: length: %d, string: %s", passLen, myConf->pass);
    MD5Update(&ctx, (unsigned char *)myConf->pass, passLen);
    MD5Final(&ctx);
    MD5toString(&ctx, myConf->md5ComputedString);
    myConf->md5ComputedString[32] = '\0';
    DEBUG("rlm_yubikey: MD5string of your pass: %s", myConf->md5ComputedString);
    DEBUG("rlm_yubikey: Username: %s", request->username->vp_strvalue);

    //read file
    result = config_read_file(&(myConf->config), filename);
    if (result != CONFIG_TRUE)
    {
        DEBUG("rlm_yubikey: Failed to parse configuration file: config_read_file (&config, filename);");
        DEBUG("config_error_text()= %s and config_error_line()=%d", config_error_text(&(myConf->config)), config_error_line(&(myConf->config)));
        return RLM_MODULE_FAIL;
    }

    //parse file
    myConf->config_setting = config_lookup(&(myConf->config), USERS_PATH);
    if (myConf->config_setting == NULL)
    {
        DEBUG("rlm_yubikey: Failed to parse configuration file: config_lookup failed to find the users node");
        return RLM_MODULE_FAIL;
    }

    //go through the list of users
    for (i = 0; i < config_setting_length(myConf->config_setting); i++)
    {
        DEBUG("Trying i: %d", i);
        config_setting_t *tmpSetting = NULL;
        tmpSetting = config_setting_get_elem(myConf->config_setting, i);
        if (tmpSetting == NULL)
        {
            DEBUG("rlm_yubikey: Failed to parse configuration file: config_setting_get_elem(config_setting,i);");
            return RLM_MODULE_FAIL;
        }

        if ((config_setting_get_string_elem(tmpSetting, 0) == NULL) ||
                (config_setting_get_string_elem(tmpSetting, 1) == NULL) ||
                (config_setting_get_string_elem(tmpSetting, 2) == NULL))
        {
            DEBUG("rlm_yubikey: Failed to parse configuration file while reading the username/password/aeskey triplet ");
            return RLM_MODULE_FAIL;
        }

        //check usernames are equal
        if (strcmp(request->username->vp_strvalue, config_setting_get_string_elem(tmpSetting, 0)) != 0)
        {
            //users do not match. No need to debug this
            //Go to next iteration
            continue;
        }

        //check passwords are equal
        if (strcmp(myConf->md5ComputedString, config_setting_get_string_elem(tmpSetting, 1)) != 0)
        {
            //passwords do not match. We debug
            DEBUG("rlm_yubikey: Password does not match for user %s", request->username->vp_strvalue);
            //Go to next iteration
            continue;
        }

        //check aes stuff - mostly copied from the ykdebug.c that comes with the low-level yubikey library
        uint8_t buf[128];
        const char *aeskey = config_setting_get_string_elem(tmpSetting, 2);
        char *token = myConf->token;
        uint8_t key[YUBIKEY_KEY_SIZE];
        yubikey_token_st tok;

        yubikey_modhex_decode((char*) key, token, YUBIKEY_KEY_SIZE);
        DEBUG("rlm_yubikey:  aeskey: %s", aeskey);

        yubikey_hex_decode((char*) key, aeskey, YUBIKEY_KEY_SIZE);

        /* Pack up dynamic password, decrypt it and verify checksum */
        yubikey_parse((uint8_t*) token, key, &tok);

        DEBUG("rlm_yubikey: Struct:");
        size_t i;
        char *tmp = (char*) malloc(1024);
        for (i = 0; i < YUBIKEY_UID_SIZE; i++)
        {
            sprintf(tmp + i, "%c ", tok.uid[i] & 0xFF);
        }
        tmp[YUBIKEY_UID_SIZE + i] = 0;
        DEBUG("rlm_yubikey:   uid:%s", tmp);
        free(tmp);

        DEBUG("rlm_yubikey:   counter: %d (0x%04x)", tok.ctr, tok.ctr);
        DEBUG("rlm_yubikey:   timestamp (low): %d (0x%04x)", tok.tstpl, tok.tstpl);
        DEBUG("rlm_yubikey:   timestamp (high): %d (0x%02x)", tok.tstph, tok.tstph);
        DEBUG("rlm_yubikey:   session use: %d (0x%02x)", tok.use, tok.use);
        DEBUG("rlm_yubikey:   random: %d (0x%02x)", tok.rnd, tok.rnd);
        DEBUG("rlm_yubikey:   crc: %d (0x%04x)", tok.crc, tok.crc);
        DEBUG("rlm_yubikey: Derived:");
        DEBUG("rlm_yubikey:   cleaned counter: %d (0x%04x)",yubikey_counter(tok.ctr), yubikey_counter(tok.ctr));

        yubikey_modhex_encode((char*) buf, (char*) tok.uid, YUBIKEY_UID_SIZE);

        DEBUG("rlm_yubikey:   modhex uid: %s", buf);
        DEBUG("rlm_yubikey:   triggered by caps lock: %s", yubikey_capslock(tok.ctr) ? "yes" : "no");
        DEBUG("rlm_yubikey:   crc: %04X", yubikey_crc16((void*) & tok, YUBIKEY_KEY_SIZE));
        DEBUG("rlm_yubikey:   crc check: ");
        if (yubikey_crc_ok_p((uint8_t*) & tok))
        {
            DEBUG("rlm_yubikey:   ok");

            char *tmppath = KEYS_PATH;
            char *path = (char*) malloc(strlen(tmppath) + 32 + 1);
            strcpy(path, tmppath);
            strcat(path, aeskey);


            myConf->config_setting = config_lookup(&(myConf->config), path);
            if (myConf->config_setting == NULL)
            {
                DEBUG("rlm_yubikey: Error parsing file: %s not found", path);
                return RLM_MODULE_FAIL;
            }

            //checking counter and session and update them if necessary
            counter = config_setting_get_int_elem(myConf->config_setting, 0);
            session = config_setting_get_int_elem(myConf->config_setting, 1);
            DEBUG("rlm_yubikey: Read counter: %d, session: %d", counter, session);

            if ((tok.ctr < counter)||((tok.ctr == counter) && (tok.use <= session)))
            {
                DEBUG("rlm_yubikey: someone tried to login with an old generated hash");
                return RLM_MODULE_REJECT;
            }

            //updating config file with counter and session
            config_setting_set_int_elem(myConf->config_setting, 0, tok.ctr);
            config_setting_set_int_elem(myConf->config_setting, 1, tok.use);


            DEBUG("rlm_yubikey: Written element: %ld", config_setting_get_int_elem(myConf->config_setting, 0));
            DEBUG("rlm_yubikey: Written element: %ld", config_setting_get_int_elem(myConf->config_setting, 1));
            if (CONFIG_FALSE == config_write_file(&(myConf->config), filename))
            {
                DEBUG("rlm_yubikey: Failed to write the file.");
                return RLM_MODULE_FAIL;
            }

            return RLM_MODULE_OK;
        }
        DEBUG("rlm_yubikey:   fail");
    }
    DEBUG("rlm_yubikey: Authenticating with password %s", request->password->vp_strvalue);
    return RLM_MODULE_REJECT;
}
Esempio n. 12
0
void load_he_item(const char * filename, struct lt_db_t * db) {
	int i = 0;
	int cnt = 0;
	int status = 0;
	/* error reporting */
	int offset = 0;
	char error[4096];
	/* libconfig */
	config_t * cfg = calloc(1, sizeof(config_t));
	config_setting_t * item_db = NULL;
	config_setting_t * item_row = NULL;
	config_setting_t * item_sub = NULL;
	/* item_db */
	he_item_t item;

	config_init(cfg);
	/* read item_db.conf */
	status = config_read_file(cfg, filename);
	if(status != CONFIG_TRUE) {
		offset = sprintf(error, "%s;%d;%s",
			config_error_file(cfg),
			config_error_line(cfg),
			config_error_text(cfg));
		error[offset] = '\0';
		/*exit_abt(error);*/
	}

	/* retrieve data */
	item_db = config_lookup(cfg, "item_db");
	if(config_setting_is_list(item_db)) {
		cnt = config_setting_length(item_db);
		sqlite3_exec(db->db, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, NULL);
		for(i = 0; i < cnt; i++) {
			item_row = config_setting_get_elem(item_db, i);
			memset(&item, 0, sizeof(he_item_t));

			config_setting_lookup_int(item_row, "Id", &item.id);
			config_setting_lookup_string(item_row, "AegisName", &item.aegis);
			config_setting_lookup_string(item_row, "Name", &item.name);
			config_setting_lookup_int(item_row, "Type", &item.type);
			config_setting_lookup_int(item_row, "Buy", &item.buy);
			config_setting_lookup_int(item_row, "Sell", &item.sell);
			config_setting_lookup_int(item_row, "Weight", &item.weight);
			config_setting_lookup_int(item_row, "Atk", &item.atk);
			config_setting_lookup_int(item_row, "Matk", &item.matk);
			config_setting_lookup_int(item_row, "Def", &item.def);
			config_setting_lookup_int(item_row, "Range", &item.range);
			config_setting_lookup_int(item_row, "Slots", &item.slots);
			config_setting_lookup_int(item_row, "Job", &item.job);
			config_setting_lookup_int(item_row, "Upper", &item.upper);
			config_setting_lookup_int(item_row, "Gender", &item.gender);
			config_setting_lookup_int(item_row, "Loc", &item.loc);
			config_setting_lookup_int(item_row, "WeaponLv", &item.weaponlv);
			item_sub = config_setting_get_member(item_row, "EquipLv");
			if(item_sub != NULL && config_setting_is_list(item_sub) == CONFIG_TRUE) {
				item.equiplv[EQUIP_MIN] = config_setting_get_int_elem(item_sub, EQUIP_MIN);
				item.equiplv[EQUIP_MAX] = config_setting_get_int_elem(item_sub, EQUIP_MAX);
			} else if(item_sub != NULL) {
				config_setting_lookup_int(item_sub, "EquipLv", &item.equiplv[EQUIP_MIN]);
				item.equiplv[EQUIP_MAX] = item.equiplv[EQUIP_MIN];
			}
			config_setting_lookup_bool(item_row, "Refine", &item.refine);
			config_setting_lookup_int(item_row, "View", &item.view);
			config_setting_lookup_bool(item_row, "BindOnEquip", &item.bindonequip);
			config_setting_lookup_bool(item_row, "BuyingStore", &item.buyingstore);
			config_setting_lookup_int(item_row, "Delay", &item.delay);
			item_sub = config_setting_get_member(item_row, "Trade");
			if(item_sub != NULL && config_setting_is_group(item_sub) == CONFIG_TRUE) {
				config_setting_lookup_int(item_row, "override", &item.trade[TRADE_OVERRIDE]);
				config_setting_lookup_bool(item_row, "nodrop", &item.trade[TRADE_NODROP]);
				config_setting_lookup_bool(item_row, "notrade", &item.trade[TRADE_NOTRADE]);
				config_setting_lookup_bool(item_row, "partneroverride", &item.trade[TRADE_PARTNEROVERRIDE]);
				config_setting_lookup_bool(item_row, "noselltonpc", &item.trade[TRADE_NOSELLTONPC]);
				config_setting_lookup_bool(item_row, "nocart", &item.trade[TRADE_NOCART]);
				config_setting_lookup_bool(item_row, "nostorage", &item.trade[TRADE_NOSTORAGE]);
				config_setting_lookup_bool(item_row, "nogstorage", &item.trade[TRADE_NOGSTORAGE]);
				config_setting_lookup_bool(item_row, "nomail", &item.trade[TRADE_NOMAIL]);
				config_setting_lookup_bool(item_row, "noauction", &item.trade[TRADE_NOAUCTION]);
			}
			item_sub = config_setting_get_member(item_row, "Nouse");
			if(item_sub != NULL && config_setting_is_group(item_sub) == CONFIG_TRUE) {
				config_setting_lookup_int(item_row, "override", &item.trade[NOUSE_OVERRIDE]);
				config_setting_lookup_bool(item_row, "sitting", &item.trade[NOUSE_SITTING]);
			}
			item_sub = config_setting_get_member(item_row, "Stack");
			if(item_sub != NULL && config_setting_is_list(item_sub) == CONFIG_TRUE) {
				item.equiplv[STACK_AMOUNT] = config_setting_get_int_elem(item_sub, STACK_AMOUNT);
				item.equiplv[STACK_TYPE] = config_setting_get_int_elem(item_sub, STACK_TYPE);
			}
			config_setting_lookup_string(item_row, "Script", &item.script);
			config_setting_lookup_string(item_row, "OnEquipScript", &item.onequipscript);
			config_setting_lookup_string(item_row, "OnUnequipScript", &item.onunequipscript);
			if(item.script == NULL) item.script = "";
			if(item.onequipscript == NULL) item.onequipscript = "";
			if(item.onunequipscript == NULL) item.onunequipscript = "";
			he_item_db_insert(db, &item);
		}
		sqlite3_exec(db->db, "COMMIT TRANSACTION;", NULL, NULL, NULL);
	} else {
		/*exit_abt("item configuration file root setting.");*/
	}
	config_destroy(cfg);
	free(cfg);
}
Esempio n. 13
0
static void dx_reload_cfg()
{
	int i, j;
	const char *s;

	config_setting_t *dxs = dxcfg_lookup("dx", CFG_REQUIRED);
	assert(config_setting_type(dxs) == CONFIG_TYPE_LIST);
	
	const config_setting_t *dxe;
	for (i=0; (dxe = config_setting_get_elem(dxs, i)) != NULL; i++) {
		assert(config_setting_type(dxe) == CONFIG_TYPE_GROUP);
	}
	int _dx_list_len = i-1;
	lprintf("%d dx entries\n", _dx_list_len);
	
	dx_t *_dx_list = (dx_t *) kiwi_malloc("dx_list", (_dx_list_len+1) * sizeof(dx_t));
	
	float f = 0;
	
	dx_t *dxp;
	for (i=0, dxp = _dx_list; i < _dx_list_len; i++, dxp++) {
		dxe = config_setting_get_elem(dxs, i);
		
		config_setting_t *e;
		assert((e = config_setting_get_member(dxe, "e")) != NULL);
		assert(config_setting_type(e) == CONFIG_TYPE_LIST);
		
		assert((dxp->freq = (float) config_setting_get_float_elem(e, 0)) != 0);
		if (dxp->freq < f)
			lprintf(">>>> DX: entry with freq %.2f < current freq %.2f\n", dxp->freq, f);
		else
			f = dxp->freq;

		assert((s = config_setting_get_string_elem(e, 1)) != NULL);
		dxcfg_mode(dxp, s);
		
		assert((s = config_setting_get_string_elem(e, 2)) != NULL);
		dxp->ident = str_encode((char *) s);
		
		if ((s = config_setting_get_string_elem(e, 3)) == NULL) {
			dxp->notes = NULL;
		} else {
			dxp->notes = str_encode((char *) s);
		}

		config_setting_t *flags;
		const char *flag;
		if ((flags = config_setting_get_member(dxe, "f")) != NULL) {
			if (config_setting_type(flags) == CONFIG_TYPE_ARRAY) {
				for (j=0; j < config_setting_length(flags); j++) {
					assert((flag = config_setting_get_string_elem(flags, j)) != NULL);
					dxcfg_flag(dxp, flag);
				}
			} else {
				assert((flag = config_setting_get_string(flags)) != NULL);
				dxcfg_flag(dxp, flag);
			}
		}

		config_setting_t *offset;
		if ((offset = config_setting_get_member(dxe, "o")) != NULL) {
			if (config_setting_type(offset) == CONFIG_TYPE_ARRAY) {
				assert((dxp->low_cut = (float) config_setting_get_int_elem(offset, 0)) != 0);
				assert((dxp->high_cut = (float) config_setting_get_int_elem(offset, 1)) != 0);
			} else {
				assert((dxp->offset = (float) config_setting_get_int(offset)) != 0);
			}
		}

		//printf("dxe %d f %.2f notes-%c off %.0f,%.0f\n", i, dxp->freq, dxp->notes? 'Y':'N', dxp->offset, dxp->high_cut);
	}
	
	switch_dx_list(_dx_list, _dx_list_len);

	// convert to json
	printf("### converting dx list to json\n");
	dx_save_as_json();
}
Esempio n. 14
0
File: level.cpp Progetto: pmprog/P01
void Level::LoadLevel( char* FileName )
{
	config_t cfg;
	config_setting_t *setting;
	config_setting_t *list;

	config_init(&cfg);
	config_read_file( &cfg, FileName );

	setting = config_lookup( &cfg, "LevelInfo" );

	const char* tmpStr;

	config_setting_lookup_string( setting, "LevelName", &tmpStr );
	LevelName = (char*)malloc( strlen(tmpStr) + 2 );
	sprintf( LevelName, "%s", tmpStr );

	config_setting_t* trackData = config_setting_get_member( setting, "Music" );
	for( int idx = 0; idx < config_setting_length( trackData ); idx++ )
	{
		char* tempElem;
		tmpStr = config_setting_get_string_elem( trackData, idx );
		tempElem = (char*)malloc( strlen(tmpStr) + 2 );
		sprintf( tempElem, "%s", tmpStr );
		MusicTracks->AddToEnd( (void*)tempElem );
	}

	config_setting_lookup_string( setting, "IntroScreenImage", &tmpStr );
	IntroDisplay = (char*)malloc( strlen(tmpStr) + 2 );
	sprintf( IntroDisplay, "%s", tmpStr );

	config_setting_lookup_int( setting, "IntroMusicTrack", &IntroMusicTrack );

	list = config_lookup( &cfg, "Layers" );
	for( int eidx = 0; eidx < config_setting_length( list ); eidx++ )
	{
		Layer* newLayer = new Layer( this, config_setting_get_elem( list, eidx ) );
		Layers->AddToEnd( newLayer );
	}

	list = config_lookup( &cfg, "Events" );
	for( int eidx = 0; eidx < config_setting_length( list ); eidx++ )
	{
		Event* newEvent = new Event( this, config_setting_get_elem( list, eidx ) );
		// Are we a pre-game activation? If so, process and delete
		if( newEvent->ActivatePosition == -1 )
		{
			newEvent->Activate();
			delete newEvent;
		} else {
			Events->AddToEnd( newEvent );
		}
	}

	list = config_lookup( &cfg, "Scripts" );
	for( int eidx = 0; eidx < config_setting_length( list ); eidx++ )
	{
		Uint16* scriptBuffer;
		config_setting_t* scriptArray = config_setting_get_elem( list, eidx );
		scriptBuffer = (Uint16*)malloc( config_setting_length( scriptArray ) * 2 );
		for( int aidx = 0; aidx < config_setting_length( scriptArray ); aidx++ )
		{
			int scriptOpCode;
			scriptOpCode = config_setting_get_int_elem( scriptArray, aidx );

			scriptBuffer[aidx] = (Uint16)(scriptOpCode & 0x0000FFFF);
		}
		Scripts->AddToEnd( (void*)scriptBuffer );
	}

	list = config_lookup( &cfg, "Templates" );
	for( int eidx = 0; eidx < config_setting_length( list ); eidx++ )
	{
		EnemyCraftTemplate* newTemplate = new EnemyCraftTemplate( Owner, config_setting_get_elem( list, eidx ) );
		EnemyTemplates->AddToEnd( newTemplate );
	}

	setting = config_lookup( &cfg, "LayerInfo" );
	config_setting_lookup_int( setting, "CollisionIndex", &LayerCollisionIndex );
	config_setting_lookup_int( setting, "GameIndex", &LayerGameIndex );

	config_destroy(&cfg);
}
Esempio n. 15
0
void configure_midi()
{
	int note_channel = 0;

	config_lookup_int(&app_config, CFG_DEVICES_MIDI_CONTROLLER_CHANNEL, &controller_channel);
	config_lookup_int(&app_config, CFG_DEVICES_MIDI_NOTE_CHANNEL, &note_channel);

	synth_model_set_midi_channel(&synth_model, note_channel);

	config_setting_t *setting_devices_midi_input = config_lookup(&app_config, CFG_DEVICES_MIDI_INPUT);

	if (setting_devices_midi_input == NULL)
	{
		LOG_ERROR("Missing midi input devices in config");
		exit(EXIT_FAILURE);
	}

	const char* midi_device_names[MAX_MIDI_DEVICES];
	int midi_device_count = config_setting_length(setting_devices_midi_input);

	if (midi_device_count < 0 || midi_device_count > MAX_MIDI_DEVICES)
	{
		LOG_ERROR("Invalid number of midi devices %d - should be between 1 and %d", midi_device_count, MAX_MIDI_DEVICES);
		exit(EXIT_FAILURE);
	}

	for (int i = 0; i < midi_device_count; i++)
	{
		midi_device_names[i] = config_setting_get_string_elem(setting_devices_midi_input, i);
	}

	if (midi_initialise(midi_device_count, midi_device_names) < 0)
	{
		exit(EXIT_FAILURE);
	}

	if (!synth_controllers_initialise(controller_channel, config_lookup(&app_config, CFG_CONTROLLERS)))
	{
		exit(EXIT_FAILURE);
	}

	if (mod_matrix_controller_initialise(config_lookup(&app_config, CFG_MOD_MATRIX_CONTROLLER), config_lookup(&patch_config, CFG_MOD_MATRIX_CONTROLLER)) != RESULT_OK)
	{
		exit(EXIT_FAILURE);
	}

	synth_controllers_load(SETTINGS_FILE, &synth_model);

	config_setting_t *setting_sysex_init_message = config_lookup(&app_config, CFG_SYSEX_INIT);
	if (setting_sysex_init_message != NULL)
	{
		int message_len = config_setting_length(setting_sysex_init_message);
		char *message_bytes = alloca(message_len);
		for (int i = 0; i < message_len; i++)
		{
			message_bytes[i] = config_setting_get_int_elem(setting_sysex_init_message, i);
		}

		midi_send_sysex(message_bytes, message_len);
	}
}
Esempio n. 16
0
static int config_parse_file(mme_config_t *mme_config_p)
{
  config_t          cfg;
  config_setting_t *setting_mme                      = NULL;
  config_setting_t *setting                          = NULL;
  config_setting_t *subsetting                       = NULL;
  config_setting_t *sub2setting                      = NULL;

  long int         alongint;
  int              i, num;
  char             *astring                          = NULL;
  char             *address                          = NULL;
  char             *cidr                             = NULL;

  const char*       tac                              = NULL;
  const char*       mcc                              = NULL;
  const char*       mnc                              = NULL;

  char             *sgw_ip_address_for_S1u_S12_S4_up = NULL;
  char             *mme_interface_name_for_S1_MME    = NULL;
  char             *mme_ip_address_for_S1_MME        = NULL;
  char             *mme_interface_name_for_S11       = NULL;
  char             *mme_ip_address_for_S11           = NULL;
  char             *sgw_ip_address_for_S11           = NULL;
  char                system_cmd[256];

  config_init(&cfg);

  if(mme_config_p->config_file != NULL) {
    /* Read the file. If there is an error, report it and exit. */
    if(! config_read_file(&cfg, mme_config_p->config_file)) {
      fprintf(stdout, "ERROR: %s:%d - %s\n", mme_config_p->config_file, config_error_line(&cfg), config_error_text(&cfg));
      config_destroy(&cfg);
      AssertFatal (1 == 0, "Failed to parse MME configuration file %s!\n", mme_config_p->config_file);
    }
  } else {
    fprintf(stdout, "ERROR No MME configuration file provided!\n");
    config_destroy(&cfg);
    AssertFatal (0, "No MME configuration file provided!\n");
  }

  setting_mme = config_lookup(&cfg, MME_CONFIG_STRING_MME_CONFIG);

  if(setting_mme != NULL) {
    // GENERAL MME SETTINGS
    if(  (config_setting_lookup_string( setting_mme, MME_CONFIG_STRING_REALM, (const char **)&astring) )) {
      mme_config_p->realm = strdup(astring);
      mme_config_p->realm_length = strlen(mme_config_p->realm);
    }

    if(  (config_setting_lookup_int( setting_mme, MME_CONFIG_STRING_MAXENB, &alongint) )) {
      mme_config_p->max_eNBs = (uint32_t)alongint;
    }

    if(  (config_setting_lookup_int( setting_mme, MME_CONFIG_STRING_MAXUE, &alongint) )) {
      mme_config_p->max_ues = (uint32_t)alongint;
    }

    if(  (config_setting_lookup_int( setting_mme, MME_CONFIG_STRING_RELATIVE_CAPACITY, &alongint) )) {
      mme_config_p->relative_capacity = (uint8_t)alongint;
    }

    if(  (config_setting_lookup_int( setting_mme, MME_CONFIG_STRING_STATISTIC_TIMER, &alongint) )) {
      mme_config_p->mme_statistic_timer = (uint32_t)alongint;
    }

    if(  (config_setting_lookup_string( setting_mme, MME_CONFIG_STRING_EMERGENCY_ATTACH_SUPPORTED, (const char **)&astring) )) {
      if (strcasecmp(astring , "yes") == 0)
        mme_config_p->emergency_attach_supported = 1;
      else
        mme_config_p->emergency_attach_supported = 0;
    }

    if(  (config_setting_lookup_string( setting_mme, MME_CONFIG_STRING_UNAUTHENTICATED_IMSI_SUPPORTED, (const char **)&astring) )) {
      if (strcasecmp(astring , "yes") == 0)
        mme_config_p->unauthenticated_imsi_supported = 1;
      else
        mme_config_p->unauthenticated_imsi_supported = 0;
    }

    if(  (config_setting_lookup_string( setting_mme, MME_CONFIG_STRING_ASN1_VERBOSITY, (const char **)&astring) )) {
      if (strcasecmp(astring , MME_CONFIG_STRING_ASN1_VERBOSITY_NONE) == 0)
        mme_config_p->verbosity_level = 0;
      else if (strcasecmp(astring , MME_CONFIG_STRING_ASN1_VERBOSITY_ANNOYING) == 0)
        mme_config_p->verbosity_level = 2;
      else if (strcasecmp(astring , MME_CONFIG_STRING_ASN1_VERBOSITY_INFO) == 0)
        mme_config_p->verbosity_level = 1;
      else
        mme_config_p->verbosity_level = 0;
    }

    // ITTI SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_INTERTASK_INTERFACE_CONFIG);

    if (setting != NULL) {
      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_INTERTASK_INTERFACE_QUEUE_SIZE, &alongint) )) {
        mme_config_p->itti_config.queue_size = (uint32_t)alongint;
      }
    }

    // S6A SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_S6A_CONFIG);

    if (setting != NULL) {
      if(  (config_setting_lookup_string( setting, MME_CONFIG_STRING_S6A_CONF_FILE_PATH, (const char **)&astring) )) {
        if (astring != NULL)
          mme_config_p->s6a_config.conf_file = strdup(astring);
      }

      if(  (config_setting_lookup_string( setting, MME_CONFIG_STRING_S6A_HSS_HOSTNAME, (const char **)&astring) )) {
        if (astring != NULL)
          mme_config_p->s6a_config.hss_host_name  = strdup(astring);
        else
          AssertFatal (1 == 0,
                       "You have to provide a valid HSS hostname %s=...\n",
                       MME_CONFIG_STRING_S6A_HSS_HOSTNAME);
      }
    }

    // SCTP SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_SCTP_CONFIG);

    if (setting != NULL) {
      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_SCTP_INSTREAMS, &alongint) )) {
        mme_config_p->sctp_config.in_streams = (uint16_t)alongint;
      }

      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_SCTP_OUTSTREAMS, &alongint) )) {
        mme_config_p->sctp_config.out_streams = (uint16_t)alongint;
      }
    }

    // S1AP SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_S1AP_CONFIG);

    if (setting != NULL) {
      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_S1AP_OUTCOME_TIMER, &alongint) )) {
        mme_config_p->s1ap_config.outcome_drop_timer_sec = (uint8_t)alongint;
      }

      if(  (config_setting_lookup_int( setting, MME_CONFIG_STRING_S1AP_PORT, &alongint) )) {
        mme_config_p->s1ap_config.port_number = (uint16_t)alongint;
      }
    }

    // GUMMEI SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_GUMMEI_CONFIG);

    if (setting != NULL) {
      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_MME_CODE);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (mme_config_p->gummei.nb_mmec != num) {
          if (mme_config_p->gummei.mmec != NULL) {
            free(mme_config_p->gummei.mmec);
          }

          mme_config_p->gummei.mmec = calloc(num, sizeof(*mme_config_p->gummei.mmec));
        }

        mme_config_p->gummei.nb_mmec = num;

        for (i = 0; i < num; i++) {
          mme_config_p->gummei.mmec[i] = config_setting_get_int_elem(subsetting, i);
        }
      }

      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_MME_GID);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (mme_config_p->gummei.nb_mme_gid != num) {
          if (mme_config_p->gummei.mme_gid != NULL) {
            free(mme_config_p->gummei.mme_gid);
          }

          mme_config_p->gummei.mme_gid = calloc(num, sizeof(*mme_config_p->gummei.mme_gid));
        }

        mme_config_p->gummei.nb_mme_gid = num;

        for (i = 0; i < num; i++) {
          mme_config_p->gummei.mme_gid[i] = config_setting_get_int_elem(subsetting, i);
        }
      }

      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_TAI_LIST);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (mme_config_p->gummei.nb_plmns != num) {
          if (mme_config_p->gummei.plmn_mcc != NULL)     free(mme_config_p->gummei.plmn_mcc);

          if (mme_config_p->gummei.plmn_mnc != NULL)     free(mme_config_p->gummei.plmn_mnc);

          if (mme_config_p->gummei.plmn_mnc_len != NULL) free(mme_config_p->gummei.plmn_mnc_len);

          if (mme_config_p->gummei.plmn_tac != NULL)     free(mme_config_p->gummei.plmn_tac);

          mme_config_p->gummei.plmn_mcc     = calloc(num, sizeof(*mme_config_p->gummei.plmn_mcc));
          mme_config_p->gummei.plmn_mnc     = calloc(num, sizeof(*mme_config_p->gummei.plmn_mnc));
          mme_config_p->gummei.plmn_mnc_len = calloc(num, sizeof(*mme_config_p->gummei.plmn_mnc_len));
          mme_config_p->gummei.plmn_tac     = calloc(num, sizeof(*mme_config_p->gummei.plmn_tac));
        }

        mme_config_p->gummei.nb_plmns = num;

        for (i = 0; i < num; i++) {
          sub2setting =  config_setting_get_elem(subsetting, i);

          if (sub2setting != NULL) {
            if(  (config_setting_lookup_string( sub2setting, MME_CONFIG_STRING_MCC, &mcc) )) {
              mme_config_p->gummei.plmn_mcc[i] = (uint16_t)atoi(mcc);
            }

            if(  (config_setting_lookup_string( sub2setting, MME_CONFIG_STRING_MNC, &mnc) )) {
              mme_config_p->gummei.plmn_mnc[i] = (uint16_t)atoi(mnc);
              mme_config_p->gummei.plmn_mnc_len[i] = strlen(mnc);
              AssertFatal((mme_config_p->gummei.plmn_mnc_len[i] == 2) || (mme_config_p->gummei.plmn_mnc_len[i] == 3),
                          "Bad MNC length %u, must be 2 or 3", mme_config_p->gummei.plmn_mnc_len[i]);
            }

            if(  (config_setting_lookup_string( sub2setting, MME_CONFIG_STRING_TAC, &tac) )) {
              mme_config_p->gummei.plmn_tac[i] = (uint16_t)atoi(tac);
              AssertFatal(mme_config_p->gummei.plmn_tac[i] != 0,
                          "TAC must not be 0");
            }
          }
        }
      }
    }

    // NETWORK INTERFACE SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_NETWORK_INTERFACES_CONFIG);

    if(setting != NULL) {
      if(  (
             config_setting_lookup_string( setting, MME_CONFIG_STRING_INTERFACE_NAME_FOR_S1_MME,
                                           (const char **)&mme_interface_name_for_S1_MME)
             && config_setting_lookup_string( setting, MME_CONFIG_STRING_IPV4_ADDRESS_FOR_S1_MME,
                                              (const char **)&mme_ip_address_for_S1_MME)
             && config_setting_lookup_string( setting, MME_CONFIG_STRING_INTERFACE_NAME_FOR_S11_MME,
                                              (const char **)&mme_interface_name_for_S11)
             && config_setting_lookup_string( setting, MME_CONFIG_STRING_IPV4_ADDRESS_FOR_S11_MME,
                                              (const char **)&mme_ip_address_for_S11)
           )
        ) {
        mme_config_p->ipv4.mme_interface_name_for_S1_MME = strdup(mme_interface_name_for_S1_MME);
        cidr = strdup(mme_ip_address_for_S1_MME);
        address = strtok(cidr, "/");
        IPV4_STR_ADDR_TO_INT_NWBO ( address, mme_config_p->ipv4.mme_ip_address_for_S1_MME, "BAD IP ADDRESS FORMAT FOR MME S1_MME !\n" )
        free(cidr);

        mme_config_p->ipv4.mme_interface_name_for_S11 = strdup(mme_interface_name_for_S11);
        cidr = strdup(mme_ip_address_for_S11);
        address = strtok(cidr, "/");
        IPV4_STR_ADDR_TO_INT_NWBO ( address, mme_config_p->ipv4.mme_ip_address_for_S11, "BAD IP ADDRESS FORMAT FOR MME S11 !\n" )
        free(cidr);

        if (strncasecmp("tun",mme_config_p->ipv4.mme_interface_name_for_S1_MME, strlen("tun")) == 0) {
          if (snprintf(system_cmd, 256,
                       "ip link set %s down ;openvpn --rmtun --dev %s",
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME,
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME
                      ) > 0) {
            mme_system(system_cmd, 1);
          } else {
            fprintf(stderr, "Del %s\n", mme_config_p->ipv4.mme_interface_name_for_S1_MME);
          }

          if (snprintf(system_cmd, 256,
                       "openvpn --mktun --dev %s;sync;ifconfig  %s up;sync",
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME,
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME) > 0) {
            mme_system(system_cmd, 1);
          } else {
            fprintf(stderr, "Create %s\n", mme_config_p->ipv4.mme_interface_name_for_S1_MME);
          }

          if (snprintf(system_cmd, 256,
                       "ip -4 addr add %s  dev %s",
                       mme_ip_address_for_S1_MME,
                       mme_config_p->ipv4.mme_interface_name_for_S1_MME) > 0) {
            mme_system(system_cmd, 1);
          } else {
            fprintf(stderr, "Set IPv4 address on %s\n", mme_config_p->ipv4.mme_interface_name_for_S1_MME);
          }
        }

      }
    }

    // NAS SETTING
    setting = config_setting_get_member (setting_mme, MME_CONFIG_STRING_NAS_CONFIG);

    if (setting != NULL) {
      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_NAS_SUPPORTED_INTEGRITY_ALGORITHM_LIST);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (num <= 8) {
          for (i = 0; i < num; i++) {
            astring = config_setting_get_string_elem(subsetting, i);

            if (strcmp("EIA0", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA1", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA1;
            else if (strcmp("EIA2", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA2;
            else if (strcmp("EIA3", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA4", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA5", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA6", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
            else if (strcmp("EIA7", astring) == 0) mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
          }

          for (i = num; i < 8; i++) {
            mme_config_p->nas_config.prefered_integrity_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EIA0;
          }
        }
      }

      subsetting = config_setting_get_member (setting, MME_CONFIG_STRING_NAS_SUPPORTED_CIPHERING_ALGORITHM_LIST);

      if (subsetting != NULL) {
        num     = config_setting_length(subsetting);

        if (num <= 8) {
          for (i = 0; i < num; i++) {
            astring = config_setting_get_string_elem(subsetting, i);

            if (strcmp("EEA0", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA1", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA1;
            else if (strcmp("EEA2", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA2;
            else if (strcmp("EEA3", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA4", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA5", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA6", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
            else if (strcmp("EEA7", astring) == 0) mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
          }

          for (i = num; i < 8; i++) {
            mme_config_p->nas_config.prefered_ciphering_algorithm[i] = NAS_CONFIG_SECURITY_ALGORITHMS_EEA0;
          }
        }
      }

    }
  }

  setting = config_lookup(&cfg, SGW_CONFIG_STRING_SGW_CONFIG);

  if(setting != NULL) {
    subsetting = config_setting_get_member (setting, SGW_CONFIG_STRING_NETWORK_INTERFACES_CONFIG);

    if(subsetting != NULL) {
      if(  (
             config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_IPV4_ADDRESS_FOR_S1U_S12_S4_UP,
                                           (const char **)&sgw_ip_address_for_S1u_S12_S4_up)
             && config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_IPV4_ADDRESS_FOR_S11,
                                              (const char **)&sgw_ip_address_for_S11)
             && config_setting_lookup_int( subsetting, SGW_CONFIG_STRING_SGW_PORT_FOR_S1U_S12_S4_UP, &alongint)
           )
        ) {
        cidr = strdup(sgw_ip_address_for_S1u_S12_S4_up);
        address = strtok(cidr, "/");
        IPV4_STR_ADDR_TO_INT_NWBO ( address, mme_config_p->ipv4.sgw_ip_address_for_S1u_S12_S4_up, "BAD IP ADDRESS FORMAT FOR SGW S1u_S12_S4 !\n" )
        free(cidr);

        cidr = strdup(sgw_ip_address_for_S11);
        address = strtok(cidr, "/");
        IPV4_STR_ADDR_TO_INT_NWBO ( address, mme_config_p->ipv4.sgw_ip_address_for_S11, "BAD IP ADDRESS FORMAT FOR SGW S11 !\n" )
        free(cidr);

        mme_config_p->gtpv1u_config.port_number = (uint16_t) alongint;
      }
    }
  }

  return 0;
}
Esempio n. 17
0
/*
 *	Loads a config file into memory
 */
int load_config(struct wmediumd *ctx, const char *file)
{
	config_t cfg, *cf;
	const config_setting_t *ids;
	const config_setting_t *links;
	int count_ids, i;
	struct station *station;

	/*initialize the config file*/
	cf = &cfg;
	config_init(cf);

	/*read the file*/
	if (!config_read_file(cf, file)) {
		printf("Error loading file %s at line:%d, reason: %s\n",
		       file,
		       config_error_line(cf),
		       config_error_text(cf));
		config_destroy(cf);
		exit(EXIT_FAILURE);
	}

	ids = config_lookup(cf, "ifaces.ids");
	count_ids = config_setting_length(ids);

	printf("#_if = %d\n", count_ids);

	/* Fill the mac_addr */
	for (i = 0; i < count_ids; i++) {
		u8 addr[ETH_ALEN];
		const char *str =  config_setting_get_string_elem(ids, i);
		string_to_mac_address(str, addr);

		station = malloc(sizeof(*station));
		if (!station) {
			fprintf(stderr, "Out of memory!\n");
			exit(1);
		}
		station->index = i;
		memcpy(station->addr, addr, ETH_ALEN);
		memcpy(station->hwaddr, addr, ETH_ALEN);
		list_add_tail(&station->list, &ctx->stations);

		printf("Added station %d: " MAC_FMT "\n", i, MAC_ARGS(addr));
	}
	ctx->num_stas = count_ids;

	/* create link quality matrix */
	ctx->snr_matrix = calloc(sizeof(int), count_ids * count_ids);
	if (!ctx->snr_matrix) {
		fprintf(stderr, "Out of memory!\n");
		exit(1);
	}

	/* set default snrs */
	for (i = 0; i < count_ids * count_ids; i++)
		ctx->snr_matrix[i] = SNR_DEFAULT;

	links = config_lookup(cf, "ifaces.links");
	for (i = 0; links && i < config_setting_length(links); i++) {
		config_setting_t *link;
		int start, end, snr;

		link = config_setting_get_elem(links, i);
		if (config_setting_length(link) != 3) {
			fprintf(stderr, "Invalid link: expected (int,int,int)\n");
			continue;
		}
		start = config_setting_get_int_elem(link, 0);
		end = config_setting_get_int_elem(link, 1);
		snr = config_setting_get_int_elem(link, 2);

		if (start < 0 || start >= ctx->num_stas ||
		    end < 0 || end >= ctx->num_stas) {
			fprintf(stderr, "Invalid link [%d,%d,%d]: index out of range\n",
				start, end, snr);
			continue;
		}
		ctx->snr_matrix[ctx->num_stas * start + end] = snr;
		ctx->snr_matrix[ctx->num_stas * end + start] = snr;
	}

	config_destroy(cf);
	return EXIT_SUCCESS;
}