Ejemplo n.º 1
0
/* V_REGEXP -> V_STRING -> V_STRING */
static struct value *rx_match(struct info *info,
                              struct value *rx, struct value *s) {
    struct value *result = NULL;
    const char *str = s->string->str;
    struct re_registers regs;
    int r;

    MEMZERO(&regs, 1);
    r = regexp_match(rx->regexp, str, strlen(str), 0, &regs);
    if (r < -1) {
        result =
            make_exn_value(ref(info), "regexp match failed (internal error)");
    } else {
        char *match = NULL;
        if (r == -1) {
            /* No match */
            match = strdup("");
        } else {
            match = strndup(str + regs.start[0], regs.end[0] - regs.start[0]);
        }
        if (match == NULL) {
            result = info->error->exn;
        } else {
            result = make_value(V_STRING, ref(info));
            result->string = make_string(match);
        }
    }
    return result;
}
Ejemplo n.º 2
0
bool rp_input_trigger( CHAR_DATA *ch, char * string )
{
	char buf[ MAX_STRING_LENGTH ];
	PROG_LIST *prg;

	for ( prg = ch->in_room->progs; prg != NULL; prg = prg->next )
	{
		if ( prg->trig_type == &TRIG_INPUT )
		{
			if ( prg->trig_phrase[ 0 ] == '@' )
			{
				sprintf( buf, "%s\n", string );
				if ( !regexp_match( prg->trig_phrase + 1, buf ) )
					continue;
			}
			else if ( prg->trig_phrase[ 0 ] == '*' )
			{
				if ( str_prefix( string, prg->trig_phrase + 1 ) )
					continue;
			}
			else
			{
				if ( str_cmp( string, prg->trig_phrase ) )
					continue;
			}

			rset_supermob( ch->in_room );
			create_rprog_env( prg->name, prg->code, ch->in_room, ch, NULL, NULL, prg->trig_type, string );
			program_flow();
			release_supermob();
			return ( TRUE );
		}
	}
	return ( FALSE );
}
Ejemplo n.º 3
0
/* Calculates the truth value of the next condition starting from
   p. Returns the point after condition. */
