#include #include #include #include #include #include "log.h" #include "config.h" bool set_config_value(const char *conf_dir_name, const char *conf_file_name, const char *section_type, const char *section_name, const char *key, const char *value) { struct uci_context *ctx; struct uci_package *pkg; struct uci_section *sct; struct uci_section *tmp_sct; struct uci_option *opt; int err_flg; char *fname; int b_count; bool save; bool ret_val; ret_val = false; save = false; if ((conf_dir_name != NULL) && (conf_file_name != NULL) && (section_type != NULL) && (section_name != NULL) && (key != NULL) && (value != NULL)) { b_count = strlen(conf_dir_name) + strlen(conf_file_name) + 10; fname = (char *)calloc(1, b_count); if (fname != NULL) { strncpy(fname, conf_dir_name, b_count); strncat(fname, "/", 1); strncat(fname, conf_file_name, strlen(conf_file_name) + 1); ctx = uci_alloc_context(); sct = NULL; uci_set_confdir(ctx, conf_dir_name); if (access(fname, F_OK) != 0) { FILE *fp; fp = fopen(fname, "w+"); fclose(fp); } err_flg = uci_load(ctx, fname, &pkg); struct uci_element *e; uci_foreach_element(&pkg->sections, e) { tmp_sct = uci_to_section(e); if (strcmp(tmp_sct->type, section_type) == 0) { sct = tmp_sct; break; } } //sct = uci_lookup_section(ctx, pkg, "service"); if (sct != NULL) { log_debug("section found\n"); } else { log_debug("adding new section\n"); err_flg = uci_add_named_section(ctx, pkg, section_type, section_name, &sct); log_debug("err_flg: %d, section name: %s\n", err_flg, sct->e.name); } opt = uci_lookup_option(ctx, sct, key); if (opt != NULL) { struct uci_ptr ptr; memset(&ptr, 0, sizeof(ptr)); ptr.package = pkg->e.name; ptr.section = sct->e.name; ptr.option = key; if (uci_lookup_ptr(ctx, &ptr, NULL, false) == UCI_OK) { log_debug("trying to change option value\n"); ptr.value = strdup(value); uci_set(ctx, &ptr); save = true; } } else { opt = uci_alloc_option(sct, key, value); save = true; } if (save == true) { log_debug("saving config file: %s\n", fname); uci_save(ctx, pkg); } free(fname); ret_val = true; } else { log_error("Could not change config value, out of memory"); } } else { log_error("Could not change config value, invalid parameters"); } return ret_val; }