Example #1
0
/* splits an input string into a date-time part and an optional operator part.
   operator can be any of "=", "<", ">", "<=", ">=" and "<>".
   range notation [x;y] can also be used
   datetime values should follow the pattern YYYY:mm:dd HH:MM:SS
   but only year part is mandatory

   datetime and operator are returned as pointers to null terminated strings in g_mallocated
   memory (to be g_free'd after use) - or NULL if no match is found.
*/
void dt_collection_split_operator_datetime(const gchar *input, char **number1, char **number2, char **operator)
{
  GRegex *regex;
  GMatchInfo *match_info;
  int match_count;

  *number1 = *number2 = *operator= NULL;

  // we test the range expression first
  // 2 elements : date-time1 and  date-time2
  regex = g_regex_new("^\\s*\\[\\s*(\\d{4}[:\\d\\s]*)\\s*;\\s*(\\d{4}[:\\d\\s]*)\\s*\\]\\s*$", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    gchar *txt = g_match_info_fetch(match_info, 1);
    gchar *txt2 = g_match_info_fetch(match_info, 2);

    *number1 = _dt_collection_compute_datetime(">=", txt);
    *number2 = _dt_collection_compute_datetime("<=", txt2);
    *operator= g_strdup("[]");

    g_free(txt);
    g_free(txt2);
    g_match_info_free(match_info);
    g_regex_unref(regex);
    return;
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);

  // and we test the classic comparaison operators
  // 2 elements : operator and date-time
  regex = g_regex_new("^\\s*(=|<|>|<=|>=|<>)?\\s*(\\d{4}[:\\d\\s]*)?\\s*%?\\s*$", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    *operator= g_match_info_fetch(match_info, 1);
    gchar *txt = g_match_info_fetch(match_info, 2);

    if(strcmp(*operator, "") == 0 || strcmp(*operator, "=") == 0 || strcmp(*operator, "<>") == 0)
      *number1 = dt_util_dstrcat(*number1, "%s%%", txt);
    else
      *number1 = _dt_collection_compute_datetime(*operator, txt);

    g_free(txt);
  }

  // ensure operator is not null
  if(!*operator) *operator= g_strdup("");

  g_match_info_free(match_info);
  g_regex_unref(regex);
}
Example #2
0
static gboolean
cmp_matches(const fvalue_t *fv_a, const fvalue_t *fv_b)
{
	char *str = fv_a->value.string;
	GRegex *regex = fv_b->value.re;

	/* fv_b is always a FT_PCRE, otherwise the dfilter semcheck() would have
	 * warned us. For the same reason (and because we're using g_malloc()),
	 * fv_b->value.re is not NULL.
	 */
	if (strcmp(fv_b->ftype->name, "FT_PCRE") != 0) {
		return FALSE;
	}
	if (! regex) {
		return FALSE;
	}
	return g_regex_match_full(
			regex,		/* Compiled PCRE */
			str,		/* The data to check for the pattern... */
			(int)strlen(str),	/* ... and its length */
			0,		/* Start offset within data */
			(GRegexMatchFlags)0,		/* GRegexMatchFlags */
			NULL,		/* We are not interested in the match information */
			NULL		/* We don't want error information */
			);
}
Example #3
0
 static int gsub_exec (TGrgx *ud, TArgExec *argE, int st, int retry) {
   int eflags = retry ? (argE->eflags|G_REGEX_MATCH_NOTEMPTY|G_REGEX_MATCH_ANCHORED) : argE->eflags;
   minfo_free (ud);
   gerror_free (ud);
   return g_regex_match_full (ud->pr, argE->text, argE->textlen,
     st, (GRegexMatchFlags)eflags, &ud->match_info, &ud->error);
 }