static char *test_condition (char *p, int *condition)
{
    WPanel *panel;
    char arg [256];

    /* Handle one condition */
    for (;*p != '\n' && *p != '&' && *p != '|'; p++){
    if (*p == ' ' || *p == '\t')
        continue;
    if (*p >= 'a')
        panel = cpanel;
    else {
        if (get_other_type () == view_listing)
        panel = other_panel;
        else
        panel = NULL;
    }
    *p |= 0x20;

    switch (*p++){
    case '!':
        p = test_condition (p, condition);
        *condition = ! *condition;
        p--;
        break;
    case 'f':
        p = extract_arg (p, arg);
        *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file);
        break;
    case 'd':
        p = extract_arg (p, arg);
        *condition = panel && regexp_match (arg, panel->cwd, match_file);
        break;
    case 't':
        p = extract_arg (p, arg);
        *condition = panel && test_type (panel, arg);
        break;
    default:
        debug_error = 1;
        break;
    } /* switch */

    } /* while */
    return p;
}
Ejemplo n.º 4
0
void InotifyEvent::Callback(int fd, EventManager::ETYPE event_type) {
	if(event_type==EventManager::TIMEOUT)
		return;
	struct kevent ev;
	int ret;
	ret=kevent(rfds[0], NULL, 0, &ev, 1, NULL);
	if(ret<0) {
		perror("kevent");
		return;
	}


	inotify_file file=inotify_files[(int)ev.udata];
	cfgNode node=cfg;
	while(!!node) {
		char *folder=strdup(node["folder"]());
		if(folder[strlen(folder)-1]=='/')
			folder[strlen(folder)-1]=0;
		struct context ctx;
		memset(&ctx, 0, sizeof(ctx));
		ctx.pid=0;
		if(strcmp(folder, file.filename)!=0) {
			free(folder);
			++node;
			continue;
		}
		if(!node["file"]()) {
			time(&(file.last));
			Cmds::Call(node, ctx);
			free(folder);
			++node;
			continue;
		}
		DIR *dir=opendir(folder);
		struct dirent *file_info=NULL;
		struct stat stat_buf;
		//Does asprintf exists on BSD ?
		char path[1024];
		while((file_info=readdir(dir))!=NULL) {
			if(!regexp_match(node["file"](), file_info->d_name))
				continue;
			bzero(&path, sizeof(path));
			snprintf(path, sizeof(path), "%s/%s", folder, file_info->d_name);
			path[sizeof(path)-1]=0;
			stat(path, &stat_buf);
			if(stat_buf.st_mtime<=file.last && stat_buf.st_ctime<=file.last)
				continue;
			//Ok, file is newer than last check.
			ctx.file=path;
			Cmds::Call(node, ctx);
		}
		time(&(file.last));
		free(folder);
		++node;
	}
}
Ejemplo n.º 5
0
bool UEvents::USB::Match(cfgNode config) {
	printf("%s\n", config.getName());
	if(config["vid"]) {
		char vid[6];//5 should be enough
		sprintf(vid, "%04x", idVendor);
		if(!regexp_match(config["vid"], vid))
			return false;
	}
	if(config["pid"]) {
		char pid[6];//5 should be enough
		sprintf(pid, "%04x", idProduct);
		if(!regexp_match(config["pid"], pid))
			return false;
	}
	if(config["devtype"])
		if(!regexp_match(config["devtype"], devtype))
			return false;
	return true;
}
Ejemplo n.º 6
0
char *hilight_match(const char *channel, const char *nickmask, int level, const char *str)
{
	GSList *tmp;
	const char *color;
	char number[MAX_INT_STRLEN];
	int len, best_match, colornum;

	g_return_val_if_fail(str != NULL, NULL);

	color = NULL; best_match = 0;
	for (tmp = hilights; tmp != NULL; tmp = tmp->next) {
		HILIGHT_REC *rec = tmp->data;

		if ((level & (rec->level > 0 ? rec->level : DEFAULT_HILIGHT_LEVEL)) == 0)
                        continue;
		if (!rec->nick && nickmask != NULL)
                        continue;
		if (rec->channels != NULL && (channel == NULL || strarray_find(rec->channels, channel) == -1))
			continue;
		if (rec->nickmask) {
			if (nickmask == NULL || !match_wildcards(rec->text, nickmask))
				continue;
		} else if (rec->regexp) {
			if (!regexp_match(str, rec->text))
				continue;
		} else if (rec->fullword) {
			if (stristr_full(str, rec->text) == NULL)
				continue;
		} else {
			if (stristr(str, rec->text) == NULL)
				continue;
		}

		len = strlen(rec->text);
		if (best_match < len) {
			best_match = len;
			color = rec->color;
		}
	}

	if (best_match == 0)
		return NULL;

	if (color == NULL) color = settings_get_str("hilight_color");
	if (isalpha((int) *color)) {
		/* color was specified with it's name - try to convert it */
		colornum = mirc_color_name(color);
		if (colornum <= 0) colornum = 16;

		ltoa(number, colornum);
		color = number;
	}
	return g_strconcat(isdigit(*color) ? "\003" : "", color, NULL);
}
Ejemplo n.º 7
0
static void
select_unselect_cmd (const char *title, int cmd)
{
    char *reg_exp, *reg_exp_t;
    int i;
    int c;
    int dirflag = 0;

    reg_exp = input_dialog (title, "", easy_patterns ? "*" : ".");
    if (!reg_exp)
	return;
    if (!*reg_exp) {
	g_free (reg_exp);
	return;
    }

    reg_exp_t = reg_exp;

    /* Check if they specified a directory */
    if (*reg_exp_t == PATH_SEP) {
	dirflag = 1;
	reg_exp_t++;
    }
    if (reg_exp_t[strlen (reg_exp_t) - 1] == PATH_SEP) {
	dirflag = 1;
	reg_exp_t[strlen (reg_exp_t) - 1] = 0;
    }

    for (i = 0; i < current_panel->count; i++) {
	if (!strcmp (current_panel->dir.list[i].fname, ".."))
	    continue;
	if (S_ISDIR (current_panel->dir.list[i].st.st_mode)) {
	    if (!dirflag)
		continue;
	} else {
	    if (dirflag)
		continue;
	}
	c = regexp_match (reg_exp_t, current_panel->dir.list[i].fname,
			  match_file);
	if (c == -1) {
	    message (1, MSG_ERROR, _("  Malformed regular expression  "));
	    g_free (reg_exp);
	    return;
	}
	if (c) {
	    do_file_mark (current_panel, i, cmd);
	}
    }
    g_free (reg_exp);
}
Ejemplo n.º 8
0
//=================================================================================================
bool RSSoft_Engine::decode_regex(rssoft::RS_ReliabilityMatrix& mat_Pi,
		std::string& retrieved_text_msg,
        RSSoft_generic_codeword& retrieved_message,
        const SourceCodec& src_codec,
        const std::string& regexp)
{
	mat_Pi.normalize();
    M = init_M;
    bool found = false;

    for (unsigned int ni=1; (ni<=nb_retries) && !found; ni++) // Retry loop
    {
    	rssoft::MultiplicityMatrix mat_M(mat_Pi, M);
    	const rssoft::gf::GFq_BivariatePolynomial& Q = gskv.run(mat_M);
    	if (!Q.is_in_X()) // Interpolation successful
    	{
    		std::vector<rssoft::gf::GFq_Polynomial>& res_polys = rr.run(Q);

    		if (res_polys.size() > 0) // Factorization successful
    		{
    			final_evaluation.run(res_polys, mat_Pi);
    			const std::vector<rssoft::ProbabilityCodeword>& messages = final_evaluation.get_messages();
    			std::vector<rssoft::ProbabilityCodeword>::const_iterator msg_it = messages.begin();

    			for (; msg_it != messages.end(); ++ msg_it) // Explore results
    			{
                    src_codec.decode(msg_it->get_codeword(), retrieved_text_msg);
                    if (regexp_match(retrieved_text_msg,regexp))
                    {
                        retrieved_message.get_symbols() = msg_it->get_codeword();
                        retrieved_message.set_retry_nb(ni);
                        retrieved_message.set_mm_cost(mat_M.cost());
                        retrieved_message.set_reliability(msg_it->get_probability_score());
                        found = true;
                        break;
                    }
    			} // Explore results
    		} // Factorization successful
    	} // Interpolation successful
        new_multiplicity();
        gskv.init();
        rr.init();
        final_evaluation.init();
    } // Retry loop

    return found;
}
Ejemplo n.º 9
0
/**
 * Check is string matches to regular expression
 *
 * @param __regexp - regular expression to use
 * @param __string - string to check
 * @return non-zero if string matches to regular expression, zero otherwise
 */
