Exemple #1
0
int get_family_id(int sd)
{
	struct msgtemplate msg;
	int	len;
	int	recv_len;
	int	rc;
	struct nlattr *na;

	rc = send_cmd(sd, GENL_ID_CTRL, CTRL_CMD_GETFAMILY,
			CTRL_ATTR_FAMILY_NAME, SAMPLE_NETLINK_NL_FAMILY_NAME,
			strlen(SAMPLE_NETLINK_NL_FAMILY_NAME)+1, NLM_F_REQUEST);
	if (rc < 0) {
		printf("Error sending family cmd (%d:%s)\n",
				errno, strerror(errno));
		return -1;
	}
	recv_len = recv(sd, &msg, sizeof(msg), 0);
	if (msg.n.nlmsg_type == NLMSG_ERROR) {
		printf("Error: recv family error msg\n");
		return -1;
	}
	if (recv_len < 0) {
		printf("Error: recv family (%d)\n", recv_len);
		return -1;
	}
	if (!NLMSG_OK((&msg.n), recv_len)) {
		printf("Error: recv family msg nok\n");
		return -1;
	}

	len = 0;
	recv_len = GENLMSG_PAYLOAD(&msg.n);
	na = (struct nlattr *) GENLMSG_DATA(&msg);
	while (len < recv_len) {
		len += NLA_ALIGN(na->nla_len);
		switch (na->nla_type) {
			case CTRL_ATTR_FAMILY_ID:
				nl_family_id = *(uint16_t *) NLA_DATA(na);
				printf("family id:%d\n", nl_family_id);
				break;
			case CTRL_ATTR_MCAST_GROUPS:
				parse_groups(NLA_DATA(na),
						NLA_PAYLOAD_LEN(na->nla_len));
				break;
			case CTRL_ATTR_FAMILY_NAME:
			case CTRL_ATTR_VERSION:
			case CTRL_ATTR_HDRSIZE:
			case CTRL_ATTR_MAXATTR:
			case CTRL_ATTR_OPS:
				printf("Unused family attr %d\n", na->nla_type);
				break;
			default:
				printf("Unknown family attr %d\n", na->nla_type);
				break;
		}
		na = (struct nlattr *) (GENLMSG_DATA(&msg) + len);
	}

	return nl_family_id;
}
Exemple #2
0
bool mesos_state_t::parse_groups(std::string&& json, const std::string& framework_id)
{
	Json::Value root;
	Json::Reader reader;
	if(reader.parse(json, root, false) && !root["id"].isNull())
	{
		return parse_groups(std::move(root), framework_id);
	}
	else
	{
		throw sinsp_exception("Marathon groups parsing failed (Invalid JSON).");
	}
}
int main(int argc, char **argv) {
    char *filename;

    if (argc == 2) {
        filename = argv[1];
    } else {
        filename = DEFAULT_TRANSLITERATION_PATH;
    }

    FILE *f = fopen(filename, "wb");

    if (f == NULL) {
        log_error("File could not be opened, ensure directory exists: %s", filename);
        exit(1);
    }

    size_t num_source_transliterators = sizeof(transliterators_source) / sizeof(transliterator_source_t);

    char *key;
    size_t key_len;

    context_type_t pre_context_type;
    size_t pre_context_max_len;
    char *pre_context;
    size_t pre_context_len;

    context_type_t post_context_type;
    size_t post_context_max_len;
    char *post_context;
    size_t post_context_len;

    char *replacement;
    size_t replacement_len;

    char *revisit;
    size_t revisit_len;

    char *group_regex_str;
    size_t group_regex_len;

    transliteration_module_init();

    transliteration_table_t *trans_table = get_transliteration_table();

    trie_t *trie = trans_table->trie;

    for (int i = 0; i < num_source_transliterators; i++) {
        transliterator_source_t trans_source = transliterators_source[i];

        size_t trans_name_len = strlen(trans_source.name);

        log_info("Doing transliterator: %s\n", trans_source.name);

        char_array *trans_key = char_array_from_string(trans_source.name);
        char_array_cat(trans_key, NAMESPACE_SEPARATOR_CHAR);

        char *trans_name = strdup(trans_source.name);
        if (trans_name == NULL) {
            log_error("strdup returned NULL on trans_source.name\n");
            goto exit_teardown;
        }

        transliterator_t *trans = transliterator_new(trans_name, trans_source.internal, trans_table->steps->n, trans_source.steps_length);

        for (int j = 0; j < trans_source.steps_length; j++) {
            transliteration_step_source_t step_source = steps_source[trans_source.steps_start + j];

            size_t step_name_len = strlen(step_source.name);

            log_debug("Doing step: %s, type=%d\n", step_source.name, step_source.type);

            if (!transliteration_table_add_step(trans_table, step_source.type, step_source.name)) {
                log_error("Step couldn't be added\n");
                goto exit_teardown;
            }

            if (step_source.type != STEP_RULESET) {
                continue;
            }

            char_array *step_key = char_array_from_string(char_array_get_string(trans_key));
            char_array_cat(step_key, step_source.name);
            char_array_cat(step_key, NAMESPACE_SEPARATOR_CHAR);

            char *step_key_str = char_array_get_string(step_key);
            size_t step_key_len = strlen(step_key_str);

            for (int k = 0; k < step_source.rules_length; k++) {
                transliteration_rule_source_t rule_source = rules_source[step_source.rules_start + k];
                key = rule_source.key;
                key_len = rule_source.key_len;

                pre_context_type = rule_source.pre_context_type;
                pre_context_max_len = rule_source.pre_context_max_len;
                pre_context = rule_source.pre_context;
                pre_context_len = rule_source.pre_context_len;

                post_context_type = rule_source.post_context_type;
                post_context_max_len = rule_source.post_context_max_len;
                post_context = rule_source.post_context;
                post_context_len = rule_source.post_context_len;

                replacement = rule_source.replacement;
                replacement_len = rule_source.replacement_len;

                revisit = rule_source.revisit;
                revisit_len = rule_source.revisit_len;

                group_regex_str = rule_source.group_regex_str;
                group_regex_len = rule_source.group_regex_len;

                uint32_t data = trans_table->replacements->n;
                
                char_array *rule_key = char_array_from_string(step_key_str);

                uint32_t replacement_string_index = cstring_array_num_strings(trans_table->replacement_strings);
                cstring_array_add_string_len(trans_table->replacement_strings, replacement, replacement_len);

                uint32_t revisit_index = 0;
                if (revisit != NULL && revisit_len > 0) {
                    revisit_index = cstring_array_num_strings(trans_table->revisit_strings);
                    cstring_array_add_string_len(trans_table->revisit_strings, revisit, revisit_len);
                }

                group_capture_array *groups = parse_groups(group_regex_str, group_regex_len);

                transliteration_replacement_t *trans_repl = transliteration_replacement_new(replacement_string_index, revisit_index, groups);

                uint32_t replacement_index = trans_table->replacements->n;
                transliteration_replacement_array_push(trans_table->replacements, trans_repl);

                int c;

                char *token;

                log_debug("Doing rule: %s\n", key);

                string_tree_t *tree = regex_string_tree(key, key_len);

                string_tree_t *pre_context_tree = NULL;
                string_tree_iterator_t *pre_context_iter = NULL;

                cstring_array *pre_context_strings = NULL;

                if (pre_context_type != CONTEXT_TYPE_NONE) {
                    pre_context_strings = cstring_array_new();
                }

                if (pre_context_type == CONTEXT_TYPE_REGEX) {
                    log_debug("pre_context_type == CONTEXT_TYPE_REGEX\n");
                    pre_context_tree = regex_string_tree(pre_context, pre_context_len);

                    pre_context_iter = string_tree_iterator_new(pre_context_tree);

                    char_array *pre_context_perm = char_array_new_size(pre_context_len);

                    for (; !string_tree_iterator_done(pre_context_iter); string_tree_iterator_next(pre_context_iter)) {
                        char_array_clear(pre_context_perm);
                        for (c = 0; c < pre_context_iter->num_tokens; c++) {
                            token = string_tree_iterator_get_string(pre_context_iter, c);
                            if (token == NULL || strlen(token) == 0) {
                                log_warn("pre_token_context is NULL or 0 length: %s\n", token);
                            }
                            char_array_cat(pre_context_perm, token);
                        }
                        token = char_array_get_string(pre_context_perm);
                        if (token == NULL || strlen(token) == 0) {
                            log_warn("pre_perm is NULL or 0 length\n");
                        }
                        cstring_array_add_string(pre_context_strings, token);
                    }

                    char_array_destroy(pre_context_perm);
                    string_tree_iterator_destroy(pre_context_iter);
                    string_tree_destroy(pre_context_tree);
                } else if (pre_context_type == CONTEXT_TYPE_STRING) {
                    if (pre_context == NULL || strlen(pre_context) == 0) {
                        log_warn("pre_context STRING NULL or 0 length\n");
                    }
                    cstring_array_add_string(pre_context_strings, pre_context);
                } else if (pre_context_type == CONTEXT_TYPE_WORD_BOUNDARY) {
                    cstring_array_add_string(pre_context_strings, WORD_BOUNDARY_CHAR);
                }

                size_t num_pre_context_strings = 0;
                if (pre_context_type != CONTEXT_TYPE_NONE) {
                    num_pre_context_strings = cstring_array_num_strings(pre_context_strings);
                    log_debug("num_pre_context_strings = %zu\n", num_pre_context_strings);
                }

                string_tree_t *post_context_tree = NULL;
                string_tree_iterator_t *post_context_iter = NULL;

                cstring_array *post_context_strings = NULL;

                if (post_context_type != CONTEXT_TYPE_NONE) {
                    post_context_strings = cstring_array_new();
                }

                if (post_context_type == CONTEXT_TYPE_REGEX) {
                    log_debug("post_context_type == CONTEXT_TYPE_REGEX\n");
                    post_context_tree = regex_string_tree(post_context, post_context_len);

                    post_context_iter = string_tree_iterator_new(post_context_tree);

                    char_array *post_context_perm = char_array_new_size(post_context_len);

                    for (; !string_tree_iterator_done(post_context_iter); string_tree_iterator_next(post_context_iter)) {
                        char_array_clear(post_context_perm);
                        for (c = 0; c < post_context_iter->num_tokens; c++) {
                            token = string_tree_iterator_get_string(post_context_iter, c);
                            if (token == NULL) {
                                log_error ("post_token_context is NULL\n");
                            } else if (strlen(token) == 0) {
                                log_error("post_token_context is 0 length\n");
                            }
                            char_array_cat(post_context_perm, token);
                        }

                        cstring_array_add_string(post_context_strings, char_array_get_string(post_context_perm));
                    }

                    char_array_destroy(post_context_perm);
                    string_tree_iterator_destroy(post_context_iter);
                    string_tree_destroy(post_context_tree);
                } else if (post_context_type == CONTEXT_TYPE_STRING) {
                    if (post_context == NULL || strlen(post_context) == 0) {
                        log_error("post_context STRING NULL or 0 length\n");
                    }
                    cstring_array_add_string(post_context_strings, post_context);
                } else if (post_context_type == CONTEXT_TYPE_WORD_BOUNDARY) {
                    cstring_array_add_string(post_context_strings, WORD_BOUNDARY_CHAR);
                }

                size_t num_post_context_strings = 0;
                if (post_context_type != CONTEXT_TYPE_NONE) {
                    num_post_context_strings = cstring_array_num_strings(post_context_strings);
                    log_debug("num_post_context_strings = %zu\n", num_post_context_strings);
                }

                cstring_array *context_strings = NULL;
                size_t num_context_strings = 0;
                char *context_start_char = NULL;
                bool combined_context_strings = false;

                int ante, post;

                if (num_pre_context_strings > 0 && num_post_context_strings > 0) {
                    context_start_char = PRE_CONTEXT_CHAR;
                    combined_context_strings = true;
                    size_t max_string_size = 2 * MAX_UTF8_CHAR_SIZE + 
                                             ((pre_context_max_len * MAX_UTF8_CHAR_SIZE) * 
                                             (post_context_max_len * MAX_UTF8_CHAR_SIZE));
                    num_context_strings = num_pre_context_strings * num_post_context_strings;
                    char_array *context = char_array_new_size(max_string_size);
                    context_strings = cstring_array_new_size(num_context_strings * max_string_size + num_context_strings);
                    for (ante = 0; ante < num_pre_context_strings; ante++) {
                        char_array_clear(context);

                        token = cstring_array_get_string(pre_context_strings, ante);
                        if (token == NULL || strlen(token) == 0) {
                            log_error("pre_context token was NULL or 0 length\n");
                            goto exit_teardown;
                        }

                        char_array_cat(context, token);
                        size_t context_len = strlen(char_array_get_string(context));

                        for (post = 0; post < num_post_context_strings; post++) {
                            context->n = context_len;
                            char_array_cat(context, POST_CONTEXT_CHAR);
                            token = cstring_array_get_string(post_context_strings, post);
                            char_array_cat(context, token);
                            if (token == NULL || strlen(token) == 0) {
                                log_error("post_context token was NULL or 0 length\n");
                                goto exit_teardown;
                            }

                            token = char_array_get_string(context);
                            cstring_array_add_string(context_strings, token);

                        }

                    }

                    char_array_destroy(context);

                } else if (num_pre_context_strings > 0) {
                    context_start_char = PRE_CONTEXT_CHAR;
                    num_context_strings = num_pre_context_strings;
                    context_strings = pre_context_strings;
                } else if (num_post_context_strings > 0) {
                    context_start_char = POST_CONTEXT_CHAR;
                    num_context_strings = num_post_context_strings;
                    context_strings = post_context_strings;
                }

                if (num_context_strings > 0) {
                    log_debug("num_context_strings = %zu\n", num_context_strings);
                }


                if (tree == NULL) {
                    log_error("Tree was NULL, rule=%s\n", key);
                    goto exit_teardown;
                }

                string_tree_iterator_t *iter = string_tree_iterator_new(tree);

                log_debug("iter->remaining=%d\n", iter->remaining);
                
                char *key_str;

                for (; !string_tree_iterator_done(iter); string_tree_iterator_next(iter)) {
                    rule_key->n = step_key_len;

                    for (c = 0; c < iter->num_tokens; c++) {
                        token = string_tree_iterator_get_string(iter, c);
                        if (token == NULL) {
                            log_error("string_tree_iterator_get_string was NULL: %s\n", key);
                            goto exit_teardown;
                        }
                        char_array_cat(rule_key, token);
                        log_debug("string_tree token was %s\n", token);
                    }

                    log_debug("rule_key=%s\n", char_array_get_string(rule_key));

                    size_t context_key_len;

                    if (num_context_strings == 0) {

                        token = char_array_get_string(rule_key);
                        if (trie_get(trie, token) == NULL_NODE_ID) {
                            trie_add(trie, token, replacement_index);
                        } else {
                            log_warn("Key exists: %s, skipping\n", token);                            
                        }
                    } else {
                        char_array_cat(rule_key, context_start_char);
                        context_key_len = strlen(char_array_get_string(rule_key));

                        for (c = 0; c < num_context_strings; c++) {
                            rule_key->n = context_key_len;
                            token = cstring_array_get_string(context_strings, c);
                            if (token == NULL) {
                                log_error("token was NULL for c=%d\n", c);
                            }
                            char_array_cat(rule_key, token);
                            token = char_array_get_string(rule_key);
                            if (trie_get(trie, token) == NULL_NODE_ID) {
                                trie_add(trie, token, replacement_index);
                            } else {
                                log_warn("Key exists: %s, skipping\n", token);
                            }
                        }

                    }

                }

                string_tree_iterator_destroy(iter);
                string_tree_destroy(tree);

                char_array_destroy(rule_key);

                if (pre_context_strings != NULL) {
                    cstring_array_destroy(pre_context_strings);
                }

                if (post_context_strings != NULL) {
                    cstring_array_destroy(post_context_strings);
                }

                // Only needed if we created a combined context array
                if (combined_context_strings) {
                    cstring_array_destroy(context_strings);
                }
            }

            char_array_destroy(step_key);

        }

        char_array_destroy(trans_key);

        if (!transliteration_table_add_transliterator(trans)) {
            goto exit_teardown;
        }

    }

    size_t num_source_scripts = sizeof(script_transliteration_rules) / sizeof(script_transliteration_rule_t);

    for (int i = 0; i < num_source_scripts; i++) {
        script_transliteration_rule_t rule = script_transliteration_rules[i];

        if (!transliteration_table_add_script_language(rule.script_language, rule.index)) {
            goto exit_teardown;
        }

        transliterator_index_t index = rule.index;

        for (int j = index.transliterator_index; j < index.transliterator_index + index.num_transliterators; j++) {
            char *trans_name = script_transliterators[j];
            if (trans_name == NULL) {
                goto exit_teardown;
            }
            cstring_array_add_string(trans_table->transliterator_names, trans_name);
        }

    }

    transliteration_table_write(f);
    fclose(f);
    transliteration_module_teardown();
    log_info("Done!\n");
    exit(EXIT_SUCCESS);

exit_teardown:
    log_error("FAIL\n");
    transliteration_module_teardown();
    exit(EXIT_FAILURE);

}
Exemple #4
0
int main(int argc, const char **argv)
{
    uid_t pc_uid = 0;
    const char *pc_gecos = NULL;
    const char *pc_home = NULL;
    char *pc_shell = NULL;
    int pc_debug = SSSDBG_DEFAULT;
    int pc_create_home = 0;
    const char *pc_username = NULL;
    const char *pc_skeldir = NULL;
    const char *pc_selinux_user = NULL;
    struct poptOption long_options[] = {
        POPT_AUTOHELP
        { "debug", '\0', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_debug, 0, _("The debug level to run with"), NULL },
        { "uid",   'u', POPT_ARG_INT, &pc_uid, 0, _("The UID of the user"), NULL },
        { "gecos", 'c', POPT_ARG_STRING, &pc_gecos, 0, _("The comment string"), NULL },
        { "home",  'h', POPT_ARG_STRING, &pc_home, 0, _("Home directory"), NULL },
        { "shell", 's', POPT_ARG_STRING, &pc_shell, 0, _("Login shell"), NULL },
        { "groups", 'G', POPT_ARG_STRING, NULL, 'G', _("Groups"), NULL },
        { "create-home", 'm', POPT_ARG_NONE, NULL, 'm', _("Create user's directory if it does not exist"), NULL },
        { "no-create-home", 'M', POPT_ARG_NONE, NULL, 'M', _("Never create user's directory, overrides config"), NULL },
        { "skel", 'k', POPT_ARG_STRING, &pc_skeldir, 0, _("Specify an alternative skeleton directory"), NULL },
        { "selinux-user", 'Z', POPT_ARG_STRING, &pc_selinux_user, 0, _("The SELinux user for user's login"), NULL },
        POPT_TABLEEND
    };
    poptContext pc = NULL;
    struct tools_ctx *tctx = NULL;
    char *groups = NULL;
    char *badgroup = NULL;
    int ret;
    errno_t sret;
    bool in_transaction = false;

    debug_prg_name = argv[0];

    ret = set_locale();
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE,
              "set_locale failed (%d): %s\n", ret, strerror(ret));
        ERROR("Error setting the locale\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* parse parameters */
    pc = poptGetContext(NULL, argc, argv, long_options, 0);
    poptSetOtherOptionHelp(pc, "USERNAME");
    while ((ret = poptGetNextOpt(pc)) > 0) {
        switch (ret) {
            case 'G':
                groups = poptGetOptArg(pc);
                if (!groups) {
                    BAD_POPT_PARAMS(pc, _("Specify group to add to\n"),
                                    ret, fini);
                }
                break;

            case 'm':
                pc_create_home = DO_CREATE_HOME;
                break;

            case 'M':
                pc_create_home = DO_NOT_CREATE_HOME;
                break;
        }
    }

    DEBUG_CLI_INIT(pc_debug);

    if (ret != -1) {
        BAD_POPT_PARAMS(pc, poptStrerror(ret), ret, fini);
    }

    /* username is an argument without --option */
    pc_username = poptGetArg(pc);
    if (pc_username == NULL) {
        BAD_POPT_PARAMS(pc, _("Specify user to add\n"), ret, fini);
    }

    CHECK_ROOT(ret, debug_prg_name);

    ret = init_sss_tools(&tctx);
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE,
              "init_sss_tools failed (%d): %s\n", ret, strerror(ret));
        if (ret == ENOENT) {
            ERROR("Error initializing the tools - no local domain\n");
        } else {
            ERROR("Error initializing the tools\n");
        }
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* if the domain was not given as part of FQDN, default to local domain */
    ret = parse_name_domain(tctx, pc_username);
    if (ret != EOK) {
        ERROR("Invalid domain specified in FQDN\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    if (groups) {
        ret = parse_groups(tctx, groups, &tctx->octx->addgroups);
        if (ret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE,
                  "Cannot parse groups to add the user to\n");
            ERROR("Internal error while parsing parameters\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        ret = parse_group_name_domain(tctx, tctx->octx->addgroups);
        if (ret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE,
                  "Cannot parse FQDN groups to add the user to\n");
            ERROR("Groups must be in the same domain as user\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        /* Check group names in the LOCAL domain */
        ret = check_group_names(tctx, tctx->octx->addgroups, &badgroup);
        if (ret != EOK) {
            ERROR("Cannot find group %1$s in local domain\n", badgroup);
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

    tctx->octx->uid = pc_uid;

    /*
     * Fills in defaults for ops_ctx user did not specify.
     */
    ret = useradd_defaults(tctx, tctx->confdb, tctx->octx,
                           pc_gecos, pc_home, pc_shell,
                           pc_create_home, pc_skeldir);
    if (ret != EOK) {
        ERROR("Cannot set default values\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* arguments processed, go on to actual work */
    if (id_in_range(tctx->octx->uid, tctx->octx->domain) != EOK) {
        ERROR("The selected UID is outside the allowed range\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    tctx->error = sysdb_transaction_start(tctx->sysdb);
    if (tctx->error != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Failed to start transaction\n");
        goto done;
    }
    in_transaction = true;

    /* useradd */
    tctx->error = useradd(tctx, tctx->octx);
    if (tctx->error) {
        goto done;
    }

    tctx->error = sysdb_transaction_commit(tctx->sysdb);
    if (tctx->error) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Failed to commit transaction\n");
        goto done;
    }
    in_transaction = false;

    /* Set SELinux login context - must be done after transaction is done
     * b/c libselinux calls getpwnam */
    ret = set_seuser(tctx->octx->name, pc_selinux_user, NULL);
    if (ret != EOK) {
        ERROR("Cannot set SELinux login context\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* Create user's home directory and/or mail spool */
    if (tctx->octx->create_homedir) {
        /* We need to know the UID of the user, if
         * sysdb did assign it automatically, do a lookup */
        if (tctx->octx->uid == 0) {
            ret = sysdb_getpwnam_sync(tctx,
                                      tctx->octx->name,
                                      tctx->octx);
            if (ret != EOK) {
                ERROR("Cannot get info about the user\n");
                ret = EXIT_FAILURE;
                goto fini;
            }
        }

        ret = create_homedir(tctx->octx->skeldir,
                             tctx->octx->home,
                             tctx->octx->uid,
                             tctx->octx->gid,
                             tctx->octx->umask);
        if (ret == EEXIST) {
            ERROR("User's home directory already exists, not copying "
                  "data from skeldir\n");
        } else if (ret != EOK) {
            ERROR("Cannot create user's home directory: %1$s\n", strerror(ret));
            ret = EXIT_FAILURE;
            goto fini;
        }

        ret = create_mail_spool(tctx,
                                tctx->octx->name,
                                tctx->octx->maildir,
                                tctx->octx->uid,
                                tctx->octx->gid);
        if (ret != EOK) {
            ERROR("Cannot create user's mail spool: %1$s\n", strerror(ret));
            DEBUG(SSSDBG_CRIT_FAILURE,
                  "Cannot create user's mail spool: [%d][%s].\n",
                        ret, strerror(ret));
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

done:
    if (in_transaction) {
        sret = sysdb_transaction_cancel(tctx->sysdb);
        if (sret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE, "Failed to cancel transaction\n");
        }
    }

    if (tctx->error) {
        switch (tctx->error) {
            case ERANGE:
                ERROR("Could not allocate ID for the user - domain full?\n");
                break;

            case EEXIST:
                ERROR("A user or group with the same name or ID already exists\n");
                break;

            default:
                DEBUG(SSSDBG_CRIT_FAILURE, "sysdb operation failed (%d)[%s]\n",
                          tctx->error, strerror(tctx->error));
                ERROR("Transaction error. Could not add user.\n");
                break;
        }
        ret = EXIT_FAILURE;
        goto fini;
    }

    ret = EXIT_SUCCESS;

fini:
    poptFreeContext(pc);
    talloc_free(tctx);
    free(groups);
    exit(ret);
}
Exemple #5
0
int read_mesh(const std::string &exo_file,
              Problem_Description* problem,
              Mesh_Description<INT>* mesh,
              Weight_Description<INT>* weight
	      )
{
  float  version, *xptr, *yptr, *zptr;
  char   elem_type[MAX_STR_LENGTH+1];
  E_Type blk_elem_type;
  
  /*---------------------------Execution Begins--------------------------------*/

  /* Open the ExodusII file */
  int exoid, cpu_ws=0, io_ws=0;
  int mode = EX_READ | problem->int64api;
  if((exoid=ex_open(exo_file.c_str(), mode, &cpu_ws, &io_ws, &version)) < 0)
    {
      Gen_Error(0, "fatal: unable to open ExodusII mesh file");
      return 0;
    }

  /* Read the coordinates, if desired */
  xptr = yptr = zptr = NULL;
  if(problem->read_coords == ELB_TRUE)
    {
      switch(mesh->num_dims)
	{
	case 3:
	  zptr = (mesh->coords)+2*(mesh->num_nodes);
	  /* FALLTHRU */
	case 2:
	  yptr = (mesh->coords)+(mesh->num_nodes);
	  /* FALLTHRU */
	case 1:
	  xptr = mesh->coords;
	}

      if(ex_get_coord(exoid, xptr, yptr, zptr) < 0)
	{
	  Gen_Error(0, "fatal: unable to read coordinate values for mesh");
	  return 0;
	}

    } /* End "if(problem->read_coords == ELB_TRUE)" */

  /* Read the element block IDs */
  std::vector<INT> el_blk_ids(mesh->num_el_blks);
  std::vector<INT> el_blk_cnts(mesh->num_el_blks);

  if(ex_get_elem_blk_ids(exoid, &el_blk_ids[0]) < 0)
    {
      Gen_Error(0, "fatal: unable to read element block IDs");
      return 0;
    }

  /* Read the element connectivity */
  size_t gelem_cnt=0;
  for(size_t cnt=0; cnt < mesh->num_el_blks; cnt++) {
    INT nodes_per_elem, num_attr;
    if(ex_get_elem_block(exoid, el_blk_ids[cnt], elem_type,
                         &(el_blk_cnts[cnt]), &nodes_per_elem,
                         &num_attr) < 0)
      {
	Gen_Error(0, "fatal: unable to read element block");
	return 0;
      }

    blk_elem_type = get_elem_type(elem_type, nodes_per_elem, mesh->num_dims);

    INT *blk_connect = (INT*)malloc(sizeof(INT)*el_blk_cnts[cnt]*nodes_per_elem);
    if(!blk_connect)
      {
	Gen_Error(0, "fatal: insufficient memory");
	return 0;
      }

    /* Get the connectivity for this element block */
    if(ex_get_elem_conn(exoid, el_blk_ids[cnt], blk_connect) < 0)
      {
	Gen_Error(0, "fatal: failed to get element connectivity");
	return 0;
      }

    /* find out if this element block is weighted */
    int wgt = -1;
    if (weight->type & EL_BLK)
      wgt = in_list(el_blk_ids[cnt], weight->elemblk);
    
    /* Fill the 2D global connectivity array */
    if (((problem->type == ELEMENTAL) && (weight->type & EL_BLK)) ||
        ((problem->type == NODAL) && (weight->type & EL_BLK))) {
      
      for(int64_t cnt2=0; cnt2 < el_blk_cnts[cnt]; cnt2++) {
	mesh->elem_type[gelem_cnt] = blk_elem_type;
      
	/* while going through the blocks, take care of the weighting */
	if ((problem->type == ELEMENTAL) && (weight->type & EL_BLK)) {
	  /* is this block weighted */
	  if (wgt >= 0) {
	    /* check if there is a read value */
	    if (weight->vertices[gelem_cnt] >= 1) {
	      /* and if it should be overwritten */
	      if (weight->ow_read)
		weight->vertices[gelem_cnt] = weight->elemblk_wgt[wgt];
	    }
	    else
	      weight->vertices[gelem_cnt] = weight->elemblk_wgt[wgt];
	  }
	  else {
	    /* now check if this weight has been initialized */
	    if (weight->vertices[gelem_cnt] < 1)
	      weight->vertices[gelem_cnt] = 1;
	  }
	}

	for(int64_t cnt3=0; cnt3 < nodes_per_elem; cnt3++) {
	  INT node = blk_connect[cnt3 + cnt2*nodes_per_elem] - 1;
	  assert(node >= 0);
	  mesh->connect[gelem_cnt][cnt3] = node;

	  /* deal with the weighting if necessary */
	  if ((problem->type == NODAL) && (weight->type & EL_BLK)) {
	    /* is this block weighted */
	    if (wgt >= 0) {
	      /* check if I read an exodus file */
	      if (weight->type & READ_EXO) {
		/* check if it can be overwritten */
		if (weight->ow_read) {
		  /* check if it has been overwritten already */
		  if (weight->ow[node]) {
		    weight->vertices[node] =
		      MAX(weight->vertices[node], weight->elemblk_wgt[wgt]);
		  }
		  else {
		    weight->vertices[node] = weight->elemblk_wgt[wgt];
		    weight->ow[node] = 1;   /* read value has been overwritten */
		  }
		}
	      }
	      else {
		weight->vertices[node] =
		  MAX(weight->vertices[node], weight->elemblk_wgt[wgt]);
	      }
	    }
	    else {
	      /* now check if this weight has been initialized */
	      if (weight->vertices[node] < 1)
		weight->vertices[node] = 1;
	    }
	  }
	}
	gelem_cnt++;
      }
    } else {
      // No weights...
      for (int64_t cnt2=0; cnt2 < el_blk_cnts[cnt]; cnt2++) {
	mesh->elem_type[gelem_cnt] = blk_elem_type;

	for (int64_t cnt3=0; cnt3 < nodes_per_elem; cnt3++) {
	  INT node = blk_connect[cnt2*nodes_per_elem + cnt3] - 1;
	  assert(node >= 0);
	  mesh->connect[gelem_cnt][cnt3] = node;
	}

	gelem_cnt++;
      }
    }
    /* Free up memory */
    free(blk_connect);

  } /* End "for(cnt=0; cnt < mesh->num_el_blks; cnt++)" */

  /* if there is a group designator, then parse it here */
  if (problem->groups != NULL) {
    if (!parse_groups(&el_blk_ids[0], &el_blk_cnts[0], mesh, problem)) {
      Gen_Error(0, "fatal: unable to parse group designator");
      ex_close(exoid);
      return 0;
    }
  }
  else problem->num_groups = 1; /* there is always one group */

  /* Close the ExodusII file */
  if(ex_close(exoid) < 0)
    Gen_Error(0, "warning: failed to close ExodusII mesh file");

  return 1;

} /*---------------------------End read_mesh()-------------------------------*/
Exemple #6
0
int parse_data_module( DATAModule *module ) {
  int data_count;
  bool fatalError = TRUE; // if true, catch leads to exit(-1)
  try {
    data_count = module->datas_count;
    for ( int i = 0; i < module->datas_count; i++ ) {
      DataContext ctx; data_context = &ctx;

      const char *tagName = module->datas[i]->tag->image;
      const int tagId = find_tag( tagName );
      if ( DATA_VERBOSE > 4 ) {
	printf("tagName: %s  tagId: %d\n\r", tagName, tagId );
      }
      switch ( tagId ) {
      case TAG_Prereq: parse_prerequisite( module->datas[i] ); break;
      case TAG_BrewFormula: 
	create_brew_formula_table( module->datas_count ); 
	parse_brew_formula( module->datas[i] ); 
	break;
      case TAG_Ban: parse_ban( module->datas[i] ); break;
      case TAG_Command:
	create_command_table( module->datas_count );
	parse_command( module->datas[i] );
	break;
      case TAG_Unique: parse_unique( module->datas[i] ); break;
      case TAG_Disable: parse_disabled( module->datas[i] ); break;
      case TAG_Material: 
	create_material_table( module->datas_count );
	parse_material( module->datas[i] );
	break;
      case TAG_Liquid:
	create_liquid_table( module->datas_count );
	parse_liquid( module->datas[i] );
	break;
      case TAG_God:
	create_god_table( module->datas_count );
	parse_god( module->datas[i] );
	break;
      case TAG_Clan: parse_clan( module->datas[i] ); break;
      case TAG_Faction:
	create_faction_table( module->datas_count, module );
	parse_faction( module->datas[i] );
	break;
      case TAG_Race:
	create_races_table( module->datas_count );
	parse_race( module->datas[i] );
	break;
      case TAG_PCRace:
	create_pcraces_table( module->datas_count );
	parse_pcrace( module->datas[i] );
	break;
      case TAG_Sphere:
	create_spheres_table( module->datas_count );
	parse_sphere( module->datas[i] );
	break;
      case TAG_Group:
	create_groups_table( module->datas_count );
	parse_groups( module->datas[i] );
	break;
      case TAG_Ability: parse_abilities( module->datas[i] ); break;
      case TAG_Class: 
	create_classes_table( module->datas_count );
	parse_classes( module->datas[i] );
	break;
      case TAG_Player: 
	fatalError = FALSE;
	parse_player( module->datas[i] );
	fatalError = TRUE;
	break;
      case TAG_Area: parse_area( module->datas[i] ); break;
      case TAG_Config:
	if ( parse_config( module->datas[i] ) )  // once we have found the right config: skip others
	  return data_count;
	break;
      case TAG_AreaState: parse_area_state( module->datas[i] ); break;
      case TAG_Time: parse_time( module->datas[i] ); break;
      case TAG_Hometown:
	create_hometown_table( module->datas_count );
	parse_hometown( module->datas[i] );
	break;
      case TAG_School:
	create_school_table( module->datas_count );
	parse_school( module->datas[i] );
	break;
      case TAG_Super_Race:
	create_super_race_table( module->datas_count );
	parse_super_race( module->datas[i] );
	break;

      default: p_error("Invalid Tag: %s", tagName ); break;
      }

    }
  } catch (ScriptException e) {
    bug("Error while parsing datas. %s", e.msg );
    if ( fatalError ) {
      bug("FATAL error. Bye!");
      exit(-1);
    }
    else
      return -1;
  }

  dump_GC_info();

  return data_count;
}
Exemple #7
0
int main(int argc, char **argv)
{
    enum {
        NNP = CHAR_MAX + 1,
        RUID,
        EUID,
        RGID,
        EGID,
        REUID,
        REGID,
        CLEAR_GROUPS,
        KEEP_GROUPS,
        GROUPS,
        INHCAPS,
        LISTCAPS,
        CAPBSET,
        SECUREBITS,
        SELINUX_LABEL,
        APPARMOR_PROFILE
    };

    static const struct option longopts[] = {
        {"dump", no_argument, 0, 'd'},
        {"nnp", no_argument, 0, NNP},
        {"no-new-privs", no_argument, 0, NNP},
        {"inh-caps", required_argument, 0, INHCAPS},
        {"list-caps", no_argument, 0, LISTCAPS},
        {"ruid", required_argument, 0, RUID},
        {"euid", required_argument, 0, EUID},
        {"rgid", required_argument, 0, RGID},
        {"egid", required_argument, 0, EGID},
        {"reuid", required_argument, 0, REUID},
        {"regid", required_argument, 0, REGID},
        {"clear-groups", no_argument, 0, CLEAR_GROUPS},
        {"keep-groups", no_argument, 0, KEEP_GROUPS},
        {"groups", required_argument, 0, GROUPS},
        {"bounding-set", required_argument, 0, CAPBSET},
        {"securebits", required_argument, 0, SECUREBITS},
        {"selinux-label", required_argument, 0, SELINUX_LABEL},
        {"apparmor-profile", required_argument, 0, APPARMOR_PROFILE},
        {"help", no_argument, 0, 'h'},
        {"version", no_argument, 0, 'V'},
        {NULL, 0, 0, 0}
    };

    static const ul_excl_t excl[] = {
        /* keep in same order with enum definitions */
        {CLEAR_GROUPS, KEEP_GROUPS, GROUPS},
        {0}
    };
    int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;

    int c;
    struct privctx opts;
    int dumplevel = 0;
    int total_opts = 0;
    int list_caps = 0;

    setlocale(LC_ALL, "");
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);
    atexit(close_stdout);

    memset(&opts, 0, sizeof(opts));

    while ((c = getopt_long(argc, argv, "+dhV", longopts, NULL)) != -1) {
        err_exclusive_options(c, longopts, excl, excl_st);
        total_opts++;
        switch (c) {
        case 'd':
            dumplevel++;
            break;
        case NNP:
            if (opts.nnp)
                errx(EXIT_FAILURE,
                     _("duplicate --no-new-privs option"));
            opts.nnp = 1;
            break;
        case RUID:
            if (opts.have_ruid)
                errx(EXIT_FAILURE, _("duplicate ruid"));
            opts.have_ruid = 1;
            opts.ruid = get_user(optarg, _("failed to parse ruid"));
            break;
        case EUID:
            if (opts.have_euid)
                errx(EXIT_FAILURE, _("duplicate euid"));
            opts.have_euid = 1;
            opts.euid = get_user(optarg, _("failed to parse euid"));
            break;
        case REUID:
            if (opts.have_ruid || opts.have_euid)
                errx(EXIT_FAILURE, _("duplicate ruid or euid"));
            opts.have_ruid = opts.have_euid = 1;
            opts.ruid = opts.euid = get_user(optarg, _("failed to parse reuid"));
            break;
        case RGID:
            if (opts.have_rgid)
                errx(EXIT_FAILURE, _("duplicate rgid"));
            opts.have_rgid = 1;
            opts.rgid = get_group(optarg, _("failed to parse rgid"));
            break;
        case EGID:
            if (opts.have_egid)
                errx(EXIT_FAILURE, _("duplicate egid"));
            opts.have_egid = 1;
            opts.egid = get_group(optarg, _("failed to parse egid"));
            break;
        case REGID:
            if (opts.have_rgid || opts.have_egid)
                errx(EXIT_FAILURE, _("duplicate rgid or egid"));
            opts.have_rgid = opts.have_egid = 1;
            opts.rgid = opts.egid = get_group(optarg, _("failed to parse regid"));
            break;
        case CLEAR_GROUPS:
            if (opts.clear_groups)
                errx(EXIT_FAILURE,
                     _("duplicate --clear-groups option"));
            opts.clear_groups = 1;
            break;
        case KEEP_GROUPS:
            if (opts.keep_groups)
                errx(EXIT_FAILURE,
                     _("duplicate --keep-groups option"));
            opts.keep_groups = 1;
            break;
        case GROUPS:
            if (opts.have_groups)
                errx(EXIT_FAILURE,
                     _("duplicate --groups option"));
            parse_groups(&opts, optarg);
            break;
        case LISTCAPS:
            list_caps = 1;
            break;
        case INHCAPS:
            if (opts.caps_to_inherit)
                errx(EXIT_FAILURE,
                     _("duplicate --inh-caps option"));
            opts.caps_to_inherit = optarg;
            break;
        case CAPBSET:
            if (opts.bounding_set)
                errx(EXIT_FAILURE,
                     _("duplicate --bounding-set option"));
            opts.bounding_set = optarg;
            break;
        case SECUREBITS:
            if (opts.have_securebits)
                errx(EXIT_FAILURE,
                     _("duplicate --securebits option"));
            parse_securebits(&opts, optarg);
            break;
        case SELINUX_LABEL:
            if (opts.selinux_label)
                errx(EXIT_FAILURE,
                     _("duplicate --selinux-label option"));
            opts.selinux_label = optarg;
            break;
        case APPARMOR_PROFILE:
            if (opts.apparmor_profile)
                errx(EXIT_FAILURE,
                     _("duplicate --apparmor-profile option"));
            opts.apparmor_profile = optarg;
            break;
        case 'h':
            usage(stdout);
        case 'V':
            printf(UTIL_LINUX_VERSION);
            return EXIT_SUCCESS;
        case '?':
            usage(stderr);
        default:
            errx(EXIT_FAILURE, _("unrecognized option '%c'"), c);
        }
    }

    if (dumplevel) {
        if (total_opts != dumplevel || optind < argc)
            errx(EXIT_FAILURE,
                 _("--dump is incompatible with all other options"));
        dump(dumplevel);
        return EXIT_SUCCESS;
    }

    if (list_caps) {
        if (total_opts != 1 || optind < argc)
            errx(EXIT_FAILURE,
                 _("--list-caps must be specified alone"));
        list_known_caps();
        return EXIT_SUCCESS;
    }

    if (argc <= optind)
        errx(EXIT_FAILURE, _("No program specified"));

    if ((opts.have_rgid || opts.have_egid)
            && !opts.keep_groups && !opts.clear_groups && !opts.have_groups)
        errx(EXIT_FAILURE,
             _("--[re]gid requires --keep-groups, --clear-groups, or --groups"));

    if (opts.nnp)
        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1)
            err(EXIT_FAILURE, _("disallow granting new privileges failed"));

    if (opts.selinux_label)
        do_selinux_label(opts.selinux_label);
    if (opts.apparmor_profile)
        do_apparmor_profile(opts.apparmor_profile);

    if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
        err(EXIT_FAILURE, _("keep process capabilities failed"));

    /* We're going to want CAP_SETPCAP, CAP_SETUID, and CAP_SETGID if
     * possible.  */
    bump_cap(CAP_SETPCAP);
    bump_cap(CAP_SETUID);
    bump_cap(CAP_SETGID);
    if (capng_apply(CAPNG_SELECT_CAPS) != 0)
        err(SETPRIV_EXIT_PRIVERR, _("activate capabilities"));

    if (opts.have_ruid || opts.have_euid) {
        do_setresuid(&opts);
        /* KEEPCAPS doesn't work for the effective mask. */
        if (capng_apply(CAPNG_SELECT_CAPS) != 0)
            err(SETPRIV_EXIT_PRIVERR, _("reactivate capabilities"));
    }

    if (opts.have_rgid || opts.have_egid)
        do_setresgid(&opts);

    if (opts.have_groups) {
        if (setgroups(opts.num_groups, opts.groups) != 0)
            err(SETPRIV_EXIT_PRIVERR, _("setgroups failed"));
    } else if (opts.clear_groups) {
        gid_t x = 0;
        if (setgroups(0, &x) != 0)
            err(SETPRIV_EXIT_PRIVERR, _("setgroups failed"));
    }

    if (opts.have_securebits)
        if (prctl(PR_SET_SECUREBITS, opts.securebits, 0, 0, 0) != 0)
            err(SETPRIV_EXIT_PRIVERR, _("set process securebits failed"));

    if (opts.bounding_set) {
        do_caps(CAPNG_BOUNDING_SET, opts.bounding_set);
        errno = EPERM;	/* capng doesn't set errno if we're missing CAP_SETPCAP */
        if (capng_apply(CAPNG_SELECT_BOUNDS) != 0)
            err(SETPRIV_EXIT_PRIVERR, _("apply bounding set"));
    }

    if (opts.caps_to_inherit) {
        do_caps(CAPNG_INHERITABLE, opts.caps_to_inherit);
        if (capng_apply(CAPNG_SELECT_CAPS) != 0)
            err(SETPRIV_EXIT_PRIVERR, _("apply capabilities"));
    }

    execvp(argv[optind], argv + optind);

    err(EXIT_FAILURE, _("cannot execute: %s"), argv[optind]);
}
int main(int argc, const char **argv)
{
    gid_t pc_gid = 0;
    int pc_debug = SSSDBG_DEFAULT;
    struct poptOption long_options[] = {
        POPT_AUTOHELP
        { "debug", '\0', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_debug,
                            0, _("The debug level to run with"), NULL },
        { "append-group", 'a', POPT_ARG_STRING, NULL,
                            'a', _("Groups to add this group to"), NULL },
        { "remove-group", 'r', POPT_ARG_STRING, NULL,
                            'r', _("Groups to remove this group from"), NULL },
        { "gid",   'g', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_gid,
                            0, _("The GID of the group"), NULL },
        POPT_TABLEEND
    };
    poptContext pc = NULL;
    struct tools_ctx *tctx = NULL;
    char *addgroups = NULL, *rmgroups = NULL;
    int ret;
    errno_t sret;
    const char *pc_groupname = NULL;
    char *badgroup = NULL;
    bool in_transaction = false;

    debug_prg_name = argv[0];

    ret = set_locale();
    if (ret != EOK) {
        DEBUG(1, ("set_locale failed (%d): %s\n", ret, strerror(ret)));
        ERROR("Error setting the locale\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* parse parameters */
    pc = poptGetContext(NULL, argc, argv, long_options, 0);
    poptSetOtherOptionHelp(pc, "GROUPNAME");
    while ((ret = poptGetNextOpt(pc)) > 0) {
        switch (ret) {
            case 'a':
                addgroups = poptGetOptArg(pc);
                if (addgroups == NULL) {
                    BAD_POPT_PARAMS(pc, _("Specify group to add to\n"),
                                    ret, fini);
                }
                break;

            case 'r':
                rmgroups = poptGetOptArg(pc);
                if (rmgroups == NULL) {
                    BAD_POPT_PARAMS(pc, _("Specify group to remove from\n"),
                                    ret, fini);
                }
                break;
        }
    }

    if (ret != -1) {
        BAD_POPT_PARAMS(pc, poptStrerror(ret), ret, fini);
    }

    /* groupname is an argument without --option */
    pc_groupname = poptGetArg(pc);
    if (pc_groupname == NULL) {
        BAD_POPT_PARAMS(pc, _("Specify group to modify\n"), ret, fini);
    }

    DEBUG_INIT(pc_debug);

    CHECK_ROOT(ret, debug_prg_name);

    ret = init_sss_tools(&tctx);
    if (ret != EOK) {
        DEBUG(1, ("init_sss_tools failed (%d): %s\n", ret, strerror(ret)));
        if (ret == ENOENT) {
            ERROR("Error initializing the tools - no local domain\n");
        } else {
            ERROR("Error initializing the tools\n");
        }
        ret = EXIT_FAILURE;
        goto fini;
    }

    ret = parse_name_domain(tctx, pc_groupname);
    if (ret != EOK) {
        ERROR("Invalid domain specified in FQDN\n");
        ret = EXIT_FAILURE;
        goto fini;
    }
    /* check the username to be able to give sensible error message */
    ret = sysdb_getgrnam_sync(tctx, tctx->sysdb, tctx->octx->name, tctx->octx);
    if (ret != EOK) {
        ERROR("Cannot find group in local domain, "
              "modifying groups is allowed only in local domain\n");
        ret = EXIT_FAILURE;
        goto fini;
    }


    tctx->octx->gid = pc_gid;

    if (addgroups) {
        ret = parse_groups(tctx, addgroups, &tctx->octx->addgroups);
        if (ret != EOK) {
            DEBUG(1, ("Cannot parse groups to add the group to\n"));
            ERROR("Internal error while parsing parameters\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        ret = parse_group_name_domain(tctx, tctx->octx->addgroups);
        if (ret != EOK) {
            DEBUG(1, ("Cannot parse FQDN groups to add the group to\n"));
            ERROR("Member groups must be in the same domain as parent group\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        /* Check group names in the LOCAL domain */
        ret = check_group_names(tctx, tctx->octx->addgroups, &badgroup);
        if (ret != EOK) {
            ERROR("Cannot find group %1$s in local domain, "
                  "only groups in local domain are allowed\n", badgroup);
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

    if (rmgroups) {
        ret = parse_groups(tctx, rmgroups, &tctx->octx->rmgroups);
        if (ret != EOK) {
            DEBUG(1, ("Cannot parse groups to remove the group from\n"));
            ERROR("Internal error while parsing parameters\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        ret = parse_group_name_domain(tctx, tctx->octx->rmgroups);
        if (ret != EOK) {
            DEBUG(1, ("Cannot parse FQDN groups to remove the group from\n"));
            ERROR("Member groups must be in the same domain as parent group\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        /* Check group names in the LOCAL domain */
        ret = check_group_names(tctx, tctx->octx->rmgroups, &badgroup);
        if (ret != EOK) {
            ERROR("Cannot find group %1$s in local domain, "
                  "only groups in local domain are allowed\n", badgroup);
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

    if (id_in_range(tctx->octx->gid, tctx->octx->domain) != EOK) {
        ERROR("The selected GID is outside the allowed range\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    tctx->error = sysdb_transaction_start(tctx->sysdb);
    if (tctx->error != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, ("Failed to start transaction\n"));
        goto done;
    }
    in_transaction = true;

    /* groupmod */
    tctx->error = groupmod(tctx, tctx->sysdb, tctx->octx);
    if (tctx->error) {
        goto done;
    }

    tctx->error = sysdb_transaction_commit(tctx->sysdb);
    if (tctx->error != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, ("Failed to commit transaction\n"));
        goto done;
    }
    in_transaction = false;

    ret = sss_mc_refresh_group(pc_groupname);
    if (ret != EOK) {
        ERROR("NSS request failed (%1$d). Entry might remain in memory "
              "cache.\n", ret);
        /* Nothing we can do about it */
    }

    ret = sss_mc_refresh_grouplist(tctx, tctx->octx->addgroups);
    if (ret != EOK) {
        ERROR("NSS request failed (%1$d). Entry might remain in memory "
              "cache.\n", ret);
        /* Nothing we can do about it */
    }

    ret = sss_mc_refresh_grouplist(tctx, tctx->octx->rmgroups);
    if (ret != EOK) {
        ERROR("NSS request failed (%1$d). Entry might remain in memory "
              "cache.\n", ret);
        /* Nothing we can do about it */
    }

done:
    if (in_transaction) {
        sret = sysdb_transaction_cancel(tctx->sysdb);
        if (sret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE, ("Failed to cancel transaction\n"));
        }
    }
    if (tctx->error) {
        ret = tctx->error;
        DEBUG(1, ("sysdb operation failed (%d)[%s]\n", ret, strerror(ret)));
        switch (ret) {
            case ENOENT:
                ERROR("Could not modify group - check if member group names are correct\n");
                break;

            case EFAULT:
                ERROR("Could not modify group - check if groupname is correct\n");
                break;

            default:
                ERROR("Transaction error. Could not modify group.\n");
                break;
        }

        ret = EXIT_FAILURE;
        goto fini;
    }

    ret = EXIT_SUCCESS;

fini:
    free(addgroups);
    free(rmgroups);
    poptFreeContext(pc);
    talloc_free(tctx);
    exit(ret);
}
Exemple #9
0
bool get_wrap_data(char *wrapid, char *handler, char *cgi, t_wrap *wrap_data, char *user_directory) {
	FILE *fp;
	char line[257], *item, *rest, *pipe;
	struct passwd *pwd;
	bool wrap_oke = false, handler_oke;
	size_t len;

	handler_oke = (handler == NULL);

	wrap_data->chroot = NULL;

	/* WrapID is local userid? */
	if (*wrapid == '~') {
		if ((pwd = getpwnam(wrapid + 1)) == NULL) {
			return false;
		}
		if ((wrap_data->uid = pwd->pw_uid) == 0) {
			return false;
		}
		len = strlen(pwd->pw_dir);
		if ((wrap_data->cgiroot = (char*)malloc(len + strlen(user_directory) + 1)) == NULL) {
			return false;
		}
		memcpy(wrap_data->cgiroot, pwd->pw_dir, len);
		strcpy(wrap_data->cgiroot + len, user_directory);
		if (strncmp(wrap_data->cgiroot, cgi, strlen(wrap_data->cgiroot)) != 0) {
			return false;
		}
		if (lookup_group_ids(wrap_data->uid, &(wrap_data->gid), &(wrap_data->groups)) == -1) {
			return false;
		}

		if (handler_oke) {
			return true;
		}

		wrap_oke = true;
	} else {
		wrap_data->cgiroot = NULL;
	}

	/* Read CGI wrapper configuration */
	if ((fp = fopen(CONFIG_DIR"/cgi-wrapper.conf", "r")) != NULL) {
		line[256] = '\0';

		while (fgets(line, 256, fp) != NULL) {
			rest = uncomment(line);
			if (*rest == '\0') {
				continue;
			}

			if (split_configline(rest, &item, &rest) == 0) {
				strlower(item);
				if (strcmp(item, "cgihandler") == 0) {
					/* CGI handler */
					if (handler_oke) {
						continue;
					}
					do {
						split_string(rest, &item, &rest, ',');
						if (strcmp(handler, item) == 0) {
							handler_oke = true;
							break;
						}
					} while (rest != NULL);
				} else if (strcmp(item, "wrap") == 0) {
					/* Wrap entry */
					if (wrap_oke) {
						continue;
					}

					/* Wrap Id */
					if (split_string(rest, &item, &rest, DELIMITER) == -1) {
						break;
					}
					if (strcmp(item, wrapid) != 0) {
						continue;
					}

					/* Homedirectory */
					if (split_string(rest, &item, &rest, DELIMITER) == -1) {
						break;
					}
					if (*item == '/') {
						/* chroot directory */
						if ((pipe = strchr(item, '|')) != NULL) {
							*pipe = '\0';
							len = pipe - item + 1;
							if ((wrap_data->chroot = (char*)malloc(len)) == NULL) {
								break;
							}
							memcpy(wrap_data->chroot, item, len);
							*pipe = '/';
						}

						if ((len = strlen(item)) == 0) {
							break;
						}
						if ((strncmp(item, cgi, len) != 0) || (*(cgi + len) != '/')) {
							log_error("CGI not in WebsiteRoot");
							break;
						}

						if (pipe != NULL) {
							cgi += (pipe - item);
							item = pipe;
						}

						wrap_data->cgiroot = strdup(item);
					} else if (*item == '~') {
						if ((pwd = getpwnam(item + 1)) == NULL) {
							log_error("invalid username");
							break;
						}
						len = strlen(pwd->pw_dir);
						if ((wrap_data->cgiroot = (char*)malloc(len + strlen(user_directory) + 1)) == NULL) {
							break;
						}
						memcpy(wrap_data->cgiroot, pwd->pw_dir, len);
						strcpy(wrap_data->cgiroot + len, user_directory);
						if (strncmp(wrap_data->cgiroot, cgi, strlen(wrap_data->cgiroot)) != 0) {
							log_error("CGI not in user directory");
							break;
						}
					} else {
						log_error("invalid CGI root");
						break;
					}

					/* User Id */
					split_string(rest, &item, &rest, ':');
					if (parse_userid(item, &(wrap_data->uid)) != 1) {
						log_error("invalid userid");
						break;
					}

					/* Group id */
					if (rest != NULL) {
						if (parse_groups(rest, &(wrap_data->gid), &(wrap_data->groups)) != 1) {
							log_error("syntax error in groupid");
							break;
						}
					} else {
						if (lookup_group_ids(wrap_data->uid, &(wrap_data->gid), &(wrap_data->groups)) != 1) {
							log_error("invalid group (user member of root?)");
							break;
						}
					}

					wrap_oke = true;
				} else {
					/* Crap in configurationfile */
					log_error("syntax error in configurationfile");
					break;
				}
				if (wrap_oke && handler_oke) {
					break;
				}
			} else {
				/* split_string() error */
				break;
			}
		}
		fclose(fp);

		if (wrap_oke == false) {
			log_error("no valid Wrap found");
		}
		if (handler_oke == false) {
			log_error("no valid CGIhandler found");
		}

		return (wrap_oke && handler_oke);
	} else {
		return false;
	}
}