Example #4
0
static mc_search__found_cond_t
mc_search__regex_found_cond_one (mc_search_t * mc_search, mc_search_regex_t * regex,
                                 GString * search_str)
{
#ifdef SEARCH_TYPE_GLIB
    GError *error = NULL;

    if (!g_regex_match_full
        (regex, search_str->str, -1, 0, G_REGEX_MATCH_NEWLINE_ANY, &mc_search->regex_match_info,
         &error)) {
        g_match_info_free (mc_search->regex_match_info);
        mc_search->regex_match_info = NULL;
        if (error) {
            mc_search->error = MC_SEARCH_E_REGEX;
            mc_search->error_str = str_conv_gerror_message (error, _(" Regular expression error "));
            g_error_free (error);
            return COND__FOUND_ERROR;
        }
        return COND__NOT_FOUND;
    }
    mc_search->num_rezults = g_match_info_get_match_count (mc_search->regex_match_info);
#else /* SEARCH_TYPE_GLIB */
    mc_search->num_rezults = pcre_exec (regex, mc_search->regex_match_info,
                                        search_str->str, search_str->len - 1, 0, 0, mc_search->iovector,
                                        MC_SEARCH__NUM_REPLACE_ARGS);
    if (mc_search->num_rezults < 0) {
        return COND__NOT_FOUND;
    }
#endif /* SEARCH_TYPE_GLIB */
    return COND__FOUND_OK;

}
Example #5
0
Ref<String>
regexMatch (Regex *regex,
	    ConstMemoryDesc const &mdesc,
	    int match_num)
{
    GMatchInfo *match_info = NULL;

    gboolean match = g_regex_match_full ((GRegex*) regex->regex,
					 (const gchar*) mdesc.getMemory (),
					 // FIXME Overflow check
					 (gssize) mdesc.getLength (),
					 0, // start_position
					 (GRegexMatchFlags) 0,
					 &match_info,
					 NULL);
    if (!match)
	return grab (new String);

    gchar *ret_str = g_match_info_fetch (match_info, match_num);
    abortIf (ret_str == NULL);

    g_match_info_free (match_info);

    return grab (static_cast <String*> (new String_ExtAlloc (ret_str,
							     countStrLength (ret_str),
							     regex_free_callback)));
}
Example #6
0
/* splits an input string into a number part and an optional operator part.
   number can be a decimal integer or rational numerical item.
   operator can be any of "=", "<", ">", "<=", ">=" and "<>".

   number and operator are returned as pointers to null terminated strings in g_mallocated
   memory (to be g_free'd after use) - or NULL if no match is found.
*/
void
dt_collection_split_operator_number (const gchar *input, char **number, char **operator)
{
  GRegex *regex;
  GMatchInfo *match_info;
  int match_count;

  *number = *operator = NULL;
   
  regex = g_regex_new("\\s*(=|<|>|<=|>=|<>)?\\s*([0-9]+\\.?[0-9]*)\\s*", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    *operator = g_match_info_fetch(match_info, 1);
    *number = g_match_info_fetch(match_info, 2);

    if(*operator && strcmp(*operator, "") == 0)
    {
      g_free(*operator);
      *operator = NULL;
    }
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);
} 
Example #7
0
/// Writes to espeak's stdin.
static gpointer
worker_writer (WorkerData *data)
{
	GError *error = NULL;
	GMatchInfo *match_info;
	while (stardict_iterator_get_offset (data->iterator) != data->end_entry)
	{
		g_mutex_lock (data->dict_mutex);
		const gchar *word = stardict_iterator_get_word (data->iterator);
		g_mutex_unlock (data->dict_mutex);

		word += strspn (word, LINE_SPLITTING_CHARS " \t");
		gchar *x = g_strdup (word);

		// Cut the word if needed be
		error = NULL;
		if (g_regex_match_full (data->re_stop,
			x, -1, 0, 0, &match_info, &error))
		{
			gint start_pos;
			g_match_info_fetch_pos (match_info, 0, &start_pos, NULL);
			x[start_pos] = 0;
		}
		g_match_info_free (match_info);

		// Change acronyms so that they're not pronounced as words
		if (!error && !data->ignore_acronyms)
		{
			char *tmp = g_regex_replace_eval (data->re_acronym,
				x, -1, 0, 0, writer_acronym_cb, NULL, &error);
			g_free (x);
			x = tmp;
		}

		if (error)
		{
			g_printerr ("Notice: error processing '%s': %s\n",
				word, error->message);
			g_clear_error (&error);
			*x = 0;
		}

		// We might have accidentally cut off everything
		if (!*x)
		{
			g_free (x);
			x = g_strdup (VOID_ENTRY);
		}

		stardict_iterator_next (data->iterator);
		if (fprintf (data->child_stdin, "%s\n", x) < 0)
			g_error ("write to eSpeak failed: %s", strerror (errno));

		g_free (x);
	}

	g_object_unref (data->iterator);
	return GINT_TO_POINTER (fclose (data->child_stdin));
}
Example #8
0
/* splits an input string into a number part and an optional operator part.
   number can be a decimal integer or rational numerical item.
   operator can be any of "=", "<", ">", "<=", ">=" and "<>".
   range notation [x;y] can also be used

   number and operator are returned as pointers to null terminated strings in g_mallocated
   memory (to be g_free'd after use) - or NULL if no match is found.
*/
void dt_collection_split_operator_number(const gchar *input, char **number1, char **number2, char **operator)
{
  GRegex *regex;
  GMatchInfo *match_info;
  int match_count;

  *number1 = *number2 = *operator= NULL;

  // we test the range expression first
  regex = g_regex_new("^\\s*\\[\\s*([0-9]+\\.?[0-9]*)\\s*;\\s*([0-9]+\\.?[0-9]*)\\s*\\]\\s*$", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    *number1 = g_match_info_fetch(match_info, 1);
    *number2 = g_match_info_fetch(match_info, 2);
    *operator= g_strdup("[]");
    g_match_info_free(match_info);
    g_regex_unref(regex);
    return;
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);

  // and we test the classic comparaison operators
  regex = g_regex_new("^\\s*(=|<|>|<=|>=|<>)?\\s*([0-9]+\\.?[0-9]*)\\s*$", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    *operator= g_match_info_fetch(match_info, 1);
    *number1 = g_match_info_fetch(match_info, 2);

    if(*operator&& strcmp(*operator, "") == 0)
    {
      g_free(*operator);
      *operator= NULL;
    }
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);
}
Example #9
0
static gboolean
validate_address (const gchar *key,
                  const gchar *value,
                  gboolean suffix,
                  GError **error)
{
  if (suffix && g_strrstr (value, "/"))
    {
      gs_strfreev gchar **tokens = NULL;
      gs_unref_object GInetAddress *address = NULL;

      tokens = g_strsplit (value, "/", 2);
      address = g_inet_address_new_from_string (tokens[0]);

      if (address == NULL)
        {
          *error = g_error_new (G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                           _("'%s' entry must contain a valid IPv4 address"),
                                key);
          return FALSE;
        }

      GRegex *regex = g_regex_new ("^[0-9]{1,2}$", 0, 0, NULL);
      if (!g_regex_match_full (regex, tokens[1], -1, 0, 0, NULL, NULL))
        {
          g_regex_unref (regex);
          *error = g_error_new (G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                            _("'%s' entry must contain a valid IPv4 suffix"),
                                key);
          return FALSE;
        }
      g_regex_unref (regex);

      if (g_ascii_strtoull (tokens[1], NULL, 0) > 32)
        {
          *error = g_error_new (G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                            _("'%s' entry must contain a valid IPv4 suffix"),
                                key);
          return FALSE;
        }
    }
  else
    {
      gs_unref_object GInetAddress *address = NULL;

      address = g_inet_address_new_from_string (value);

      if (address == NULL)
        {
          *error = g_error_new (G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                                _("'%s' entry must be a valid IPv4 address"),
                                key);
          return FALSE;
        }
    }

  return TRUE;
}
Example #10
0
static VALUE
rg_match(gint argc, VALUE *argv, VALUE self)
{
    VALUE rb_string, rb_start_position, rb_match_options, rb_options;
    VALUE rb_frozen_string, rb_match_info;
    GMatchInfo *match_info = NULL;
    GError *error = NULL;
    const gchar *string;
    gssize string_len = -1;
    gint start_position = 0;
    GRegexMatchFlags match_options = 0;

    rb_scan_args(argc, argv, "11", &rb_string, &rb_options);

    rbg_scan_options(rb_options,
                     "start_position", &rb_start_position,
                     "match_options", &rb_match_options,
                     NULL);

    if (OBJ_FROZEN(rb_string)) {
        rb_frozen_string = rb_string;
    } else {
        rb_frozen_string = rb_str_dup(rb_string);
        rb_str_freeze(rb_frozen_string);
    }

    string = RVAL2CSTR(rb_frozen_string);
    string_len = RSTRING_LEN(rb_frozen_string);


    if (!NIL_P(rb_start_position))
        start_position = NUM2INT(rb_start_position);
    if (!NIL_P(rb_match_options))
        match_options = RVAL2GREGEXMATCHOPTIONSFLAGS(rb_match_options);

    g_regex_match_full(_SELF(self),
                       string,
                       string_len,
                       start_position,
                       match_options,
                       &match_info,
                       &error);

    if (error)
        RAISE_GERROR(error);

    if (!match_info)
        return Qnil;

    rb_match_info = GMATCHINFO2RVAL(match_info);
    g_match_info_unref(match_info);
    rb_iv_set(rb_match_info, "@string", rb_frozen_string);
    return rb_match_info;
}
Example #11
0
static inline void scr_log_urls(const gchar *string)
{
  GMatchInfo *match_info;

  g_regex_match_full(url_regex, string, -1, 0, 0, &match_info, NULL);
  while (g_match_info_matches(match_info)) {
    gchar *url = g_match_info_fetch(match_info, 0);
    scr_print_logwindow(url);
    g_free(url);
    g_match_info_next(match_info, NULL);
  }
  g_match_info_free(match_info);
}
void
tpaw_string_match_link (const gchar *text,
    gssize len,
    TpawStringReplace replace_func,
    TpawStringParser *sub_parsers,
    gpointer user_data)
{
  GRegex *uri_regex;
  GMatchInfo *match_info;
  gboolean match;
  gint last = 0;

  uri_regex = uri_regex_dup_singleton ();
  if (uri_regex == NULL)
    {
      tpaw_string_parser_substr (text, len, sub_parsers, user_data);
      return;
    }

  match = g_regex_match_full (uri_regex, text, len, 0, 0, &match_info, NULL);
  if (match)
    {
      gint s = 0, e = 0;

      do
        {
          g_match_info_fetch_pos (match_info, 0, &s, &e);

          if (s > last)
            {
              /* Append the text between last link (or the
               * start of the message) and this link */
              tpaw_string_parser_substr (text + last,
                  s - last,
                  sub_parsers,
                  user_data);
            }

          replace_func (text + s, e - s, NULL, user_data);

          last = e;
        } while (g_match_info_next (match_info, NULL));
    }

  tpaw_string_parser_substr (text + last, len - last, sub_parsers, user_data);

  g_match_info_free (match_info);
  g_regex_unref (uri_regex);
}
static gchar *
parse_time (const gchar *response,
            const gchar *regex,
            const gchar *tag,
            GError **error)
{
    GRegex *r;
    GMatchInfo *match_info = NULL;
    GError *match_error = NULL;
    guint year, month, day, hour, minute, second;
    gchar *result = NULL;

    r = g_regex_new (regex, 0, 0, NULL);
    g_assert (r != NULL);

    if (!g_regex_match_full (r, response, -1, 0, 0, &match_info, &match_error)) {
        if (match_error) {
            g_propagate_error (error, match_error);
            g_prefix_error (error, "Could not parse %s results: ", tag);
        } else {
            g_set_error (error,
                         MM_CORE_ERROR,
                         MM_CORE_ERROR_FAILED,
                         "Couldn't match %s reply", tag);
        }
    } else {
        if (mm_get_uint_from_match_info (match_info, 1, &year) &&
            mm_get_uint_from_match_info (match_info, 2, &month) &&
            mm_get_uint_from_match_info (match_info, 3, &day) &&
            mm_get_uint_from_match_info (match_info, 4, &hour) &&
            mm_get_uint_from_match_info (match_info, 5, &minute) &&
            mm_get_uint_from_match_info (match_info, 6, &second)) {
            /* Return ISO-8601 format date/time string */
            result = g_strdup_printf ("%04d/%02d/%02d %02d:%02d:%02d",
                                      year, month, day, hour, minute, second);
        } else {
            g_set_error (error,
                         MM_CORE_ERROR,
                         MM_CORE_ERROR_FAILED,
                         "Failed to parse %s reply", tag);
        }
    }

    if (match_info)
        g_match_info_free (match_info);
    g_regex_unref (r);
    return result;
}
Example #14
0
GSList*
parse_acl(const GByteArray* acl_byte, gboolean authorize)
{
	/* sanity check */
	GError* error = NULL;

	if(!acl_byte || !acl_byte->data || acl_byte->len == 0)	{
		return NULL;
	}
		
	GSList* result = NULL;
	gchar** access_rules = NULL;
	
	access_rules = g_strsplit(((char*)acl_byte->data), ";", 0);
	
	GRegex *range_regex = NULL;
	range_regex = g_regex_new("([0-9]{1,3}.){3}[0-9]{1,3}/[0-9]{1,2}", 0, 0, &error);

	for(int i = 0; i < ((int)g_strv_length(access_rules)); i++) {
		addr_rule_t* rule = NULL;
		rule = g_malloc0(sizeof(addr_rule_t));
		if((access_rules[i] == NULL) || (strlen(access_rules[i])<=1))
			continue;

		/* regex matching [X.X.X.X/X] */
		gchar** tmp_array = NULL;
		if(g_regex_match_full(range_regex, access_rules[i], strlen(access_rules[i]), 0, 0, NULL, &error)) {
			gchar* tmp = NULL;
			tmp = _range2netmask(access_rules[i]);
			tmp_array = g_strsplit(tmp, " ", 2);
			rule->network_addr = g_strdup(tmp_array[0]);
			rule->network_mask = g_strdup(tmp_array[1]);
			g_free(tmp);
		} else {
			tmp_array = g_strsplit(access_rules[i], " ", 2);
			rule->network_addr = g_strdup(tmp_array[0]);
			rule->network_mask = g_strdup(tmp_array[1]);
		}
		rule->authorize = authorize;
		result = g_slist_prepend(result, rule);
		g_strfreev(tmp_array);
	}
	g_regex_unref(range_regex);

	g_strfreev(access_rules);

	return g_slist_reverse(result);
}
Example #15
0
static void
parse_unsolicited (MMPortSerial *port, GByteArray *response)
{
    MMPortSerialAt *self = MM_PORT_SERIAL_AT (port);
    GSList *iter;

    /* Remove echo */
    if (self->priv->remove_echo)
        mm_port_serial_at_remove_echo (response);

    for (iter = self->priv->unsolicited_msg_handlers; iter; iter = iter->next) {
        MMAtUnsolicitedMsgHandler *handler = (MMAtUnsolicitedMsgHandler *) iter->data;
        GMatchInfo *match_info;
        gboolean matches;

        if (!handler->enable)
            continue;

        matches = g_regex_match_full (handler->regex,
                                      (const char *) response->data,
                                      response->len,
                                      0, 0, &match_info, NULL);
        if (handler->callback) {
            while (g_match_info_matches (match_info)) {
                handler->callback (self, match_info, handler->user_data);
                g_match_info_next (match_info, NULL);
            }
        }

        g_match_info_free (match_info);

        if (matches) {
            /* Remove matches */
            char *str;
            int result_len = response->len;

            str = g_regex_replace_eval (handler->regex,
                                        (const char *) response->data,
                                        response->len,
                                        0, 0,
                                        remove_eval_cb, &result_len, NULL);

            g_byte_array_remove_range (response, 0, response->len);
            g_byte_array_append (response, (const guint8 *) str, result_len);
            g_free (str);
        }
    }
}
static void
parse_unsolicited (MMSerialPort *port, GByteArray *response)
{
    MMAtSerialPort *self = MM_AT_SERIAL_PORT (port);
    MMAtSerialPortPrivate *priv = MM_AT_SERIAL_PORT_GET_PRIVATE (self);
    GSList *iter;

    for (iter = priv->unsolicited_msg_handlers; iter; iter = iter->next) {
        MMAtUnsolicitedMsgHandler *handler = (MMAtUnsolicitedMsgHandler *) iter->data;
        GMatchInfo *match_info;
        gboolean matches;

        matches = g_regex_match_full (handler->regex,
                                      (const char *) response->data,
                                      response->len,
                                      0, 0, &match_info, NULL);
        if (handler->callback) {
            while (g_match_info_matches (match_info)) {
                handler->callback (self, match_info, handler->user_data);
                g_match_info_next (match_info, NULL);
            }
        }

        g_match_info_free (match_info);

        if (matches) {
            /* Remove matches */
            char *str;
            int result_len = response->len;

            str = g_regex_replace_eval (handler->regex,
                                        (const char *) response->data,
                                        response->len,
                                        0, 0,
                                        remove_eval_cb, &result_len, NULL);

            g_byte_array_remove_range (response, 0, response->len);
            g_byte_array_append (response, (const guint8 *) str, result_len);
            g_free (str);
        }
    }
}
Example #17
0
static gboolean
validate_domainname (const gchar *key,
                     const gchar *value,
                     GError **error)
{
  GRegex *regex;
  regex = g_regex_new ("^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,13}$",
                       0, 0, NULL);
  if (!g_regex_match_full (regex, value, -1, 0, 0, NULL, NULL))
    {
      g_regex_unref (regex);
      *error = g_error_new (G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                            _("'%s' entry must contain a valid domain name"),
                            key);
      return FALSE;
    }
  g_regex_unref (regex);

  return TRUE;
}
Example #18
0
int regex_match_count(char *buff, int buff_size, const gchar * regex_string, GRegexCompileFlags compile_flags)
{
  int matches = 0;

  //create regex
  GError *regex_error = NULL;
  GMatchInfo *match_info = NULL;
  GRegex *regex = g_regex_new(regex_string, compile_flags, (GRegexMatchFlags) 0, &regex_error);

  if (regex_error != NULL)
  {
    debug_log("regex error code was: %s", regex_error->message);
    g_error_free(regex_error);
  } else
  {
    g_regex_match_full(regex, buff, buff_size, 0, (GRegexMatchFlags) 0, &match_info, &regex_error);
    if (regex_error != NULL)
    {
      debug_log("regex error code was: %s", regex_error->message);
      g_error_free(regex_error);
    }
    while (g_match_info_matches(match_info))
    {
      gchar *word = g_match_info_fetch(match_info, 0);

      //debug_log("Regex matched: : %s", word);
      g_free(word);
      g_match_info_next(match_info, NULL);
      matches++;
    }
    //free match info
    g_match_info_free(match_info);
  }

  //free regex
  g_regex_unref(regex);

  return matches;
}
Example #19
0
gboolean
_gtk_source_regex_match (GtkSourceRegex *regex,
			 const gchar    *line,
			 gint             byte_length,
			 gint             byte_pos)
{
	gboolean result;

	g_assert (regex->resolved);

	if (regex->u.regex.match)
	{
		g_match_info_free (regex->u.regex.match);
		regex->u.regex.match = NULL;
	}

	result = g_regex_match_full (regex->u.regex.regex, line,
				     byte_length, byte_pos,
				     0, &regex->u.regex.match,
				     NULL);

	return result;
}
static void
nwrat_query_ready (MMBaseModem *self,
                   GAsyncResult *res,
                   GSimpleAsyncResult *simple)
{
    LoadCurrentModesResult result;
    GError *error = NULL;
    const gchar *response;
    GRegex *r;
    GMatchInfo *match_info = NULL;
    gint a = -1;
    gint b = -1;

    response = mm_base_modem_at_command_finish (MM_BASE_MODEM (self), res, &error);
    if (!response) {
        g_simple_async_result_take_error (simple, error);
        g_simple_async_result_complete (simple);
        g_object_unref (simple);
        return;
    }

    /* Parse response */
    r = g_regex_new ("\\$NWRAT:\\s*(\\d),(\\d),(\\d)", G_REGEX_UNGREEDY, 0, NULL);
    g_assert (r != NULL);

    if (!g_regex_match_full (r, response, strlen (response), 0, 0, &match_info, &error)) {
        if (error)
            g_simple_async_result_take_error (simple, error);
        else
            g_simple_async_result_set_error (simple,
                                             MM_CORE_ERROR,
                                             MM_CORE_ERROR_FAILED,
                                             "Couldn't match NWRAT reply: %s",
                                             response);
        g_simple_async_result_complete (simple);
        g_object_unref (simple);
        g_match_info_free (match_info);
        g_regex_unref (r);
        return;
    }

    if (!mm_get_int_from_match_info (match_info, 1, &a) ||
        !mm_get_int_from_match_info (match_info, 2, &b) ||
        a < 0 || a > 2 ||
        b < 1 || b > 2) {
        g_simple_async_result_set_error (
            simple,
            MM_CORE_ERROR,
            MM_CORE_ERROR_FAILED,
            "Failed to parse mode/tech response '%s': invalid modes reported",
            response);
        g_match_info_free (match_info);
        g_regex_unref (r);
        g_simple_async_result_complete (simple);
        g_object_unref (simple);
        return;
    }

    switch (a) {
    case 0:
        result.allowed = (MM_MODEM_MODE_2G | MM_MODEM_MODE_3G);
        result.preferred = MM_MODEM_MODE_NONE;
        break;
    case 1:
        if (b == 1) {
            result.allowed = MM_MODEM_MODE_2G;
            result.preferred = MM_MODEM_MODE_NONE;
        } else /* b == 2 */ {
            result.allowed = (MM_MODEM_MODE_2G | MM_MODEM_MODE_3G);
            result.preferred = MM_MODEM_MODE_2G;
        }
        break;
    case 2:
        if (b == 1) {
            result.allowed = MM_MODEM_MODE_3G;
            result.preferred = MM_MODEM_MODE_NONE;
        } else /* b == 2 */ {
            result.allowed = (MM_MODEM_MODE_2G | MM_MODEM_MODE_3G);
            result.preferred = MM_MODEM_MODE_3G;
        }
        break;
    default:
        /* We only allow mode 0|1|2 */
        g_assert_not_reached ();
        break;
    }

    g_match_info_free (match_info);
    g_regex_unref (r);

    /* When a valid result is given, we never complete in idle */
    g_simple_async_result_set_op_res_gpointer (simple, &result, NULL);
    g_simple_async_result_complete (simple);
    g_object_unref (simple);
}
static gboolean
parse_nwltime_reply (const char *response,
                     gchar **out_iso_8601,
                     MMNetworkTimezone **out_tz,
                     GError **error)
{
    GRegex *r;
    GMatchInfo *match_info = NULL;
    GError *match_error = NULL;
    guint year, month, day, hour, minute, second;
    gchar *result = NULL;
    gint utc_offset = 0;
    gboolean success = FALSE;

    /* Sample reply: 2013.3.27.15.47.19.2.-5 */
    r = g_regex_new ("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\.([\\-\\+\\d]+)$", 0, 0, NULL);
    g_assert (r != NULL);

    if (!g_regex_match_full (r, response, -1, 0, 0, &match_info, &match_error)) {
        if (match_error) {
            g_propagate_error (error, match_error);
            g_prefix_error (error, "Could not parse $NWLTIME results: ");
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Couldn't match $NWLTIME reply");
        }
    } else {
        /* Remember that g_match_info_get_match_count() includes match #0 */
        g_assert (g_match_info_get_match_count (match_info) >= 9);

        if (mm_get_uint_from_match_info (match_info, 1, &year) &&
            mm_get_uint_from_match_info (match_info, 2, &month) &&
            mm_get_uint_from_match_info (match_info, 3, &day) &&
            mm_get_uint_from_match_info (match_info, 4, &hour) &&
            mm_get_uint_from_match_info (match_info, 5, &minute) &&
            mm_get_uint_from_match_info (match_info, 6, &second) &&
            mm_get_int_from_match_info (match_info, 8, &utc_offset)) {

            result = mm_new_iso8601_time (year, month, day, hour, minute, second,
                                          TRUE, utc_offset * 60);
            if (out_tz) {
                *out_tz = mm_network_timezone_new ();
                mm_network_timezone_set_offset (*out_tz, utc_offset * 60);
            }

            success = TRUE;
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Failed to parse $NWLTIME reply");
        }
    }

    if (out_iso_8601)
        *out_iso_8601 = result;
    else
        g_free (result);

    if (match_info)
        g_match_info_free (match_info);
    g_regex_unref (r);
    return success;
}
Example #22
0
static void wp_query_callback(const GEADAsyncHandler *handle, GEADStatus status, gpointer ignored)
{
	xmlDocPtr doc;
	goffset size;
	xmlNodePtr root, sect, desc, url, c1, query;
	const gchar *data;
	gchar *targeturl, *txt;



    g_log(wikipedia_logdomain, G_LOG_LEVEL_DEBUG, "query returned %i\n",status);
	if(status != GEAD_DONE)
		return;
    g_log(wikipedia_logdomain, G_LOG_LEVEL_DEBUG, "query returned done\n");
    data = gmpc_easy_handler_get_data(handle, &size);

	doc = xmlParseMemory(data, size);
	if(!doc)
		return;
	root = xmlDocGetRootElement(doc);
	if(!root)
		return;
	sect = get_first_node_by_name(root,"Section");
	if (!sect)
		goto out_doc;

	for(c1 = sect->xmlChildrenNode; c1; c1 = c1->next)
	{
		desc = get_first_node_by_name(c1, "Text");
		url = get_first_node_by_name(c1, "Url");
		if (!desc || !url)
			continue;
		txt = xmlNodeListGetString(doc, desc->xmlChildrenNode, 1);
		if (!txt)
			continue;
		if (g_regex_match_full(page_guess_re, txt, strlen(txt), 0, 0, NULL, NULL) &&
				xmlNodeListGetString(doc, url->xmlChildrenNode, 1))
		{
			wp_set_url(xmlNodeListGetString(doc, url->xmlChildrenNode, 1));
			break;
		}

	}
	/* nothing was found by regex, use first entry */
	if (!c1) {
		c1 = sect->xmlChildrenNode;
		if (c1) {
			url = get_first_node_by_name(c1, "Url");
			if (url && xmlNodeListGetString(doc, url->xmlChildrenNode, 1))
				wp_set_url(xmlNodeListGetString(doc,url->xmlChildrenNode,1));
		} else {
			/* nothing is found, if we are localized, grab our search string back and do some magic */
			query = get_first_node_by_name(root, "Query");
			if (!query)
				goto out_doc;
			txt = xmlNodeListGetString(doc, query->xmlChildrenNode, 1);
			if (!txt)
				goto out_doc;

			/* fist try english wikipedia, it's the biggest after all */
			const gchar *oldurl = gmpc_easy_handler_get_uri(handle);
			if (!g_str_has_prefix(oldurl, "http://en.")) {
				gchar *newurl = g_strdup_printf("http://en.wikipedia.org/w/api.php?action=opensearch&search=%s&format=xml", txt);
				g_log(wikipedia_logdomain, G_LOG_LEVEL_DEBUG, "Trying to fetch: %s\n", newurl);
				gmpc_easy_async_downloader(newurl, wp_query_callback, NULL);
				g_free(newurl);
				goto out_doc;
			}
			/* nothing is found, display localized wikipedia
			 * "unknown article" page. Not loading anything is
			 * confusing */
			targeturl = g_strdup_printf("http://%s.wikipedia.org/wiki/%s", locale, txt);
			wp_set_url(targeturl);
			g_free(targeturl);
		}
	}
out_doc:
	xmlFreeDoc(doc);
}
static gboolean
load_allowed_modes_finish (MMIfaceModem *self,
                           GAsyncResult *res,
                           MMModemMode *allowed,
                           MMModemMode *preferred,
                           GError **error)
{
    const gchar *response;
    GMatchInfo *match_info = NULL;
    GRegex *r;
    gint cm_mode = -1;
    gint pref_acq = -1;
    gboolean result;

    response = mm_base_modem_at_command_finish (MM_BASE_MODEM (self), res, error);
    if (!response)
        return FALSE;

    r = g_regex_new ("\\+ZSNT:\\s*(\\d),(\\d),(\\d)", G_REGEX_UNGREEDY, 0, error);
    g_assert (r != NULL);

    result = FALSE;
    if (!g_regex_match_full (r, response, strlen (response), 0, 0, &match_info, error))
        goto done;

    if (!mm_get_int_from_match_info (match_info, 1, &cm_mode) ||
        cm_mode < 0 || (cm_mode > 2 && cm_mode != 6) ||
        !mm_get_int_from_match_info (match_info, 3, &pref_acq) ||
        pref_acq < 0 || pref_acq > 2) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_FAILED,
                     "Failed to parse the allowed mode response: '%s'",
                     response);
        goto done;
    }

    /* Correctly parsed! */
    result = TRUE;
    if (cm_mode == 0) {
        /* Both 2G, 3G and LTE allowed. For LTE modems, no 2G/3G preference supported. */
        if (pref_acq == 0 || mm_iface_modem_is_3gpp_lte (self)) {
            /* Any allowed */
            *allowed = MM_MODEM_MODE_ANY;
            *preferred = MM_MODEM_MODE_NONE;
        } else if (pref_acq == 1) {
            *allowed = (MM_MODEM_MODE_2G | MM_MODEM_MODE_3G);
            *preferred = MM_MODEM_MODE_2G;
        } else if (pref_acq == 2) {
            *allowed = (MM_MODEM_MODE_2G | MM_MODEM_MODE_3G);
            *preferred = MM_MODEM_MODE_3G;
        } else
            g_assert_not_reached ();
    } else if (cm_mode == 1) {
        /* GSM only */
        *allowed = MM_MODEM_MODE_2G;
        *preferred = MM_MODEM_MODE_NONE;
    } else if (cm_mode == 2) {
        /* WCDMA only */
        *allowed = MM_MODEM_MODE_3G;
        *preferred = MM_MODEM_MODE_NONE;
    } else if (cm_mode == 6) {
        /* LTE only */
        *allowed = MM_MODEM_MODE_4G;
        *preferred = MM_MODEM_MODE_NONE;
    } else
        g_assert_not_reached ();