BOOL
preg_match (const char *__regexp, const char *__str)
{
    int dummy;
    regexp_t *re;

    /* Compile regexp */
    re = regexp_compile (__regexp);
    if (!re)
    {
        return FALSE;
    }

    dummy = regexp_match (re, __str);

    /* Free memory */
    regexp_free (re);

    return dummy;
}
Ejemplo n.º 10
0
int ignore_check(IRC_SERVER_REC *server, const char *nick, const char *host,
		 const char *channel, const char *text, int level)
{
	GSList *tmp;
	int ok, mask_len, patt_len;
	int best_mask, best_patt, best_ignore;

	g_return_val_if_fail(server != NULL, 0);

	best_mask = 0; best_patt = 0; best_ignore = FALSE;
	for (tmp = ignores; tmp != NULL; tmp = tmp->next) {
		IGNORE_REC *rec = tmp->data;

		if ((level & (rec->level|rec->except_level)) == 0)
			continue;

		/* server */
		if (rec->servertag != NULL && g_strcasecmp(server->tag, rec->servertag) != 0)
			continue;

		/* channel list */
		if (rec->channels != NULL) {
			if (channel == NULL || !ischannel(*channel))
				continue;
			if (strarray_find(rec->channels, channel) == -1)
				continue;
		}

		/* nick mask */
		mask_len = 0;
		if (rec->mask != NULL) {
			if (nick == NULL)
				continue;

			mask_len = strlen(rec->mask);
			if (mask_len <= best_mask) continue;

			ok = ((host == NULL || *host == '\0')) ?
				match_wildcards(rec->mask, nick) :
				irc_mask_match_address(rec->mask, nick, host);
			if (!ok) {
                                /* nick didn't match, but maybe this is a reply to nick? */
				if (!rec->replies || channel == NULL || text == NULL ||
				    !ignore_check_replies(rec, server, channel, text))
					continue;
			}
		}

		/* pattern */
		patt_len = 0;
		if (rec->pattern != NULL) {
			if (!mask_len && !best_mask) {
				patt_len = strlen(rec->pattern);
				if (patt_len <= best_patt) continue;
			}

			ok = rec->regexp ? regexp_match(text, rec->pattern) :
				rec->fullword ? stristr_full(text, rec->pattern) != NULL :
				stristr(text, rec->pattern) != NULL;
			if (!ok) continue;
		}

		if (mask_len || best_mask)
			best_mask = mask_len;
		else if (patt_len)
			best_patt = patt_len;

		best_ignore = (rec->level & level) != 0;
	}

	return best_ignore;
}
Ejemplo n.º 11
0
/* The second argument is action, i.e. Open, View or Edit
 *
 * This function returns:
 *
 * -1 for a failure or user interrupt
 * 0 if no command was run
 * 1 if some command was run
 *
 * If action == "View" then a parameter is checked in the form of "View:%d",
 * if the value for %d exists, then the viewer is started up at that line number.
 */
int
regex_command (const char *filename, const char *action, int *move_dir)
{
    char *p, *q, *r, c;
    int file_len = strlen (filename);
    int found = 0;
    int error_flag = 0;
    int ret = 0;
    struct stat mystat;
    int view_at_line_number;
    char *include_target;
    int include_target_len;
    int have_type = 0;		/* Flag used by regex_check_type() */

    /* Check for the special View:%d parameter */
    if (strncmp (action, "View:", 5) == 0) {
	view_at_line_number = atoi (action + 5);
	action = "View";
    } else {
	view_at_line_number = 0;
    }

    if (data == NULL) {
	char *extension_file;
	int mc_user_ext = 1;
	int home_error = 0;

	extension_file = concat_dir_and_file (home_dir, MC_USER_EXT);
	if (!exist_file (extension_file)) {
	    g_free (extension_file);
	  check_stock_mc_ext:
	    extension_file = concat_dir_and_file (mc_home, MC_LIB_EXT);
	    mc_user_ext = 0;
	}
	data = load_file (extension_file);
	g_free (extension_file);
	if (data == NULL)
	    return 0;

	if (!strstr (data, "default/")) {
	    if (!strstr (data, "regex/") && !strstr (data, "shell/")
		&& !strstr (data, "type/")) {
		g_free (data);
		data = NULL;
		if (mc_user_ext) {
		    home_error = 1;
		    goto check_stock_mc_ext;
		} else {
		    char *msg;
		    char *msg2;
		    msg =
			g_strconcat (" ", mc_home, MC_LIB_EXT,
				     _(" file error "), (char *) NULL);
		    msg2 =
			g_strconcat (_("Format of the "), mc_home,
				     _("mc.ext file has changed\n"
				       "with version 3.0. It seems that installation\n"
				       "failed. Please fetch a fresh new copy from the\n"
				       "Midnight Commander package."),
				     (char *) NULL);
		    message (1, msg, "%s", msg2);
		    g_free (msg);
		    g_free (msg2);
		    return 0;
		}
	    }
	}
	if (home_error) {
	    char *msg;
	    char *msg2;
	    msg =
		g_strconcat (" ~/", MC_USER_EXT, _(" file error "), (char *) NULL);
	    msg2 =
		g_strconcat (_("Format of the "), "~/", MC_USER_EXT,
			     _(" file has changed\n"
			       "with version 3.0. You may want either to\n"
			       "copy it from "), mc_home,
			     _("mc.ext or use that\n"
			       "file as an example of how to write it.\n"),
			     mc_home,
			     _("mc.ext will be used for this moment."),
			     (char *) NULL);
	    message (1, msg, "%s", msg2);
	    g_free (msg);
	    g_free (msg2);
	}
    }
    mc_stat (filename, &mystat);

    include_target = NULL;
    include_target_len = 0;
    for (p = data; *p; p++) {
	for (q = p; *q == ' ' || *q == '\t'; q++);
	if (*q == '\n' || !*q)
	    p = q;		/* empty line */
	if (*p == '#')		/* comment */
	    while (*p && *p != '\n')
		p++;
	if (*p == '\n')
	    continue;
	if (!*p)
	    break;
	if (p == q) {		/* i.e. starts in the first column, should be
				 * keyword/descNL
				 */
	    found = 0;
	    q = strchr (p, '\n');
	    if (q == NULL)
		q = strchr (p, 0);
	    c = *q;
	    *q = 0;
	    if (include_target) {
		if ((strncmp (p, "include/", 8) == 0)
		    && (strncmp (p + 8, include_target, include_target_len)
			== 0))
		    found = 1;
	    } else if (!strncmp (p, "regex/", 6)) {
		p += 6;
		/* Do not transform shell patterns, you can use shell/ for
		 * that
		 */
		if (regexp_match (p, filename, match_regex))
		    found = 1;
	    } else if (!strncmp (p, "directory/", 10)) {
		if (S_ISDIR (mystat.st_mode)
		    && regexp_match (p + 10, filename, match_regex))
		    found = 1;
	    } else if (!strncmp (p, "shell/", 6)) {
		p += 6;
		if (*p == '.' && file_len >= (q - p)) {
		    if (!strncmp (p, filename + file_len - (q - p), q - p))
			found = 1;
		} else {
		    if (q - p == file_len && !strncmp (p, filename, q - p))
			found = 1;
		}
	    } else if (!strncmp (p, "type/", 5)) {
		int res;
		p += 5;
		res = regex_check_type (filename, p, &have_type);
		if (res == 1)
		    found = 1;
		if (res == -1)
		    error_flag = 1;	/* leave it if file cannot be opened */
	    } else if (!strncmp (p, "default/", 8)) {
		found = 1;
	    }
	    *q = c;
	    p = q;
	    if (!*p)
		break;
	} else {		/* List of actions */
	    p = q;
	    q = strchr (p, '\n');
	    if (q == NULL)
		q = strchr (p, 0);
	    if (found && !error_flag) {
		r = strchr (p, '=');
		if (r != NULL) {
		    c = *r;
		    *r = 0;
		    if (strcmp (p, "Include") == 0) {
			char *t;

			include_target = p + 8;
			t = strchr (include_target, '\n');
			if (t)
			    *t = 0;
			include_target_len = strlen (include_target);
			if (t)
			    *t = '\n';

			*r = c;
			p = q;
			found = 0;

			if (!*p)
			    break;
			continue;
		    }
		    if (!strcmp (action, p)) {
			*r = c;
			for (p = r + 1; *p == ' ' || *p == '\t'; p++);

			/* Empty commands just stop searching
			 * through, they don't do anything
			 *
			 * We need to copy the filename because exec_extension
			 * may end up invoking update_panels thus making the
			 * filename parameter invalid (ie, most of the time,
			 * we get filename as a pointer from current_panel->dir).
			 */
			if (p < q) {
			    char *filename_copy = g_strdup (filename);

			    exec_extension (filename_copy, r + 1, move_dir,
					    view_at_line_number);
			    g_free (filename_copy);

			    ret = 1;
			}
			break;
		    } else
			*r = c;
		}
	    }
	    p = q;
	    if (!*p)
		break;
	}
    }
    if (error_flag)
	return -1;
    return ret;
}
Ejemplo n.º 12
0
/*
 * Invoke the "file" command on the file and match its output against PTR.
 * have_type is a flag that is set if we already have tried to determine
 * the type of that file.
 * Return 1 for match, 0 for no match, -1 errors.
 */