done:
    if (match_info)
        g_match_info_free (match_info);
    if (r)
        g_regex_unref (r);

    return result;
}
gchar *build_remote_exec_cmd(TrgClient * tc, GtkTreeModel * model,
                             GList * selection, const gchar * input)
{
    TrgPrefs *prefs = trg_client_get_prefs(tc);
    JsonObject *session = trg_client_get_session(tc);
    JsonObject *profile = trg_prefs_get_connection(prefs);
    gchar *work;
    GRegex *regex, *replacerx;
    GMatchInfo *match_info;
    gchar *whole, *wholeEscaped, *id, *tmp, *valuestr, *repeater;
    JsonNode *replacement;

    if (!profile)
        return NULL;

    work = g_strdup(input);
    regex = g_regex_new("%{([A-Za-z\\-]+)}(?:\\[(.*)\\])?", 0, 0, NULL);

    g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);

    if (match_info) {
        while (g_match_info_matches(match_info)) {
            whole = g_match_info_fetch(match_info, 0);
            wholeEscaped = g_regex_escape_string(whole, -1);
            id = g_match_info_fetch(match_info, 1);
            repeater = g_match_info_fetch(match_info, 2);

            replacerx = g_regex_new(wholeEscaped, 0, 0, NULL);
            valuestr = NULL;

            if (profile && json_object_has_member(profile, id)) {
                replacement = json_object_get_member(profile, id);
                if (JSON_NODE_HOLDS_VALUE(replacement))
                    valuestr = dump_json_value(replacement);
            } else if (session && json_object_has_member(session, id)) {
                replacement = json_object_get_member(session, id);
                if (JSON_NODE_HOLDS_VALUE(replacement))
                    valuestr = dump_json_value(replacement);
            } else {
                GString *gs = g_string_new("");
                GList *li;
                GtkTreeIter iter;
                JsonObject *json;
                gchar *piece;

                for (li = selection; li; li = g_list_next(li)) {
                    piece = NULL;
                    gtk_tree_model_get_iter(model, &iter,
                                            (GtkTreePath *) li->data);
                    gtk_tree_model_get(model, &iter, TORRENT_COLUMN_JSON,
                                       &json, -1);
                    if (json_object_has_member(json, id)) {
                        replacement = json_object_get_member(json, id);
                        if (JSON_NODE_HOLDS_VALUE(replacement)) {
                            piece = dump_json_value(replacement);
                        }
                    }

                    if (!piece) {
                        if (!g_strcmp0(id, "full-dir")) {
                            piece = torrent_get_full_dir(json);
                        } else if (!g_strcmp0(id, "full-path")) {
                            piece = torrent_get_full_path(json);
                        }
                    }

                    if (piece) {
                        g_string_append(gs, piece);
                        g_free(piece);
                    }

                    if (!repeater)
                        break;

                    if (piece && li != g_list_last(selection))
                        g_string_append(gs, repeater);
                }

                if (gs->len > 0)
                    valuestr = g_string_free(gs, FALSE);
                else
                    g_string_free(gs, TRUE);
            }

            if (valuestr) {
                tmp = g_regex_replace(replacerx, work, -1, 0, valuestr, 0,
                                      NULL);
                g_free(work);
                work = tmp;
                g_free(valuestr);
            }

            g_regex_unref(replacerx);
            g_free(whole);
            g_free(repeater);
            g_free(wholeEscaped);
            g_free(id);
            g_match_info_next(match_info, NULL);
        }

        g_match_info_free(match_info);
    }

    g_regex_unref(regex);
    return work;
}
Example #25
0
static int split_exec (TGrgx *ud, TArgExec *argE, int offset) {
  minfo_free (ud);
  gerror_free (ud);
  return g_regex_match_full (ud->pr, argE->text, argE->textlen, offset,
                    (GRegexMatchFlags)argE->eflags, &ud->match_info, &ud->error);
}
Example #26
0
 static int gmatch_exec (TUserdata *ud, TArgExec *argE) {
   minfo_free (ud);
   gerror_free (ud);
   return g_regex_match_full (ud->pr, argE->text, argE->textlen,
     argE->startoffset, (GRegexMatchFlags)argE->eflags, &ud->match_info, &ud->error);
 }
Example #27
0
File: givimage.c Project: dov/giv
GivImage *giv_image_new_from_file(const char *filename,
                                  GError **error)
{
    GivImage *img = NULL;
    // TBD - run through a list of loaders. Right now just
    // use gdkpixbuf.
    gchar *extension = g_strrstr(filename, ".");
    if (extension)
        extension++;

    if ((img = giv_plugin_load_image(filename,
                                     error)) != NULL) {
        return img;
    }
    if (*error) {
        printf("Got error: %s\n", (*error)->message);
        return NULL;
    }
    else if (!extension) {
    }
    else if (g_regex_match_simple("png"
                                  "|jpe?g"
                                  "|p[bgp]m"
                                  "|bmp"
                                  "|svg"
                                  ,
                                  extension,
                                  G_REGEX_CASELESS,
                                  0)) {
        GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(filename,
                                                     error);
        
        if (*error)
            return img;

        gboolean is_mono = TRUE;

        // Check if the file is monochrome.
        int row_idx,col_idx;
        int width = gdk_pixbuf_get_width(pixbuf);
        int height = gdk_pixbuf_get_height(pixbuf);
        guint8 *buf = gdk_pixbuf_get_pixels(pixbuf);
        int row_stride = gdk_pixbuf_get_rowstride(pixbuf);

        for (row_idx=0; row_idx<height; row_idx++) {
            guint8 *p = buf + row_idx * row_stride;
            for (col_idx=0; col_idx<width; col_idx++) {
                if (p[0] != p[1]
                    || p[0] != p[2]) {
                    is_mono = FALSE;
                    break;
                }
                p+= 3;
            }
        }

        if (is_mono) {
            GivImageType img_type = GIVIMAGE_U8;
            img = giv_image_new_full(img_type,
                                     width,
                                     width,
                                     height,
                                     width * height,
                                     2,
                                     1);
            if (!img) {
                *error = g_error_new(GIV_IMAGE_ERROR, -1, "Failed allocating memory for an image of size %dx%d pixels!", width, height);
                return NULL;
            }

            guchar *src_buf = gdk_pixbuf_get_pixels(pixbuf);
            guchar *dst_buf = img->buf.buf;
            int row_idx, col_idx;
            int ncolors = 3;
            if (gdk_pixbuf_get_has_alpha(pixbuf))
                ncolors = 4;
            for (row_idx=0; row_idx<height; row_idx++) {
                guchar *dst_row = dst_buf + row_idx*width;
                guchar *src_row = src_buf + row_idx*row_stride;
                for (col_idx=0; col_idx<width; col_idx++) 
                    dst_row[col_idx] = src_row[col_idx*ncolors];
            }
        }
        else {
            GivImageType img_type = GIVIMAGE_RGB_U8;
            if (gdk_pixbuf_get_has_alpha(pixbuf)) 
                img_type = GIVIMAGE_RGBA_U8;
            img = giv_image_new_full(img_type,
                                     width,
                                     row_stride,
                                     height,
                                     row_stride * height,
                                     2,
                                     1);
            if (!img) {
                *error = g_error_new(GIV_IMAGE_ERROR, -1, "Failed allocating memory for an image of size %dx%d pixels!", width, height);
                return NULL;
            }
            memcpy(img->buf.buf,
                   gdk_pixbuf_get_pixels(pixbuf),
                   row_stride * height);
        }
        g_object_unref(pixbuf);
    }
    // Space separated value. A simple text format parser. Still
    // doesn't support comments. Fix this!
    else if (g_regex_match_simple("ssv",
                                  extension,
                                  G_REGEX_CASELESS,
                                  0)) {
        gchar *ssv_string;
        gsize length;
        
        g_file_get_contents(filename, &ssv_string, &length, error);
        gchar **lines = g_regex_split_simple("\r?\n",
                                             ssv_string,
                                             0, 0);
        int num_lines = g_strv_length(lines);

        // Count lines while skipping comments
        int height = 0;
        int line_idx;
        for (line_idx = 0; line_idx<num_lines; line_idx++) {
            if (lines[line_idx][0] == '#'
                || strlen(lines[line_idx]) == 0)
                continue;
            height++;
        }

        gint width = -1;
        float *fbuf;
        int row_idx = 0;
        for (line_idx=0; line_idx<num_lines; line_idx++) {
            int col_idx;
            if (lines[line_idx][0] == '#'
                || strlen(lines[line_idx]) == 0)
                continue;
            // comma or space split
            gchar *p = lines[line_idx];

            // skip whitespace
            while(*p == ' ')
                p++;
            gchar **fields = g_regex_split_simple("(?:,|;|\\s)\\s*",
                                                  p,
                                                  0,0);
            if (row_idx==0) {
                width = g_strv_length(fields);
                img = giv_image_new(GIVIMAGE_FLOAT,
                                    width, height);
                fbuf = img->buf.fbuf;
            }
            for (col_idx=0; col_idx<width; col_idx++) 
                fbuf[row_idx*width + col_idx] = atof(fields[col_idx]);
            g_strfreev(fields);
            row_idx++;

        }
        g_strfreev(lines);
        g_free(ssv_string);
    }
    else if (g_regex_match_simple("npy",
                                  extension,
                                  G_REGEX_CASELESS,
                                  0)) {
        gchar *npy_string;
        gsize length;
        
        g_file_get_contents(filename, &npy_string, &length, error);

        // Various checks that it is format we support
        gboolean header_ok = (g_strstr_len(npy_string, 6, "\223NUMPY") == npy_string );
        gboolean ver_ok = (npy_string[6] == 1
                           && npy_string[7] == 0);
        gint header_len = *((guint16*)(npy_string+8));

        // Use regex to parse the header. Should update this to allow
        // user attributes.
        GRegex *regex = g_regex_new ("^\\{\\s*"
                                     "'descr':\\s*\\'(.*?)\\'\\s*,\\s*"
                                     "'fortran_order':\\s*(\\w+)\\s*,\\s*"
                                     "'shape':\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\),?\\s*"
                                     "\\}", 0, 0, error);
        if (*error) {
            printf("Programming GivRegEx error: %s\n", (*error)->message);
            exit(-1);
        }
        GMatchInfo *match_info = NULL;
        gboolean is_match = g_regex_match_full(regex,
                                               npy_string+10,
                                               header_len,
                                               0,
                                               (GRegexMatchFlags)0,
                                               &match_info,
                                               error);
        gboolean is_supported_type = TRUE;
        gboolean is_fortran_type = FALSE;
        gint width=-1, height = -1;
        GivImageType image_type;
        if (is_match) {
            gchar *match_string = g_match_info_fetch(match_info, 1);

            if (strcmp(match_string, "<f8")==0) 
                image_type = GIVIMAGE_DOUBLE;
            else if (strcmp(match_string, "<f4")==0) 
                image_type = GIVIMAGE_FLOAT;
            else if (strcmp(match_string, "<i4")==0) 
                image_type = GIVIMAGE_I32;
            else if (strcmp(match_string, "<i2")==0) 
                image_type = GIVIMAGE_I16;
            else if (strcmp(match_string, "<u2")==0) 
                image_type = GIVIMAGE_U16;
            else if (strcmp(match_string, "|u1")==0) 
                image_type = GIVIMAGE_U8;
            else
                is_supported_type = FALSE;
            
            g_free(match_string);
            
            match_string = g_match_info_fetch(match_info, 2);
            is_fortran_type = strcmp(match_string, "True") == 0;
            g_free(match_string);
            
            match_string = g_match_info_fetch(match_info, 3);
            height = atoi(match_string);
            g_free(match_string);
            
            match_string = g_match_info_fetch(match_info, 4);
            width = atoi(match_string);
            g_free(match_string);
        }

        g_regex_unref(regex);
        g_match_info_free(match_info);
        
        if  (!is_match
             || !header_ok
             || !is_supported_type
             || is_fortran_type
            ) {
            *error = g_error_new(GIV_IMAGE_ERROR, -1, "Invalid npy file!");
            g_free(npy_string);
            return NULL;
        }

        img = giv_image_new(image_type,
                            width, height);

        // Copy the data
        //        printf("image: type size width height= %d %d\n", image_type, giv_image_type_get_size(image_type), width, height);

        memcpy(img->buf.buf,
               npy_string + 10 + header_len,
               giv_image_type_get_size(image_type) * width * height / 8);
        g_free(npy_string);
    }
    else {
        *error = g_error_new(GIV_IMAGE_ERROR, -1, "Giv: Unknown filetype %s!", extension);
    }

    if (!img && !*error)
        *error = g_error_new(GIV_IMAGE_ERROR, -1, "Giv: Failed loading %s!", filename);
    return img;
}
Example #28
0
static GSList*
_parse_acl_bytes(const GByteArray* acl_byte)
{
	/* sanity check */
	GError* error = NULL;

	if(!acl_byte || !acl_byte->data || acl_byte->len == 0)	{
		return NULL;
	}
		
	GSList* result = NULL;
	gchar** access_rules = NULL;
	
	access_rules = g_strsplit(((char*)acl_byte->data), "\n", 0);

	GRegex *range_regex = NULL;
	range_regex = g_regex_new("([0-9]{1,3}.){3}[0-9]{1,3}/[0-9]{1,2}", 0, 0, &error);

	int i, max;

	for(i=0,max=g_strv_length(access_rules); i<max; i++) {
		addr_rule_t* rule = NULL;
		rule = g_malloc0(sizeof(addr_rule_t));

		if (!access_rules[i] || !*(access_rules[i]))
			continue;

		/* regex matching [X.X.X.X/X xxxx] or [X.X.X.X X.X.X.X xxxx] or [xxxx X.X.X.X] */
		if(g_str_has_prefix(access_rules[i], "host")) {
			rule->authorize = TRUE;
			gchar** splits = g_strsplit(access_rules[i], " ", 2);	
			rule->network_addr = g_strdup(splits[1]);	
			gchar buff[50];
			memset(buff, 0, sizeof(buff));	
			g_snprintf(buff, sizeof(buff), "255.255.255.255");
			rule->network_mask = g_strdup(buff); 
			g_strfreev(splits);
		} else {
			gchar** line_splits = NULL;
			line_splits = g_strsplit(access_rules[i], " ", 0);
			if (g_strv_length(line_splits) == 3) {
				rule->network_addr = g_strdup(line_splits[0]);
				rule->network_mask = g_strdup(line_splits[1]);
			}
			else {
				if(g_regex_match_full(range_regex, line_splits[0], strlen(line_splits[0]), 0, 0, NULL, &error)) {
					gchar** tmp_array = NULL;
					gchar* tmp = NULL;
					tmp = _range2netmask(line_splits[0]);
					tmp_array = g_strsplit(tmp, " ", 2);
					rule->network_addr = g_strdup(tmp_array[0]);
					rule->network_mask = g_strdup(tmp_array[1]);
					g_free(tmp);
					g_strfreev(tmp_array);
				} else {
					/* Failed to read line */
				}

				if(g_str_has_suffix(access_rules[i],"allow")) 
					rule->authorize = TRUE;
				else
					rule->authorize = FALSE;
			}
			g_strfreev(line_splits);
		}
		result = g_slist_prepend(result, rule);
	}

	g_strfreev(access_rules);

	return g_slist_reverse(result);
}
/**
 * rakia_codec_param_parse_generic:
 * @fmtp: a string value with the parameter description
 * @out: the parameter map to populate
 *
 * Parses parameters formatted as a semicolon separated list of
 * <replaceable>parameter</replaceable><literal>=</literal><replaceable>value</replaceable>
 * pairs, as recommended in IETF RFC 4855 Section 3.
 */