static int
regex_check_type (const char *filename, const char *ptr, int *have_type)
{
    int found = 0;

    /* Following variables are valid if *have_type is 1 */
    static char content_string[2048];
    static int content_shift = 0;
    static int got_data = 0;

    if (!use_file_to_check_type) {
	return 0;
    }

    if (!*have_type) {
	char *realname;		/* name used with "file" */
	char *localfile;
	/* Don't repeate even unsuccessful checks */
	*have_type = 1;

	localfile = mc_getlocalcopy (filename);
	if (!localfile)
	    return -1;

	realname = localfile;
	got_data =
	    get_file_type_local (localfile, content_string,
				 sizeof (content_string));
	mc_ungetlocalcopy (filename, localfile, 0);

	if (got_data > 0) {
	    char *pp;

	    /* Paranoid termination */
	    content_string[sizeof (content_string) - 1] = 0;

	    if ((pp = strchr (content_string, '\n')) != 0)
		*pp = 0;

	    if (!strncmp (content_string, realname, strlen (realname))) {
		/* Skip "realname: " */
		content_shift = strlen (realname);
		if (content_string[content_shift] == ':') {
		    /* Solaris' file prints tab(s) after ':' */
		    for (content_shift++;
			 content_string[content_shift] == ' '
			 || content_string[content_shift] == '\t';
			 content_shift++);
		}
	    }
	} else {
	    /* No data */
	    content_string[0] = 0;
	}
	g_free (realname);
    }

    if (got_data == -1) {
	return -1;
    }

    if (content_string[0]
	&& regexp_match (ptr, content_string + content_shift, match_regex)) {
	found = 1;
    }

    return found;
}
Ejemplo n.º 13
0
Archivo: user.c Proyecto: dborca/mc
/* Calculates the truth value of the next condition starting from
   p. Returns the point after condition. */
static char *test_condition (WEdit *edit_widget, char *p, int *condition)
{
    WPanel *panel;
    char arg [256];

    /* Handle one condition */
    for (;*p != '\n' && *p != '&' && *p != '|'; p++){
                /* support quote space .mnu */
	if ((*p == ' ' && *(p-1) != '\\') || *p == '\t')
	    continue;
	if (*p >= 'a')
	    panel = current_panel;
	else {
	    if (get_other_type () == view_listing)
		panel = other_panel;
	    else
		panel = NULL;
	}
	*p |= 0x20;

	switch (*p++){
	case '!':
	    p = test_condition (edit_widget, p, condition);
	    *condition = ! *condition;
	    p--;
	    break;
	case 'f': /* file name pattern */
	    p = extract_arg (p, arg, sizeof (arg));
	    *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file, 0);
	    break;
	case 'y': /* syntax pattern */
            if (edit_widget && edit_widget->syntax_type) {
	        p = extract_arg (p, arg, sizeof (arg));
	        *condition = panel &&
                    regexp_match (arg, edit_widget->syntax_type, match_normal, 0);
	    }
            break;
	case 'd':
	    p = extract_arg (p, arg, sizeof (arg));
	    *condition = panel && regexp_match (arg, panel->cwd, match_file, 0);
	    break;
	case 't':
	    p = extract_arg (p, arg, sizeof (arg));
	    *condition = panel && test_type (panel, arg);
	    break;
	case 'x': /* executable */
	{
	    struct stat status;
	    
	    p = extract_arg (p, arg, sizeof (arg));
	    if (stat (arg, &status) == 0)
		*condition = is_exe (status.st_mode);
	    else
		*condition = 0; 
	    break;
	}
	default:
	    debug_error = 1;
	    break;
	} /* switch */

    } /* while */
    return p;
}
Ejemplo n.º 14
0
Archivo: regexp.c Proyecto: mchf/augeas
int regexp_matches_empty(struct regexp *r) {
    return regexp_match(r, "", 0, 0, NULL) == 0;
}
Ejemplo n.º 15
0
/*
 * Lens primitives
 */