static void
rakia_codec_param_parse_generic (const gchar *fmtp, TpMediaStreamType media_type,
    RakiaSipCodec *codec)
{
  GMatchInfo *match = NULL;
  gint pos;
  gint value_start;
  gint value_end;

  if (fmtp == NULL)
    return;

  pos = 0;

  /* Fast path for trivial cases, not involving the regex engine */
  while (g_ascii_isspace (fmtp[pos]))
    ++pos;
  if (!fmtp[pos])
    return;

  g_assert (fmtp_attr_regex != NULL);

  g_regex_match_full (fmtp_attr_regex,
      fmtp, -1, pos, G_REGEX_MATCH_ANCHORED, &match, NULL);

  while (g_match_info_matches (match))
    {
      gchar *name;
      gchar *value;

      name = g_match_info_fetch_named (match, FMTP_MATCH_NAME_PARAM);

      g_match_info_fetch_named_pos (match, FMTP_MATCH_NAME_VALUE,
          &value_start, &value_end);

      if (value_end - 1 > value_start
          && fmtp[value_start] == '\"' && fmtp[value_end - 1] == '\"')
        {
          value = rakia_unquote_string (fmtp + value_start,
                                        value_end - value_start);
        }
      else
        {
          value = g_strndup (fmtp + value_start,
                             value_end - value_start);
        }

      rakia_sip_codec_add_param (codec, name, value);

      g_match_info_fetch_pos (match, 0, NULL, &pos);
      if (!fmtp[pos])
        break;

      g_match_info_next (match, NULL);
    }

  g_match_info_free (match);

  if (fmtp[pos])
    MESSAGE ("failed to parse part of format parameters"
               " as an attribute-value list: %s", &fmtp[pos]);
}
Example #30
0
void dt_collection_split_operator_datetime(const gchar *input, char **number1, char **number2, char **operator)
{
  GRegex *regex;
  GMatchInfo *match_info;
  int match_count;

  *number1 = *number2 = *operator= NULL;

  // we test the range expression first
  // 4 elements : date1 time1(optional) date2 time2(optional)
  regex = g_regex_new("^\\s*\\[\\s*(\\d{4}:\\d{2}:\\d{2})\\s*( "
                      "\\d{2}:\\d{2}:\\d{2})?\\s*;\\s*(\\d{4}:\\d{2}:\\d{2})\\s*( "
                      "\\d{2}:\\d{2}:\\d{2})?\\s*\\]\\s*$",
                      0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count >= 4)
  {
    *number1 = g_match_info_fetch(match_info, 1);
    gchar *number1_time = g_match_info_fetch(match_info, 2);
    *number2 = g_match_info_fetch(match_info, 3);
    *operator= g_strdup("[]");

    if(!number1_time || strcmp(number1_time, "") == 0)
      *number1 = dt_util_dstrcat(*number1, " 00:00:00");
    else
      *number1 = dt_util_dstrcat(*number1, "%s", number1_time);

    if(match_count == 5)
    {
      gchar *number2_time = g_match_info_fetch(match_info, 4);
      *number2 = dt_util_dstrcat(*number2, "%s", number2_time);
      g_free(number2_time);
    }
    else
      *number2 = dt_util_dstrcat(*number2, " 23:59:59");

    if(number1_time) g_free(number1_time);
    g_match_info_free(match_info);
    g_regex_unref(regex);
    return;
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);

  // and we test the classic comparaison operators
  // 2 elements : date time(optional)
  regex = g_regex_new("^\\s*(=|<|>|<=|>=|<>)?\\s*(\\d{4}:\\d{2}:\\d{2})\\s*( \\d{2}:\\d{2}:\\d{2})?\\s*$", 0,
                      0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count >= 3)
  {
    *operator= g_match_info_fetch(match_info, 1);
    *number1 = g_match_info_fetch(match_info, 2);
    // we fill the time part if it's not set
    if(match_count == 4)
    {
      gchar *nb_time = g_match_info_fetch(match_info, 3);
      *number1 = dt_util_dstrcat(*number1, "%s", nb_time);
      g_free(nb_time);
    }
    else if(*operator&& strcmp(*operator, ">") == 0)
      *number1 = dt_util_dstrcat(*number1, " 23:59:59");
    else if(*operator&& strcmp(*operator, ">=") == 0)
      *number1 = dt_util_dstrcat(*number1, " 00:00:00");
    else if(*operator&& strcmp(*operator, "<") == 0)
      *number1 = dt_util_dstrcat(*number1, " 00:00:00");
    else if(*operator&& strcmp(*operator, "<=") == 0)
      *number1 = dt_util_dstrcat(*number1, " 23:59:59");
    else if(*operator&& strcmp(*operator, "=") == 0)
      *number1 = dt_util_dstrcat(*number1, "%%");
    else if(*operator&& strcmp(*operator, "<>") == 0)
      *number1 = dt_util_dstrcat(*number1, "%%");
    else if(*operator&& strcmp(*operator, "") == 0)
      *number1 = dt_util_dstrcat(*number1, "%%");
    else if(!*operator)
      *number1 = dt_util_dstrcat(*number1, "%%");

    if(*operator&& strcmp(*operator, "") == 0)
    {
      g_free(*operator);
      *operator= NULL;
    }
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);
}