struct value *lns_make_prim(enum lens_tag tag, struct info *info,
                            struct regexp *regexp, struct string *string) {
    struct lens *lens = NULL;
    struct value *exn = NULL;
    struct fa *fa_slash = NULL;
    struct fa *fa_key = NULL;
    struct fa *fa_isect = NULL;

    /* Typecheck */
    if (tag == L_KEY) {
        exn = str_to_fa(info, "(.|\n)*/(.|\n)*", &fa_slash);
        if (exn != NULL)
            goto error;

        exn = regexp_to_fa(regexp, &fa_key);
        if (exn != NULL)
            goto error;

        fa_isect = fa_intersect(fa_slash, fa_key);
        if (! fa_is_basic(fa_isect, FA_EMPTY)) {
            exn = make_exn_value(info,
                                 "The key regexp /%s/ matches a '/'",
                                 regexp->pattern->str);
            goto error;
        }
        fa_free(fa_isect);
        fa_free(fa_key);
        fa_free(fa_slash);
        fa_isect = fa_key = fa_slash = NULL;
    } else if (tag == L_LABEL) {
        if (strchr(string->str, SEP) != NULL) {
            exn = make_exn_value(info,
                                 "The label string \"%s\" contains a '/'",
                                 string->str);
            goto error;
        }
    } else if (tag == L_DEL) {
        int cnt;
        const char *dflt = string->str;
        cnt = regexp_match(regexp, dflt, strlen(dflt), 0, NULL);
        if (cnt != strlen(dflt)) {
            char *s = escape(dflt, -1);
            char *r = escape(regexp->pattern->str, -1);
            exn = make_exn_value(info,
                   "del: the default value '%s' does not match /%s/",
                   s, r);
            FREE(s);
            FREE(r);
            goto error;
        }
    }

    /* Build the actual lens */
    lens = make_lens(tag, info);
    lens->regexp = regexp;
    lens->string = string;
    lens->key = (tag == L_KEY || tag == L_LABEL || tag == L_SEQ);
    lens->value = (tag == L_STORE);
    lens->consumes_value = (tag == L_STORE);
    lens->atype = regexp_make_empty(info);
    if (tag == L_DEL || tag == L_STORE || tag == L_KEY) {
        lens->ctype = ref(regexp);
    } else if (tag == L_LABEL || tag == L_SEQ || tag == L_COUNTER) {
        lens->ctype = regexp_make_empty(info);
    } else {
        assert(0);
    }
    return make_lens_value(lens);
 error:
    fa_free(fa_isect);
    fa_free(fa_key);
    fa_free(fa_slash);
    return exn;
}
Ejemplo n.º 16
0
static int
component_match(krb5_context context,
		rule_component *rc,
		pkinit_cert_matching_data *md,
		krb5_principal princ)
{
    int match = 0;
    int i;
    krb5_principal p;
    char *princ_string;

    switch (rc->kwval_type) {
    case kwvaltype_regexp:
	switch (rc->kw_type) {
	case kw_subject:
	    match = regexp_match(context, rc, md->subject_dn);
	    break;
	case kw_issuer:
	    match = regexp_match(context, rc, md->issuer_dn);
	    break;
	case kw_san:
	    if (md->sans == NULL)
		break;
	    for (i = 0, p = md->sans[i]; p != NULL; p = md->sans[++i]) {
		krb5_unparse_name(context, p, &princ_string);
		match = regexp_match(context, rc, princ_string);
		krb5_free_unparsed_name(context, princ_string);
		if (match)
		    break;
	    }
	    break;
	default:
	    pkiDebug("%s: keyword %s, keyword value %s mismatch\n",
		     __FUNCTION__, keyword2string(rc->kw_type),
		     kwval2string(kwvaltype_regexp));
	    break;
	}
	break;
    case kwvaltype_list:
	switch(rc->kw_type) {
	case kw_eku:
	    pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n",
		     __FUNCTION__, keyword2string(rc->kw_type),
		     rc->eku_bits, md->eku_bits);
	    if ((rc->eku_bits & md->eku_bits) == rc->eku_bits)
		match = 1;
	    break;
	case kw_ku:
	    pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n",
		     __FUNCTION__, keyword2string(rc->kw_type),
		     rc->ku_bits, md->ku_bits);
	    if ((rc->ku_bits & md->ku_bits) == rc->ku_bits)
		match = 1;
	    break;
	default:
	    pkiDebug("%s: keyword %s, keyword value %s mismatch\n",
		     __FUNCTION__, keyword2string(rc->kw_type),
		     kwval2string(kwvaltype_regexp));
	    break;
	}
	break;
    case kwvaltype_principal:
        if (md->sans == NULL)
            break;
#ifdef DEBUG
        krb5_unparse_name(context, princ, &princ_string);
#endif
        for (i = 0, p = md->sans[i]; p != NULL; p = md->sans[++i]) {
#ifdef DEBUG
            char *san_string;

            krb5_unparse_name(context, p, &san_string);
            pkiDebug("%s: comparing principal '%s' with cert SAN '%s'\n",
                    __FUNCTION__, princ_string, san_string);
#endif
            if (krb5_principal_compare_flags(context, p, princ,
                        KRB5_PRINCIPAL_COMPARE_CASEFOLD)) {
                match = 1;
                break;
            }
            if (match)
                break;
        }
	break;
    default:
	pkiDebug("%s: unknown keyword value type %d\n",
		 __FUNCTION__, rc->kwval_type);
	break;
    }
    pkiDebug("%s: returning match = %d\n", __FUNCTION__, match);
    return match;
}
Ejemplo n.º 17
0
HRESULT regexp_string_match(script_ctx_t *ctx, jsdisp_t *re, jsstr_t *str, jsval_t *r)
{
    static const WCHAR indexW[] = {'i','n','d','e','x',0};
    static const WCHAR inputW[] = {'i','n','p','u','t',0};
    static const WCHAR lastIndexW[] = {'l','a','s','t','I','n','d','e','x',0};

    RegExpInstance *regexp = (RegExpInstance*)re;
    match_result_t *match_result;
    unsigned match_cnt, i;
    jsdisp_t *array;
    HRESULT hres;

    if(!(regexp->jsregexp->flags & REG_GLOB)) {
        match_state_t *match;
        heap_pool_t *mark;

        mark = heap_pool_mark(&ctx->tmp_heap);
        match = alloc_match_state(regexp->jsregexp, &ctx->tmp_heap, str->str);
        if(!match) {
            heap_pool_clear(mark);
            return E_OUTOFMEMORY;
        }

        hres = regexp_match_next(ctx, &regexp->dispex, 0, str, &match);
        if(FAILED(hres)) {
            heap_pool_clear(mark);
            return hres;
        }

        if(r) {
            if(hres == S_OK) {
                IDispatch *ret;

                hres = create_match_array(ctx, str, match, &ret);
                if(SUCCEEDED(hres))
                    *r = jsval_disp(ret);
            }else {
                *r = jsval_null();
            }
        }

        heap_pool_clear(mark);
        return S_OK;
    }

    hres = regexp_match(ctx, &regexp->dispex, str, FALSE, &match_result, &match_cnt);
    if(FAILED(hres))
        return hres;

    if(!match_cnt) {
        TRACE("no match\n");

        if(r)
            *r = jsval_null();
        return S_OK;
    }

    hres = create_array(ctx, match_cnt, &array);
    if(FAILED(hres))
        return hres;

    for(i=0; i < match_cnt; i++) {
        jsstr_t *tmp_str;

        tmp_str = jsstr_substr(str, match_result[i].index, match_result[i].length);
        if(!tmp_str) {
            hres = E_OUTOFMEMORY;
            break;
        }

        hres = jsdisp_propput_idx(array, i, jsval_string(tmp_str));
        jsstr_release(tmp_str);
        if(FAILED(hres))
            break;
    }

    while(SUCCEEDED(hres)) {
        hres = jsdisp_propput_name(array, indexW, jsval_number(match_result[match_cnt-1].index));
        if(FAILED(hres))
            break;

        hres = jsdisp_propput_name(array, lastIndexW,
                jsval_number(match_result[match_cnt-1].index + match_result[match_cnt-1].length));
        if(FAILED(hres))
            break;

        hres = jsdisp_propput_name(array, inputW, jsval_string(str));
        break;
    }

    heap_free(match_result);

    if(SUCCEEDED(hres) && r)
        *r = jsval_obj(array);
    else
        jsdisp_release(array);
    return hres;
}
Ejemplo n.º 18
0
static bool
check_restriction(SordModel*      model,
                  const URIs*     uris,
                  const SordNode* literal,
                  const SordNode* type,
                  const SordNode* restriction)
{
	size_t      len = 0;
	const char* str = (const char*)sord_node_get_string_counted(literal, &len);
	++n_restrictions;

	// Check xsd:pattern
	SordIter* p = sord_search(model, restriction, uris->xsd_pattern, 0, 0);
	if (p) {
		const SordNode* pat  = sord_iter_get_node(p, SORD_OBJECT);
		const bool      good = regexp_match(sord_node_get_string(pat), str);
		if (!good) {
			fprintf(stderr, "`%s' does not match <%s> pattern `%s'\n",
			        sord_node_get_string(literal),
			        sord_node_get_string(type),
			        sord_node_get_string(pat));
		}

		sord_iter_free(p);
		return good;
	}

	/* We'll do some comparison tricks for xsd:decimal types, where
	   lexicographical comparison would be incorrect.  Note that if the
	   literal's type is a descendant of xsd:decimal, we'll end up checking it
	   against the xsd:decimal pattern so there's no need to validate digits
	   here.  At worst we'll get a false positive but it will fail later. */
	const bool is_decimal = is_descendant_of(
		model, uris, type, uris->xsd_decimal, uris->owl_onDatatype);

	// Check xsd:minInclusive
	SordIter* l = sord_search(model, restriction, uris->xsd_minInclusive, 0, 0);
	if (l) {
		const SordNode* lower     = sord_iter_get_node(l, SORD_OBJECT);
		size_t          lower_len = 0;
		const char*     lower_str = (const char*)sord_node_get_string_counted(lower, &lower_len);
		bool            good      = false;
		if (!is_decimal || len == lower_len) {
			 // Not decimal, or equal lengths, strcmp
			good = (strcmp(str, lower_str) >= 0);
		} else {
			// Decimal with different length, only good if longer than the min
			good = (len > lower_len);
		}
		if (!good) {
			fprintf(stderr, "`%s' is not >= <%s> minimum `%s'\n",
			        sord_node_get_string(literal),
			        sord_node_get_string(type),
			        sord_node_get_string(lower));
		}

		sord_iter_free(l);
		return good;
	}

	// Check xsd:maxInclusive
	SordIter* u = sord_search(model, restriction, uris->xsd_maxInclusive, 0, 0);
	if (u) {
		const SordNode* upper     = sord_iter_get_node(u, SORD_OBJECT);
		size_t          upper_len = 0;
		const char*     upper_str = (const char*)sord_node_get_string_counted(upper, &upper_len);
		bool            good      = false;
		if (!is_decimal || len == upper_len) {
			 // Not decimal, or equal lengths, strcmp
			good = (strcmp(str, upper_str) <= 0);
		} else {
			// Decimal with different length, only good if shorter than the max
			good = (len < upper_len);
		}
		if (!good) {
			fprintf(stderr, "`%s' is not <= <%s> maximum `%s'\n",
			        sord_node_get_string(literal),
			        sord_node_get_string(type),
			        sord_node_get_string(upper));
		}

		sord_iter_free(u);
		return good;
	}

	--n_restrictions;
	return true;  // Unknown restriction, be quietly tolerant
}
Ejemplo n.º 19
0
static int
component_match(krb5_context context,
		rule_component *rc,
		pkinit_cert_matching_data *md)
{
    int match = 0;
    int i;
    krb5_principal p;
    char *princ_string;

    switch (rc->kwval_type) {
    case kwvaltype_regexp:
	switch (rc->kw_type) {
	case kw_subject:
	    match = regexp_match(context, rc, md->subject_dn);
	    break;
	case kw_issuer:
	    match = regexp_match(context, rc, md->issuer_dn);
	    break;
	case kw_san:
	    if (md->sans == NULL)
		break;
	    for (i = 0, p = md->sans[i]; p != NULL; p = md->sans[++i]) {
		krb5_unparse_name(context, p, &princ_string);
		match = regexp_match(context, rc, princ_string);
		krb5_free_unparsed_name(context, princ_string);
		if (match)
		    break;
	    }
	    break;
	default:
	    pkiDebug("%s: keyword %s, keyword value %s mismatch\n",
		     __FUNCTION__, keyword2string(rc->kw_type),
		     kwval2string(kwvaltype_regexp));
	    break;
	}
	break;
    case kwvaltype_list:
	switch(rc->kw_type) {
	case kw_eku:
	    pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n",
		     __FUNCTION__, keyword2string(rc->kw_type),
		     rc->eku_bits, md->eku_bits);
	    if ((rc->eku_bits & md->eku_bits) == rc->eku_bits)
		match = 1;
	    break;
	case kw_ku:
	    pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n",
		     __FUNCTION__, keyword2string(rc->kw_type),
		     rc->ku_bits, md->ku_bits);
	    if ((rc->ku_bits & md->ku_bits) == rc->ku_bits)
		match = 1;
	    break;
	default:
	    pkiDebug("%s: keyword %s, keyword value %s mismatch\n",
		     __FUNCTION__, keyword2string(rc->kw_type),
		     kwval2string(kwvaltype_regexp));
	    break;
	}
	break;
    default:
	pkiDebug("%s: unknown keyword value type %d\n",
		 __FUNCTION__, rc->kwval_type);
	break;
    }
    pkiDebug("%s: returning match = %d\n", __FUNCTION__, match);
    return match;
}
Ejemplo n.º 20
0
/**
 * Check content of file in regexp mode
 *
 * @param __name - name of file to check
 * @param __full_name - full name of file
 * @param __options - finding options
 * @param __res_wnd - window with search results
 * @return zero if file in unwanted, non-zero otherwise
 */
static BOOL
check_regexp_content (const wchar_t *__name, const wchar_t *__full_name,
                      const action_find_options_t *__options,
                      action_find_res_wnd_t *__res_wnd)
{
  vfs_file_t file;
  char buf[RE_BUF_SIZE];
  char *pchar;
  int res, i;
  BOOL matched = FALSE, finito = FALSE;

#ifdef __FILE_OFFSET64
  file = vfs_open (__full_name, O_LAGEFILE, 0);
#else
  file = vfs_open (__full_name, 0, 0);
#endif

  if (file == NULL)
    {
      /* Error opening file */
      return FALSE;
    }

  for (;;)
    {
      /* Read next buffer from file */
      res = vfs_read (file, buf, RE_BUF_SIZE - 1);

      if (res <= 0)
        {
          /* Assume file is over and we should stop greping */
          break;
        }

      buf[res] = 0;
      pchar = buf;
      i = 0;

      for (;;)
        {
          /*
           * TODO: Or we should split read buffer onto separate strings?
           */

          if (regexp_match (__options->re_content, pchar))
            {
              matched = TRUE;
              break;
            }

          /* Read buffer could contain zero characters */
          /* We should overview all parts of buffer */
          /* (between all pairs of zero characters ) */
          for (; i < res; ++i)
            {
              if (buf[i] == 0)
                {
                  break;
                }
            }

          if (i >= res)
            {
              /* Buffer is over */
              break;
            }

          ++i;
          pchar = buf + i;

          hook_call (L"switch-task-hook", NULL);

          if (ACTION_PERFORMED (__res_wnd))
            {
              finito = TRUE;
              break;
            }
        }

      if (finito)
        {
          break;
        }
    }

  vfs_close (file);

  return matched;
}
Ejemplo n.º 21
0
void InotifyEvent::Callback(int fd, EventManager::ETYPE event_type) {
	if(event_type==EventManager::TIMEOUT)
		return;
	char buffer[4096];
	int ret;
	int i=0;
	
	ret=read(this->rfds[0], buffer, 4096);
	if(ret<0)
		perror("read");
	if(ret==0)
		sleep(5);
	char *path=NULL;
	while(i<ret) {
		const char *name = NULL;
		struct inotify_event *event;
		event = (struct inotify_event *) &buffer[i];
		if (event->len)
			name = &buffer[i] + sizeof (struct inotify_event);
		if(path) {
			free(path);
			path=NULL;
		}

		i += sizeof (struct inotify_event) + event->len;
		if(event->mask!=IN_CREATE && event->mask!=IN_MOVED_TO && event->mask!=IN_CLOSE_WRITE)
			continue;

		int j;
		for(j=0;inotify_files[j].filename;j++) {
			if(inotify_files[j].wd==event->wd)
				break;
		}
		if(!inotify_files[j].filename) {
			printf("Couldn't find recorded watch descriptor!\n");
			continue;
		}
		asprintf(&path, "%s/%s", inotify_files[j].filename, name);

		char *filename=inotify_files[j].filename;
		int i;
		for(i=0;i<n_cfg;++i) {
			cfgNode node=cfg[i][0];
			if(strcmp(node.getName(), "inotify")!=0) 
				throw "Got a non inotify-node in our config nodes !";
			char *folder=strdup(node["folder"]);
			if(folder[strlen(folder)-1]=='/')
				folder[strlen(folder)-1]=0;
			struct context ctx;
			memset(&ctx, 0, sizeof(ctx));
			ctx.pid=0;
			ctx.file=path;
			if(strcmp(folder, filename)==0) {
				if(!node["file"]) 
					Cmds::Call(node, ctx);
				else if(regexp_match(node["file"], name))
					Cmds::Call(node, ctx);
			}
			free(folder);
		}
	}
	if(path)
		free(path);
}