示例#1
0
Session *session_get_by_jid(const char *jid,Stream *stream,int delay_login){
Session *s;
User *u;
char *njid;
GList *it;

	g_assert(sessions_jid!=NULL);
	debug(L_("Looking up session for '%s'"),jid);
	njid=jid_normalized(jid,0);
	if (njid==NULL){
		g_message(L_("Bad JID: '%s'"),jid);
		return NULL;
	}

	debug(L_("Using '%s' as key"),njid);
	s=(Session *)g_hash_table_lookup(sessions_jid,(gpointer)njid);
	g_free(njid);
	if (s) return s;
	debug(L_("Session not found"));
	if (!stream) return NULL;
	u=user_get_by_jid(jid);
	if (!u) return NULL;

	debug(L_("User loaded, processing his subscriptions."));
	for(it=g_list_first(u->contacts);it;it=g_list_next(it)){
		Contact *c;
		char *c_jid;
		c=(Contact *)it->data;
		if (c->subscribe == SUB_UNDEFINED) {
			c_jid=jid_build(c->uin);
			presence_send_subscribe(stream,c_jid,u->jid);
			g_free(c_jid);
		}
		else if (c->subscribe == SUB_FROM || c->subscribe == SUB_BOTH){
			c_jid=jid_build(c->uin);
			presence_send_probe(stream,c_jid,u->jid);
			g_free(c_jid);
		}
	}
	debug(L_("Creating new session"));
	return session_create(u,jid,NULL,NULL,stream,delay_login);
}
示例#2
0
Application::~Application()
{
    L_(info) << "total microslices processed: " << count_;
}
    {
      retval *= 10;
      retval += (unsigned char) **pstr - '0';
    }

  return retval;
}

#define PADSIZE 16
static char const blanks[PADSIZE] =
{' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
static char const zeroes[PADSIZE] =
{'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
static wchar_t const wblanks[PADSIZE] =
{
  L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '),
  L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' '), L_(' ')
};
static wchar_t const wzeroes[PADSIZE] =
{
  L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'),
  L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0'), L_('0')
};

attribute_hidden size_t
__quadmath_do_pad (struct __quadmath_printf_file *fp, int wide, int c,
		   size_t n)
{
  ssize_t i;
  char padbuf[PADSIZE];
  wchar_t wpadbuf[PADSIZE];
示例#4
0
INT
INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr,
		   int base, int group LOCALE_PARAM_PROTO)
{
  int negative;
  register unsigned LONG int cutoff;
  register unsigned int cutlim;
  register unsigned LONG int i;
  register const STRING_TYPE *s;
  register UCHAR_TYPE c;
  const STRING_TYPE *save, *end;
  int overflow;

#ifdef USE_NUMBER_GROUPING
# ifdef USE_IN_EXTENDED_LOCALE_MODEL
  struct locale_data *current = loc->__locales[LC_NUMERIC];
# endif
  /* The thousands character of the current locale.  */
  wchar_t thousands = L'\0';
  /* The numeric grouping specification of the current locale,
     in the format described in <locale.h>.  */
  const char *grouping;

  if (group)
    {
      grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
      if (*grouping <= 0 || *grouping == CHAR_MAX)
	grouping = NULL;
      else
	{
	  /* Figure out the thousands separator character.  */
# if defined _LIBC || defined _HAVE_BTOWC
	  thousands = __btowc (*_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP));
	  if (thousands == WEOF)
	    thousands = L'\0';
# endif
	  if (thousands == L'\0')
	    grouping = NULL;
	}
    }
  else
    grouping = NULL;
#endif

  if (base < 0 || base == 1 || base > 36)
    {
      __set_errno (EINVAL);
      return 0;
    }

  save = s = nptr;

  /* Skip white space.  */
  while (ISSPACE (*s))
    ++s;
  if (*s == L_('\0'))
    goto noconv;

  /* Check for a sign.  */
  if (*s == L_('-'))
    {
      negative = 1;
      ++s;
    }
  else if (*s == L_('+'))
    {
      negative = 0;
      ++s;
    }
  else
    negative = 0;

  /* Recognize number prefix and if BASE is zero, figure it out ourselves.  */
  if (*s == L_('0'))
    {
      if ((base == 0 || base == 16) && TOUPPER (s[1]) == L_('X'))
	{
	  s += 2;
	  base = 16;
	}
      else if (base == 0)
	base = 8;
    }
  else if (base == 0)
    base = 10;

  /* Save the pointer so we can check later if anything happened.  */
  save = s;

#ifdef USE_NUMBER_GROUPING
  if (group)
    {
      /* Find the end of the digit string and check its grouping.  */
      end = s;
      for (c = *end; c != L_('\0'); c = *++end)
	if ((wchar_t) c != thousands
	    && ((wchar_t) c < L_('0') || (wchar_t) c > L_('9'))
	    && (!ISALPHA (c) || (int) (TOUPPER (c) - L_('A') + 10) >= base))
	  break;
      if (*s == thousands)
	end = s;
      else
	end = correctly_grouped_prefix (s, end, thousands, grouping);
    }
  else
#endif
    end = NULL;

  cutoff = STRTOL_ULONG_MAX / (unsigned LONG int) base;
  cutlim = STRTOL_ULONG_MAX % (unsigned LONG int) base;

  overflow = 0;
  i = 0;
  for (c = *s; c != L_('\0'); c = *++s)
    {
      if (s == end)
	break;
      if (c >= L_('0') && c <= L_('9'))
	c -= L_('0');
      else if (ISALPHA (c))
	c = TOUPPER (c) - L_('A') + 10;
      else
	break;
      if ((int) c >= base)
	break;
      /* Check for overflow.  */
      if (i > cutoff || (i == cutoff && c > cutlim))
	overflow = 1;
      else
	{
	  i *= (unsigned LONG int) base;
	  i += c;
	}
    }

  /* Check if anything actually happened.  */
  if (s == save)
    goto noconv;

  /* Store in ENDPTR the address of one character
     past the last character we converted.  */
  if (endptr != NULL)
    *endptr = (STRING_TYPE *) s;

#if !UNSIGNED
  /* Check for a value that is within the range of
     `unsigned LONG int', but outside the range of `LONG int'.  */
  if (overflow == 0
      && i > (negative
	      ? -((unsigned LONG int) (STRTOL_LONG_MIN + 1)) + 1
	      : (unsigned LONG int) STRTOL_LONG_MAX))
    overflow = 1;
#endif

  if (overflow)
    {
      __set_errno (ERANGE);
#if UNSIGNED
      return STRTOL_ULONG_MAX;
#else
      return negative ? STRTOL_LONG_MIN : STRTOL_LONG_MAX;
#endif
    }

  /* Return the result of the appropriate sign.  */
  return negative ? -i : i;

noconv:
  /* We must handle a special case here: the base is 0 or 16 and the
     first two characters are '0' and 'x', but the rest are no
     hexadecimal digits.  This is no error case.  We return 0 and
     ENDPTR points to the `x`.  */
  if (endptr != NULL)
    {
      if (save - nptr >= 2 && TOUPPER (save[-1]) == L_('X')
	  && save[-2] == L_('0'))
	*endptr = (STRING_TYPE *) &save[-1];
      else
	/*  There was no number to convert.  */
	*endptr = (STRING_TYPE *) nptr;
    }

  return 0L;
}
示例#5
0
Application::Application(Parameters const& par) : par_(par)
{

    // Source setup
    if (!par_.input_shm.empty()) {
        L_(info) << "using shared memory as data source: " << par_.input_shm;

        shm_device_ = std::make_shared<flib_shm_device_client>(par_.input_shm);

        if (par_.shm_channel < shm_device_->num_channels()) {
            data_source_.reset(
                new flib_shm_channel_client(shm_device_, par_.shm_channel));

        } else {
            throw std::runtime_error("shared memory channel not available");
        }
    }

    if (data_source_) {
        source_.reset(new fles::MicrosliceReceiver(*data_source_));
    } else if (!par_.input_archive.empty()) {
        source_.reset(new fles::MicrosliceInputArchive(par_.input_archive));
    }

    // Sink setup
    if (par_.debugger) {
        sinks_.push_back(std::unique_ptr<fles::MicrosliceSink>(
            new NgdpbMicrosliceDumper(std::cout, par_.dump_verbosity)));
    }

    if (!par_.output_archive.empty()) {
        if ( par_.sorter ) {
            filtered_output_archive_ = new fles::MicrosliceOutputArchive(par_.output_archive);
            ngdpb_sorter_arch_       = new fles::NdpbEpochToMsSorter( par_.epoch_per_ms, par_.sortmesg );
            sinks_.push_back(std::unique_ptr<fles::MicrosliceSink>(
                    new fles::FilteringMicrosliceSink(*filtered_output_archive_, *ngdpb_sorter_arch_)));
        } else {
            sinks_.push_back(std::unique_ptr<fles::MicrosliceSink>(
               new fles::MicrosliceOutputArchive(par_.output_archive)));
        }
    }

    if (!par_.output_shm.empty()) {
        L_(info) << "providing output in shared memory: " << par_.output_shm;

        constexpr std::size_t desc_buffer_size_exp = 19; // 512 ki entries
        constexpr std::size_t data_buffer_size_exp = 27; // 128 MiB

        output_shm_device_.reset(new flib_shm_device_provider(
            par_.output_shm, 1, data_buffer_size_exp, desc_buffer_size_exp));
        InputBufferWriteInterface* data_sink =
            output_shm_device_->channels().at(0);
        if ( par_.sorter ) {
            filtered_output_mstrans_ = new fles::MicrosliceTransmitter(*data_sink);
            ngdpb_sorter_shm_        = new fles::NdpbEpochToMsSorter( par_.epoch_per_ms, par_.sortmesg );
            sinks_.push_back(std::unique_ptr<fles::MicrosliceSink>(
                    new fles::FilteringMicrosliceSink(*filtered_output_mstrans_, *ngdpb_sorter_shm_)));
        } else {
            sinks_.push_back(std::unique_ptr<fles::MicrosliceSink>(
                new fles::MicrosliceTransmitter(*data_sink)));
        }
    }
    tStart = std::chrono::steady_clock::now();
}
示例#6
0
void IBConnection::on_disconnected(struct rdma_cm_event* /* event */)
{
    L_(debug) << "[" << index_ << "] "
              << "connection disconnected";
}
示例#7
0
int
__quadmath_printf_fphex (struct __quadmath_printf_file *fp,
			 const struct printf_info *info,
			 const void *const *args)
{
  /* The floating-point value to output.  */
  ieee854_float128 fpnum;

  /* Locale-dependent representation of decimal point.	*/
  const char *decimal;
  wchar_t decimalwc;

  /* "NaN" or "Inf" for the special cases.  */
  const char *special = NULL;
  const wchar_t *wspecial = NULL;

  /* Buffer for the generated number string for the mantissa.  The
     maximal size for the mantissa is 128 bits.  */
  char numbuf[32];
  char *numstr;
  char *numend;
  wchar_t wnumbuf[32];
  wchar_t *wnumstr;
  wchar_t *wnumend;
  int negative;

  /* The maximal exponent of two in decimal notation has 5 digits.  */
  char expbuf[5];
  char *expstr;
  wchar_t wexpbuf[5];
  wchar_t *wexpstr;
  int expnegative;
  int exponent;

  /* Non-zero is mantissa is zero.  */
  int zero_mantissa;

  /* The leading digit before the decimal point.  */
  char leading;

  /* Precision.  */
  int precision = info->prec;

  /* Width.  */
  int width = info->width;

  /* Number of characters written.  */
  int done = 0;

  /* Nonzero if this is output on a wide character stream.  */
  int wide = info->wide;

  bool do_round_away;

  /* Figure out the decimal point character.  */
#ifdef USE_NL_LANGINFO
  if (info->extra == 0)
    decimal = nl_langinfo (DECIMAL_POINT);
  else
    {
      decimal = nl_langinfo (MON_DECIMAL_POINT);
      if (*decimal == '\0')
	decimal = nl_langinfo (DECIMAL_POINT);
    }
  /* The decimal point character must never be zero.  */
  assert (*decimal != '\0');
#elif defined USE_LOCALECONV
  const struct lconv *lc = localeconv ();
  if (info->extra == 0)
    decimal = lc->decimal_point;
  else
    {
      decimal = lc->mon_decimal_point;
      if (decimal == NULL || *decimal == '\0')
	decimal = lc->decimal_point;
    }
  if (decimal == NULL || *decimal == '\0')
    decimal = ".";
#else
  decimal = ".";
#endif
#ifdef USE_NL_LANGINFO_WC
  if (info->extra == 0)
    decimalwc = nl_langinfo_wc (_NL_NUMERIC_DECIMAL_POINT_WC);
  else
    {
      decimalwc = nl_langinfo_wc (_NL_MONETARY_DECIMAL_POINT_WC);
      if (decimalwc == L_('\0'))
	decimalwc = nl_langinfo_wc (_NL_NUMERIC_DECIMAL_POINT_WC);
    }
  /* The decimal point character must never be zero.  */
  assert (decimalwc != L_('\0'));
#else
  decimalwc = L_('.');
#endif

  /* Fetch the argument value.	*/
    {
      fpnum.value = **(const __float128 **) args[0];

      /* Check for special values: not a number or infinity.  */
      if (isnanq (fpnum.value))
	{
	  negative = fpnum.ieee.negative != 0;
	  if (isupper (info->spec))
	    {
	      special = "NAN";
	      wspecial = L_("NAN");
	    }
	  else
	    {
	      special = "nan";
	      wspecial = L_("nan");
	    }
	}
      else
	{
	  if (isinfq (fpnum.value))
	    {
	      if (isupper (info->spec))
		{
		  special = "INF";
		  wspecial = L_("INF");
		}
	      else
		{
		  special = "inf";
		  wspecial = L_("inf");
		}
	    }

	  negative = signbitq (fpnum.value);
	}
    }

  if (special)
    {
      int width = info->width;

      if (negative || info->showsign || info->space)
	--width;
      width -= 3;

      if (!info->left && width > 0)
	PADN (' ', width);

      if (negative)
	outchar ('-');
      else if (info->showsign)
	outchar ('+');
      else if (info->space)
	outchar (' ');

      PRINT (special, wspecial, 3);

      if (info->left && width > 0)
	PADN (' ', width);

      return done;
    }

    {
      /* We have 112 bits of mantissa plus one implicit digit.  Since
	 112 bits are representable without rest using hexadecimal
	 digits we use only the implicit digits for the number before
	 the decimal point.  */
      uint64_t num0, num1;

      assert (sizeof (long double) == 16);

      num0 = fpnum.ieee.mant_high;
      num1 = fpnum.ieee.mant_low;

      zero_mantissa = (num0|num1) == 0;

      if (sizeof (unsigned long int) > 6)
	{
	  numstr = _itoa_word (num1, numbuf + sizeof numbuf, 16,
			       info->spec == 'A');
	  wnumstr = _itowa_word (num1,
				 wnumbuf + sizeof (wnumbuf) / sizeof (wchar_t),
				 16, info->spec == 'A');
	}
      else
	{
	  numstr = _itoa (num1, numbuf + sizeof numbuf, 16,
			  info->spec == 'A');
	  wnumstr = _itowa (num1,
			    wnumbuf + sizeof (wnumbuf) / sizeof (wchar_t),
			    16, info->spec == 'A');
	}

      while (numstr > numbuf + (sizeof numbuf - 64 / 4))
	{
	  *--numstr = '0';
	  *--wnumstr = L_('0');
	}

      if (sizeof (unsigned long int) > 6)
	{
	  numstr = _itoa_word (num0, numstr, 16, info->spec == 'A');
	  wnumstr = _itowa_word (num0, wnumstr, 16, info->spec == 'A');
	}
      else
	{
	  numstr = _itoa (num0, numstr, 16, info->spec == 'A');
	  wnumstr = _itowa (num0, wnumstr, 16, info->spec == 'A');
	}

      /* Fill with zeroes.  */
      while (numstr > numbuf + (sizeof numbuf - 112 / 4))
	{
	  *--wnumstr = L_('0');
	  *--numstr = '0';
	}

      leading = fpnum.ieee.exponent == 0 ? '0' : '1';

      exponent = fpnum.ieee.exponent;

      if (exponent == 0)
	{
	  if (zero_mantissa)
	    expnegative = 0;
	  else
	    {
	      /* This is a denormalized number.  */
	      expnegative = 1;
	      exponent = IEEE854_FLOAT128_BIAS - 1;
	    }
	}
      else if (exponent >= IEEE854_FLOAT128_BIAS)
	{
	  expnegative = 0;
	  exponent -= IEEE854_FLOAT128_BIAS;
	}
      else
	{
	  expnegative = 1;
	  exponent = -(exponent - IEEE854_FLOAT128_BIAS);
	}
    }

  /* Look for trailing zeroes.  */
  if (! zero_mantissa)
    {
      wnumend = &wnumbuf[sizeof wnumbuf / sizeof wnumbuf[0]];
      numend = &numbuf[sizeof numbuf / sizeof numbuf[0]];
      while (wnumend[-1] == L_('0'))
	{
	  --wnumend;
	  --numend;
	}

      do_round_away = false;

      if (precision != -1 && precision < numend - numstr)
	{
	  char last_digit = precision > 0 ? numstr[precision - 1] : leading;
	  char next_digit = numstr[precision];
	  int last_digit_value = (last_digit >= 'A' && last_digit <= 'F'
				  ? last_digit - 'A' + 10
				  : (last_digit >= 'a' && last_digit <= 'f'
				     ? last_digit - 'a' + 10
				     : last_digit - '0'));
	  int next_digit_value = (next_digit >= 'A' && next_digit <= 'F'
				  ? next_digit - 'A' + 10
				  : (next_digit >= 'a' && next_digit <= 'f'
				     ? next_digit - 'a' + 10
				     : next_digit - '0'));
	  bool more_bits = ((next_digit_value & 7) != 0
			    || precision + 1 < numend - numstr);
#ifdef HAVE_FENV_H
	  int rounding_mode = get_rounding_mode ();
	  do_round_away = round_away (negative, last_digit_value & 1,
				      next_digit_value >= 8, more_bits,
				      rounding_mode);
#endif
	}

      if (precision == -1)
	precision = numend - numstr;
      else if (do_round_away)
	{
	  /* Round up.  */
	  int cnt = precision;
	  while (--cnt >= 0)
	    {
	      char ch = numstr[cnt];
	      /* We assume that the digits and the letters are ordered
		 like in ASCII.  This is true for the rest of GNU, too.  */
	      if (ch == '9')
		{
		  wnumstr[cnt] = (wchar_t) info->spec;
		  numstr[cnt] = info->spec;	/* This is tricky,
		  				   think about it!  */
		  break;
		}
	      else if (tolower (ch) < 'f')
		{
		  ++numstr[cnt];
		  ++wnumstr[cnt];
		  break;
		}
	      else
		{
		  numstr[cnt] = '0';
		  wnumstr[cnt] = L_('0');
		}
	    }
	  if (cnt < 0)
	    {
	      /* The mantissa so far was fff...f  Now increment the
		 leading digit.  Here it is again possible that we
		 get an overflow.  */
	      if (leading == '9')
		leading = info->spec;
	      else if (tolower (leading) < 'f')
		++leading;
	      else
		{
		  leading = '1';
		  if (expnegative)
		    {
		      exponent -= 4;
		      if (exponent <= 0)
			{
			  exponent = -exponent;
			  expnegative = 0;
			}
		    }
		  else
		    exponent += 4;
		}
	    }
	}
    }
  else
    {
      if (precision == -1)
	precision = 0;
      numend = numstr;
      wnumend = wnumstr;
    }

  /* Now we can compute the exponent string.  */
  expstr = _itoa_word (exponent, expbuf + sizeof expbuf, 10, 0);
  wexpstr = _itowa_word (exponent,
			 wexpbuf + sizeof wexpbuf / sizeof (wchar_t), 10, 0);

  /* Now we have all information to compute the size.  */
  width -= ((negative || info->showsign || info->space)
	    /* Sign.  */
	    + 2    + 1 + 0 + precision + 1 + 1
	    /* 0x    h   .   hhh         P   ExpoSign.  */
	    + ((expbuf + sizeof expbuf) - expstr));
	    /* Exponent.  */

  /* Count the decimal point.
     A special case when the mantissa or the precision is zero and the `#'
     is not given.  In this case we must not print the decimal point.  */
  if (precision > 0 || info->alt)
    width -= wide ? 1 : strlen (decimal);

  if (!info->left && info->pad != '0' && width > 0)
    PADN (' ', width);

  if (negative)
    outchar ('-');
  else if (info->showsign)
    outchar ('+');
  else if (info->space)
    outchar (' ');

  outchar ('0');
  if ('X' - 'A' == 'x' - 'a')
    outchar (info->spec + ('x' - 'a'));
  else
    outchar (info->spec == 'A' ? 'X' : 'x');

  if (!info->left && info->pad == '0' && width > 0)
    PADN ('0', width);

  outchar (leading);

  if (precision > 0 || info->alt)
    {
      const wchar_t *wtmp = &decimalwc;
      PRINT (decimal, wtmp, wide ? 1 : strlen (decimal));
    }

  if (precision > 0)
    {
      ssize_t tofill = precision - (numend - numstr);
      PRINT (numstr, wnumstr, MIN (numend - numstr, precision));
      if (tofill > 0)
	PADN ('0', tofill);
    }

  if ('P' - 'A' == 'p' - 'a')
    outchar (info->spec + ('p' - 'a'));
  else
    outchar (info->spec == 'A' ? 'P' : 'p');

  outchar (expnegative ? '-' : '+');

  PRINT (expstr, wexpstr, (expbuf + sizeof expbuf) - expstr);

  if (info->left && info->pad != '0' && width > 0)
    PADN (info->pad, width);

  return done;
}
示例#8
0
User *user_load(const char *jid){
char *fn,*njid;
xmlnode xml,tag,t;
char *uin,*ujid,*name,*password,*email,*locale;
char *status;
int last_sys_msg=0,invisible=0,friends_only=0,ignore_unknown=0;
unsigned int file_format_version=0;
SubscriptionType subscribe;
User *u;
GList *contacts;
char *p;
char *data;

	uin=ujid=name=password=email=NULL;
	debug(L_("Loading user '%s'"),jid);
	fn=jid_normalized(jid,0);
	if (fn==NULL){
		g_warning(L_("Bad JID: %s"),jid);
		return NULL;
	}
	errno=0;
	xml=xmlnode_file(fn);
	if (xml==NULL){
		debug(L_("Couldn't read or parse '%s': %s"),fn,errno?g_strerror(errno):N_("XML parse error"));
		g_free(fn);
		return NULL;
	}
	g_free(fn);
	tag=xmlnode_get_tag(xml,"version");
	if (tag!=NULL) {
		p=xmlnode_get_attrib(tag,"file_format");
		if (p!=NULL) file_format_version=(unsigned int)strtol(p,NULL,16);
	}
	tag=xmlnode_get_tag(xml,"jid");
	if (tag!=NULL) {
		ujid=xmlnode_get_data(tag);
		subscribe=get_subscribe(tag, file_format_version);
	}
	if (ujid==NULL){
		g_warning(L_("Couldn't find JID in %s's file"),jid);
		return NULL;
	}
	tag=xmlnode_get_tag(xml,"uin");
	if (tag!=NULL) uin=xmlnode_get_data(tag);
	if (uin==NULL){
		g_warning(L_("Couldn't find UIN in %s's file"),jid);
		return NULL;
	}
	tag=xmlnode_get_tag(xml,"password");
	if (tag!=NULL) password=xmlnode_get_data(tag);
	if (password==NULL){
		g_warning(L_("Couldn't find password in %s's file"),jid);
		return NULL;
	}
	tag=xmlnode_get_tag(xml,"email");
	if (tag!=NULL) email=xmlnode_get_data(tag);
	tag=xmlnode_get_tag(xml,"name");
	if (tag!=NULL) name=xmlnode_get_data(tag);
	tag=xmlnode_get_tag(xml,"last_sys_msg");
	if (tag!=NULL){
		data=xmlnode_get_data(tag);
		if (data!=NULL)
			last_sys_msg=atoi(data);
	}
	tag=xmlnode_get_tag(xml,"friendsonly");
	if (tag!=NULL) friends_only=1;
	tag=xmlnode_get_tag(xml,"invisible");
	if (tag!=NULL) invisible=1;
	tag=xmlnode_get_tag(xml,"ignore_unknown");
	if (tag!=NULL) ignore_unknown=1;
	tag=xmlnode_get_tag(xml,"locale");
	if (tag!=NULL) locale=xmlnode_get_data(tag);
	else locale=NULL;
	tag=xmlnode_get_tag(xml,"status");
	if (tag!=NULL) {
		status=xmlnode_get_data(tag);
		if (status==NULL) status="";
	}
	else status=NULL;
	tag=xmlnode_get_tag(xml,"userlist");
	contacts=NULL;
	if (tag!=NULL){
		Contact *c;

		for(t=xmlnode_get_firstchild(tag);t;t=xmlnode_get_nextsibling(t)){
			char *node_name;
			node_name=xmlnode_get_name(t);
			if (!node_name) continue;
			if (!strcmp(node_name,"uin")){
				char *d;
				int uin;

				d=xmlnode_get_data(t);
				if (d==NULL) continue;
				uin=atoi(d);
				if (uin<=0) continue;

				c=g_new0(Contact,1);
				c->status=-1;
				c->uin=uin;
				contacts=g_list_append(contacts,c);
				continue;
			}
			if (!strcmp(node_name,"contact")){
				char *d;
				int uin;

				d=xmlnode_get_attrib(t,"uin");
				if (d==NULL) continue;
				
				uin=atoi(d);
				if (uin<=0) continue;

				c=g_new0(Contact,1);
				c->status=-1;
				c->uin=uin;
				
				d=xmlnode_get_attrib(t,"ignored");
				if (d!=NULL && d[0]!='\000') c->ignored=1;
				else c->ignored=0;
				d=xmlnode_get_attrib(t,"blocked");
				if (d!=NULL && d[0]!='\000') c->blocked=1;
				else c->blocked=0;
				c->subscribe=get_subscribe(t, file_format_version);
				contacts=g_list_append(contacts,c);
			}
		}
	}
	u=g_new0(User,1);
	u->uin=atoi(uin);
	u->jid=g_strdup(jid);
	p=strchr(u->jid,'/');
	if (p) *p=0;
	u->password=g_strdup(password);
	u->last_sys_msg=last_sys_msg;
	u->friends_only=friends_only;
	u->invisible=invisible;
	u->ignore_unknown=ignore_unknown;
	u->locale=g_strdup(locale);
	u->status=g_strdup(from_utf8(status));
	u->contacts=contacts;
	xmlnode_free(xml);
	g_assert(users_jid!=NULL);
	njid=jid_normalized(u->jid,0);
	g_assert(njid!=NULL);
	g_hash_table_insert(users_jid,(gpointer)njid,(gpointer)u);
	u->confirmed=1;
	u->subscribe=subscribe;
	return u;
}
/* 2^LIMB_BITS.  */
static const DOUBLE TWO_LIMB_BITS =
  /* Assume LIMB_BITS <= 3 * 31.
     Use the identity
       n = floor(n/3) + floor((n+1)/3) + floor((n+2)/3).  */
  (DOUBLE) (1U << (LIMB_BITS / 3))
  * (DOUBLE) (1U << ((LIMB_BITS + 1) / 3))
  * (DOUBLE) (1U << ((LIMB_BITS + 2) / 3));

/* 2^-LIMB_BITS.  */
static const DOUBLE TWO_LIMB_BITS_INVERSE =
  /* Assume LIMB_BITS <= 3 * 31.
     Use the identity
       n = floor(n/3) + floor((n+1)/3) + floor((n+2)/3).  */
  L_(1.0) / ((DOUBLE) (1U << (LIMB_BITS / 3))
             * (DOUBLE) (1U << ((LIMB_BITS + 1) / 3))
             * (DOUBLE) (1U << ((LIMB_BITS + 2) / 3)));

DOUBLE
FMOD (DOUBLE x, DOUBLE y)
{
  if (isfinite (x) && isfinite (y) && y != L_(0.0))
    {
      if (x == L_(0.0))
        /* Return x, regardless of the sign of y.  */
        return x;

      {
        int negate = ((!signbit (x)) ^ (!signbit (y)));
示例#10
0
int sessions_init(){
char *proxy_ip,*proxy_username,*proxy_password,*proxy_http_only;
char *p,*r;
int port;
int i;
xmlnode parent,tag;
GgServer *server;

	stream_add_destroy_handler(sessions_stream_destroyed);

	sessions_jid=g_hash_table_new(g_str_hash,g_str_equal);
	if (!sessions_jid) return -1;

	i=config_load_int("conn_timeout",0);
	if (i>0) conn_timeout=i;
	i=config_load_int("pong_timeout",0);
	if (i>0) pong_timeout=i;
	i=config_load_int("ping_interval",0);
	if (i>0) ping_interval=i;
	i=config_load_int("reconnect",0);
	if (i>0) reconnect=i;
	i=config_load_int("server_cutoff",0);
	if (i>0) cutoff=i;
	i=config_load_int("server_cutoff_timeout",0);
	if (i>0) cutoff_timeout=i;

	tag = xmlnode_get_tag(config, "ignore_system_messages");
	if (!tag) {
		ignore_system_messages = ISM_IGNORE_NONE;
	}
	else {
		r=xmlnode_get_attrib(tag, "which");
		if (r && !g_strcasecmp(r,"html")) {
			ignore_system_messages = ISM_IGNORE_HTML;
		}
		else {
			ignore_system_messages = ISM_IGNORE_ALL;
		}
	}

	parent=xmlnode_get_tag(config,"servers");
	if (parent && xmlnode_has_children(parent)){
		gg_servers=NULL;
		for(tag=xmlnode_get_firstchild(parent); tag!=NULL;
				tag=xmlnode_get_nextsibling(tag)){
			if(xmlnode_get_type(tag) != NTYPE_TAG) continue;
			p=xmlnode_get_name(tag);
			if (strcmp(p, "hub")==0){
				server=g_new(GgServer, 1);
				server->port=1;
				gg_servers=g_list_append(gg_servers, server);
			}
			else if (strcmp(p, "server")==0){
				server=g_new(GgServer, 1);
				server->error_count=0;
				r=xmlnode_get_attrib(tag, "port");
				if (r)
					server->port=atoi(r);
				else
					server->port=8074;
				r=xmlnode_get_data(tag);
				if(inet_aton(r, &server->addr))
					gg_servers=g_list_append(gg_servers, server);
			}
			else continue;

			r=xmlnode_get_attrib(tag, "tls");
			if (r && !g_strcasecmp(r,"no"))
				server->tls=0;
			else
				server->tls=1;
		}


	}
	else{
		server=g_new(GgServer, 1);
		server->port=1;
		server->tls=0;
		gg_servers=g_list_append(gg_servers, server);

		server=g_new(GgServer, 1);
		server->error_count=0;
		inet_aton("217.17.45.145", &server->addr);
		server->port=8074;
		server->tls=0;
		gg_servers=g_list_append(gg_servers, server);
	}

	proxy_ip=config_load_string("proxy/ip");
	if (!proxy_ip) return 0;
	port=config_load_int("proxy/port",0);
	if (port<=0) return 0;
	proxy_username=config_load_string("proxy/username");
	proxy_password=config_load_string("proxy/password");

	tag=xmlnode_get_tag(config,"proxy");
	proxy_http_only=xmlnode_get_attrib(tag,"http_only");

	g_message(L_("Using proxy: http://%s:%i"),proxy_ip,port);
	gg_proxy_enabled=1;
	gg_proxy_host=proxy_ip;
	gg_proxy_port=port;
	if (proxy_username && proxy_password){
		gg_proxy_username=proxy_username;
		gg_proxy_password=proxy_password;
	}
	if (proxy_http_only && strcmp(proxy_http_only,"no")){
		gg_proxy_http_only=1;
	}
	return 0;
}
示例#11
0
int session_io_handler(Session *s){
struct gg_event *event;
char *jid,*str;
int chat;
GIOCondition condition=s->g_pollfd.revents;
time_t timestamp;
gboolean state;

	user_load_locale(s->user);
	debug(L_("Checking error conditions..."));
	if (condition&(G_IO_ERR|G_IO_NVAL)){
		if (condition&G_IO_ERR) g_warning(N_("Error on connection for %s, GGid: %i"),s->jid,s->ggs->uin);
		if (condition&G_IO_HUP){
			g_warning(N_("Hangup on connection for %s, GGid: %i"),s->jid,s->ggs->uin);
			return session_error(s);
		}
		if (condition&G_IO_NVAL) g_warning(N_("Invalid channel on connection for %s"),s->jid);

		session_broken(s);
		return FALSE;
	}

	debug(L_("watching fd (gg_debug_level=%i)..."),gg_debug_level);
	event=gg_watch_fd(s->ggs);
	if (!event){
		g_warning(N_("Connection broken. Session of %s, GGid: %i"),s->jid,s->ggs->uin);
		return session_error(s);
	}

	switch(event->type){
		case GG_EVENT_DISCONNECT:
			g_warning(N_("Server closed connection of %s, GGid: %i"),s->jid,s->ggs->uin);
			session_error(s);
			gg_event_free(event);
			return FALSE;
		case GG_EVENT_CONN_FAILED:
			g_message(N_("Login failed (%d:%s) for %s, GGid: %i"),
					event->event.failure,
					(event->event.failure>GG_FAILURE_NUM_REASONS||event->event.failure<1)?"-UNKNOWN-":gg_failure_reason[event->event.failure-1],
					s->jid,
					s->ggs->uin);
			if (s->req_id)
				jabber_iq_send_error(s->s,s->jid,NULL,s->req_id,401,_("Unauthorized"));
			else {
				str=g_strdup(from_utf8(gg_failure_reason_txt[event->event.failure-1]));
				presence_send(s->s,NULL,s->user->jid,0,NULL,str,0);
				g_free(str);
			}
			state = FALSE;
			if (!s->req_id)
				switch(event->event.failure){
					case GG_FAILURE_RESOLVING:
					case GG_FAILURE_CONNECTING:
					case GG_FAILURE_INVALID:
					case GG_FAILURE_READING:
					case GG_FAILURE_WRITING:
					case GG_FAILURE_TLS:
						state = session_try_next(s);
					default:
						break;
				}
			if (state) {
				s->connected=0;
				session_schedule_reconnect(s);
			} else
				session_remove(s);
			gg_event_free(event);
			return FALSE;
		case GG_EVENT_CONN_SUCCESS:
			g_message(L_("Login succeed for %s, GGid: %i"),s->jid,s->ggs->uin);
			if (s->req_id)
				jabber_iq_send_result(s->s,s->jid,NULL,s->req_id,NULL);
			if (s->req_id){
				g_free(s->req_id);
				s->req_id=NULL;
			}
			if (s->query){
				xmlnode_free(s->query);
				s->query=NULL;
			}
			if (!s->user->confirmed){
				s->user->confirmed=1;
				user_save(s->user);
			}
			s->connected=1;
			session_send_status(s);
			session_send_notify(s);
			presence_send(s->s,NULL,s->user->jid,s->user->invisible?-1:1,NULL,s->gg_status_descr,0);

			if (s->timeout_func) g_source_remove(s->timeout_func);
			s->timeout_func=NULL;
			if (s->ping_timeout_func) g_source_remove(s->ping_timeout_func);
			s->ping_timeout_func=g_timeout_add(ping_interval*1000,session_ping,s);
			if (s->pubdir_change){
				add_request(RT_CHANGE,s->jid,NULL,s->req_id,
							NULL,s->pubdir_change,s->s);
				gg_pubdir50_free(s->pubdir_change);
				s->pubdir_change=NULL;
			}
			if (s->get_roster){
				gg_userlist_request(s->ggs, GG_USERLIST_GET, NULL);
			}
			break;
		case GG_EVENT_NOTIFY:
			session_event_notify(s,event);
			break;
		case GG_EVENT_NOTIFY_DESCR:
			session_event_notify_descr(s,event);
			break;
		case GG_EVENT_NOTIFY60:
			session_event_notify60(s,event);
			break;
		case GG_EVENT_STATUS:
			session_event_status(s,
					event->event.status.status,
					event->event.status.uin,
					event->event.status.descr,
					0,0,0,0);
			break;
		case GG_EVENT_STATUS60:
			session_event_status(s,
					event->event.status60.status,
					event->event.status60.uin,
					event->event.status60.descr,
					1,
					event->event.status60.remote_ip,
					event->event.status60.remote_port,
					event->event.status60.version);
			break;
		case GG_EVENT_MSG:
			if (event->event.msg.recipients_count>1){
				debug(L_("Dropped conference message: sender: %i class: %i time: %lu"),
							event->event.msg.sender,
							event->event.msg.msgclass,
							(unsigned long)event->event.msg.time);
				break;
			}
			gg_messages_in++;
			debug(L_("Message: sender: %i class: %i time: %lu"),
							event->event.msg.sender,
							event->event.msg.msgclass,
							(unsigned long)event->event.msg.time);
			
			if (event->event.msg.sender==0){
				if (!user_sys_msg_received(s->user,event->event.msg.msgclass)) break;
				if (ignore_system_messages == ISM_IGNORE_ALL) break;
				if (ignore_system_messages == ISM_IGNORE_HTML
					&& strstr((const char *)event->event.msg.message, "<HTML>")) break;
				timestamp=event->event.msg.time;
				str=g_strdup_printf(_("GG System message #%i"),
							event->event.msg.msgclass);
				message_send_subject(s->s,jid, s->user->jid, str,
						string_from_gg((const char *)event->event.msg.message),
												timestamp);
				g_free(str);
				break;
			}
			else{
				Contact *c=user_get_contact(s->user,
						event->event.msg.sender,0);
				if ((!c && s->user->ignore_unknown) 
				    || (c && c->ignored)) {
					debug(L_("Ignoring the message."));
			       		break;
				}
				jid=jid_build_full(event->event.msg.sender);
				if ((event->event.msg.msgclass&GG_CLASS_CHAT)!=0) chat=1;
				else chat=0;
			}
			if ((event->event.msg.msgclass&GG_CLASS_QUEUED)!=0){
				timestamp=event->event.msg.time;
			}
			else timestamp=0;
			if(event->event.msg.formats_length>0)
				message_send_rich(s->s,jid,s->user->jid,chat,
						(char *)event->event.msg.message,timestamp,
						event->event.msg.formats_length,(void *)event->event.msg.formats);
			else
				message_send(s->s,jid,s->user->jid,chat,
						string_from_gg((const char *)event->event.msg.message),timestamp);
			g_free(jid);
			break;
		case GG_EVENT_PONG:
			s->waiting_for_pong=FALSE;
			if (s->ping_timer){
				g_timer_stop(s->ping_timer);
				debug(L_("Pong! ping time: %fs"),
						g_timer_elapsed(s->ping_timer,NULL));
			}
			if (s->timeout_func) g_source_remove(s->timeout_func);
			s->timeout_func=NULL;
			break;
		case GG_EVENT_PUBDIR50_SEARCH_REPLY:
			request_response_search(event);
			break;
		case GG_EVENT_PUBDIR50_WRITE:
			request_response_write(event);
			break;
		case GG_EVENT_ACK:
			debug("GG_EVENT_ACK");
			break;
		case GG_EVENT_NONE:
			debug("GG_EVENT_NONE");
			break;
		case GG_EVENT_USERLIST:
			if(event->event.userlist.type==GG_USERLIST_GET_REPLY)
				get_roster_done(s,event);
			else
				g_warning(N_("Wrong gg userlist type: %i"),event->event.userlist.type);
			break;
		default:
			g_warning(N_("Unknown GG event: %i"),event->type);
			break;
	}

	session_setup_g_source(s);

	gg_event_free(event);
	debug(L_("io handler done..."));

	return FALSE;
}
示例#12
0
void session_print(Session *s,int indent){
char *space,*space1;
GList *it;
Resource *r,*cr;
char *njid;

	space=g_strnfill(indent*2,' ');
	space1=g_strnfill((indent+1)*2,' ');
	njid=jid_normalized(s->jid,0);
	g_message(L_("%sSession: %p"),space,s);
	g_message("%sJID: %s",space,s->jid);
	g_message(L_("%sUser:"******"%sResources:"),space);
	cr=session_get_cur_resource(s);
	for(it=g_list_first(s->resources);it;it=g_list_next(it)){
		r=(Resource *)it->data;
		g_message(L_("%sResource: %p%s"),space1,r,(r==cr)?N_(" (current)"):"");
		if (njid && r->name) g_message("%sJID: %s/%s",space1,njid,r->name);
		else g_message("%sJID: %s",space1,s->jid);
		g_message(L_("%sPriority: %i"),space1,r->priority);
		g_message(L_("%sAvailable: %i"),space1,r->available);
		if (r->show)
			g_message(L_("%sShow: %s"),space1,r->show);
		if (r->status)
			g_message(L_("%sStatus: %s"),space1,r->status);
	}
	g_message(L_("%sGG session: %p"),space,s->ggs);
	g_message(L_("%sGSource: %p"),space,s->g_source);
	g_message(L_("%sStream: %p"),space,s->s);
	g_message(L_("%sConnected: %i"),space,s->connected);
	g_message(L_("%sRequest id: %s"),space,s->req_id?s->req_id:"(null)");
	g_message(L_("%sRequest query: %s"),space,s->query?xmlnode2str(s->query):"(null)");
	g_message(L_("%sWaiting for ping: %i"),space,(int)s->waiting_for_pong);
	g_free(njid);
	g_free(space1);
	g_free(space);
}
示例#13
0
DOUBLE
FUNC (DOUBLE x, int *expptr)
{
  int exponent;
  DECL_ROUNDING

  BEGIN_ROUNDING ();

#ifdef USE_FREXP_LDEXP
  /* frexp and ldexp are usually faster than the loop below.  */
  x = FREXP (x, &exponent);

  x = x + x;
  exponent -= 1;

  if (exponent < MIN_EXP - 1)
    {
      x = LDEXP (x, exponent - (MIN_EXP - 1));
      exponent = MIN_EXP - 1;
    }
#else
  {
    /* Since the exponent is an 'int', it fits in 64 bits.  Therefore the
       loops are executed no more than 64 times.  */
    DOUBLE pow2[64]; /* pow2[i] = 2^2^i */
    DOUBLE powh[64]; /* powh[i] = 2^-2^i */
    int i;

    exponent = 0;
    if (x >= L_(1.0))
      {
        /* A nonnegative exponent.  */
        {
          DOUBLE pow2_i; /* = pow2[i] */
          DOUBLE powh_i; /* = powh[i] */

          /* Invariants: pow2_i = 2^2^i, powh_i = 2^-2^i,
             x * 2^exponent = argument, x >= 1.0.  */
          for (i = 0, pow2_i = L_(2.0), powh_i = L_(0.5);
               ;
               i++, pow2_i = pow2_i * pow2_i, powh_i = powh_i * powh_i)
            {
              if (x >= pow2_i)
                {
                  exponent += (1 << i);
                  x *= powh_i;
                }
              else
                break;

              pow2[i] = pow2_i;
              powh[i] = powh_i;
            }
        }
        /* Here 1.0 <= x < 2^2^i.  */
      }
    else
      {
        /* A negative exponent.  */
        {
          DOUBLE pow2_i; /* = pow2[i] */
          DOUBLE powh_i; /* = powh[i] */

          /* Invariants: pow2_i = 2^2^i, powh_i = 2^-2^i,
             x * 2^exponent = argument, x < 1.0, exponent >= MIN_EXP - 1.  */
          for (i = 0, pow2_i = L_(2.0), powh_i = L_(0.5);
               ;
               i++, pow2_i = pow2_i * pow2_i, powh_i = powh_i * powh_i)
            {
              if (exponent - (1 << i) < MIN_EXP - 1)
                break;

              exponent -= (1 << i);
              x *= pow2_i;
              if (x >= L_(1.0))
                break;

              pow2[i] = pow2_i;
              powh[i] = powh_i;
            }
        }
        /* Here either x < 1.0 and exponent - 2^i < MIN_EXP - 1 <= exponent,
           or 1.0 <= x < 2^2^i and exponent >= MIN_EXP - 1.  */

        if (x < L_(1.0))
          /* Invariants: x * 2^exponent = argument, x < 1.0 and
             exponent - 2^i < MIN_EXP - 1 <= exponent.  */
          while (i > 0)
            {
              i--;
              if (exponent - (1 << i) >= MIN_EXP - 1)
                {
                  exponent -= (1 << i);
                  x *= pow2[i];
                  if (x >= L_(1.0))
                    break;
                }
            }

        /* Here either x < 1.0 and exponent = MIN_EXP - 1,
           or 1.0 <= x < 2^2^i and exponent >= MIN_EXP - 1.  */
      }

    /* Invariants: x * 2^exponent = argument, and
       either x < 1.0 and exponent = MIN_EXP - 1,
       or 1.0 <= x < 2^2^i and exponent >= MIN_EXP - 1.  */
    while (i > 0)
      {
        i--;
        if (x >= pow2[i])
          {
            exponent += (1 << i);
            x *= powh[i];
          }
      }
    /* Here either x < 1.0 and exponent = MIN_EXP - 1,
       or 1.0 <= x < 2.0 and exponent >= MIN_EXP - 1.  */
  }
#endif

  END_ROUNDING ();

  *expptr = exponent;
  return x;
}
示例#14
0
 const std::string Variant::title() const
 {
     if (package() != STROMX_RUNTIME_PACKAGE_NAME)
         return "";
     
     switch(id())
     {
     case NONE_ID:
         return  L_("None");
     case DATA_ID:
         return  L_("Data");
     case TRIGGER_ID:
         return  L_("Trigger");
     case PRIMITIVE_ID:
         return  L_("Primitive");
     case BOOL_ID:
         return  L_("Bool");
     case TRIBOOL_ID:
         return  L_("Tribool");
     case ENUM_ID:
         return  L_("Enum");
     case INT_ID:
         return  L_("Int");
     case UINT_ID:
         return  L_("UInt");
     case INT_8_ID:
         return  L_("Int8");
     case UINT_8_ID:
         return  L_("UInt8");
     case INT_16_ID:
         return  L_("Int16");
     case UINT_16_ID:
         return  L_("UInt16");
     case INT_32_ID:
         return  L_("Int32");
     case UINT_32_ID:
         return  L_("UInt32");
     case INT_64_ID:
         return  L_("Int64");
     case UINT_64_ID:
         return  L_("UInt64");
     case FLOAT_ID:
         return  L_("Float");
     case FLOAT_32_ID:
         return  L_("Float32");
     case FLOAT_64_ID:
         return  L_("Float64");
     case LIST_ID:
         return  L_("List");
     case MATRIX_ID:
         return  L_("Matrix");
     case INT_MATRIX_ID:
         return  L_("Int matrix");
     case UINT_MATRIX_ID:
         return  L_("UInt matrix");
     case INT_8_MATRIX_ID:
         return  L_("Int8 matrix");
     case UINT_8_MATRIX_ID:
         return  L_("UInt8 matrix");
     case INT_16_MATRIX_ID:
         return  L_("Int16 matrix");
     case UINT_16_MATRIX_ID:
         return  L_("UInt16 matrix");
     case INT_32_MATRIX_ID:
         return  L_("Int32 matrix");
     case UINT_32_MATRIX_ID:
         return  L_("UInt32 matrix");
     case FLOAT_MATRIX_ID:
         return  L_("Float matrix");
     case FLOAT_32_MATRIX_ID:
         return  L_("Float32 matrix");
     case FLOAT_64_MATRIX_ID:
         return  L_("Float64 matrix");
     case STRING_ID:
         return  L_("String");
     case IMAGE_ID:
         return  L_("Image");
     case MONO_IMAGE_ID:
         return  L_("Mono image");
     case RGB_IMAGE_ID:
         return  L_("RGB image");
     case MONO_8_IMAGE_ID:
         return  L_("Mono image 8-bit");
     case RGB_24_IMAGE_ID:
         return  L_("RGB image 24-bit");
     case BGR_24_IMAGE_ID:
         return  L_("BGR image 24-bit");
     case BAYERBG_8_IMAGE_ID:
         return  L_("Bayer BG image 8-bit");
     case BAYERGB_8_IMAGE_ID:
         return  L_("Bayer GB image 8-bit");
     case BAYERBG_16_IMAGE_ID:
         return  L_("Bayer BG image 16-bit");
     case BAYERGB_16_IMAGE_ID:
         return  L_("Bayer GB image 16-bit");
     case MONO_16_IMAGE_ID:
         return  L_("Mono image 16-bit");
     case RGB_48_IMAGE_ID:
         return  L_("RGB image 48-bit");
     case BGR_48_IMAGE_ID:
         return  L_("BGR image 48-bit");
     case FILE_ID:
         return  L_("File");
     case BINARY_FILE_ID:
         return  L_("Binary file");
     case TEXT_FILE_ID:
         return  L_("Text file");
     default:
         return "";
     }
 }
示例#15
0
文件: stream.c 项目: Jajcus/jggtrans
Stream *stream_connect(char *host,int port,int nonblock,xstream_onNode cb){
Stream *s;
struct hostent *he;
int optval;
int r;
int fd;

	s=g_new0(Stream,1);
	fd=socket(PF_INET,SOCK_STREAM,0);
	if (!fd){
		error_exit(L_("socket: %s"),g_strerror(errno));
		g_free(s);
		return NULL;
	}
	s->ioch=g_io_channel_unix_new(fd);
	g_io_channel_set_encoding(s->ioch,NULL,NULL);
	g_io_channel_set_buffered(s->ioch,0);
	s->sa.sin_family=AF_INET;
	s->sa.sin_port=htons(port);
	he=gethostbyname(host);
	if (he == NULL){
		g_warning(N_("Unknown host: %s"),host);
		g_free(s);
		return NULL;
	}
	s->sa.sin_addr = *(struct in_addr *) he->h_addr;
	optval=1;
	r=setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(optval));
	if (r<0){
		g_warning("setsockopt(fd,SOL_SOCKET,SO_REUSEADDR...): %s",g_strerror(errno));
		g_free(s);
		return NULL;
	}

	optval=1;
	r=setsockopt(fd,SOL_SOCKET,SO_KEEPALIVE,&optval,sizeof(optval));
	if (r<0){
		g_warning("setsockopt(fd,SOL_SOCKET,SO_KEEPALIVE...): %s",g_strerror(errno));
		g_free(s);
		return NULL;
	}

	if (nonblock)
		if (stream_set_nonblocking(s,1)){
			g_free(s);
			return NULL;
		}

	r=connect(fd, (struct sockaddr *) &s->sa, sizeof (s->sa));
	if (r<0 && nonblock && errno==EINPROGRESS){
		s->connecting=1;
	}
	else{
		if (r<0){
			error_exit(L_("connect: %s"),g_strerror(errno));
			g_free(s);
			return NULL;
		}
		s->connected=1;
	}
	s->dest=g_strdup(host); /* FIXME */
	s->err_watch=g_io_add_watch(s->ioch,G_IO_ERR|G_IO_HUP|G_IO_NVAL,stream_io_error,s);
	if (s->connecting)
		s->write_watch=g_io_add_watch(s->ioch,G_IO_OUT,stream_io_connect,s);
	else
		s->read_watch=g_io_add_watch(s->ioch,G_IO_IN,stream_io_read,s);
	s->xs=xstream_new(pool_new(),cb,s);
	if (s->connected) stream_write_hello(s);
	return s;
}
DOUBLE
FMOD (DOUBLE x, DOUBLE y)
{
  if (isfinite (x) && isfinite (y) && y != L_(0.0))
    {
      if (x == L_(0.0))
        /* Return x, regardless of the sign of y.  */
        return x;

      {
        int negate = ((!signbit (x)) ^ (!signbit (y)));

        /* Take the absolute value of x and y.  */
        x = FABS (x);
        y = FABS (y);

        /* Trivial case that requires no computation.  */
        if (x < y)
          return (negate ? - x : x);

        {
          int yexp;
          DOUBLE ym;
          DOUBLE y1;
          DOUBLE y0;
          int k;
          DOUBLE x2;
          DOUBLE x1;
          DOUBLE x0;

          /* Write y = 2^yexp * (y1 * 2^-LIMB_BITS + y0 * 2^-(2*LIMB_BITS))
             where y1 is an integer, 2^(LIMB_BITS-1) <= y1 < 2^LIMB_BITS,
             y1 has at most LIMB_BITS bits,
             0 <= y0 < 2^LIMB_BITS,
             y0 has at most (MANT_DIG + 1) / 2 bits.  */
          ym = FREXP (y, &yexp);
          ym = ym * TWO_LIMB_BITS;
          y1 = TRUNC (ym);
          y0 = (ym - y1) * TWO_LIMB_BITS;

          /* Write
               x = 2^(yexp+(k-3)*LIMB_BITS)
                   * (x2 * 2^(2*LIMB_BITS) + x1 * 2^LIMB_BITS + x0)
             where x2, x1, x0 are each integers >= 0, < 2^LIMB_BITS.  */
          {
            int xexp;
            DOUBLE xm = FREXP (x, &xexp);
            /* Since we know x >= y, we know xexp >= yexp.  */
            xexp -= yexp;
            /* Compute k = ceil(xexp / LIMB_BITS).  */
            k = (xexp + LIMB_BITS - 1) / LIMB_BITS;
            /* Note: (k - 1) * LIMB_BITS + 1 <= xexp <= k * LIMB_BITS.  */
            /* Note: 0.5 <= xm < 1.0.  */
            xm = LDEXP (xm, xexp - (k - 1) * LIMB_BITS);
            /* Note: Now xm < 2^(xexp - (k - 1) * LIMB_BITS) <= 2^LIMB_BITS
               and xm >= 0.5 * 2^(xexp - (k - 1) * LIMB_BITS) >= 1.0
               and xm has at most MANT_DIG <= 2*LIMB_BITS+1 bits.  */
            x2 = TRUNC (xm);
            x1 = (xm - x2) * TWO_LIMB_BITS;
            /* Split off x0 from x1 later.  */
          }

          /* Test whether [x2,x1,0] >= 2^LIMB_BITS * [y1,y0].  */
          if (x2 > y1 || (x2 == y1 && x1 >= y0))
            {
              /* Subtract 2^LIMB_BITS * [y1,y0] from [x2,x1,0].  */
              x2 -= y1;
              x1 -= y0;
              if (x1 < L_(0.0))
                {
                  if (!(x2 >= L_(1.0)))
                    abort ();
                  x2 -= L_(1.0);
                  x1 += TWO_LIMB_BITS;
                }
            }

          /* Split off x0 from x1.  */
          {
            DOUBLE x1int = TRUNC (x1);
            x0 = TRUNC ((x1 - x1int) * TWO_LIMB_BITS);
            x1 = x1int;
          }

          for (; k > 0; k--)
            {
              /* Multiprecision division of the limb sequence [x2,x1,x0]
                 by [y1,y0].  */
              /* Here [x2,x1,x0] < 2^LIMB_BITS * [y1,y0].  */
              /* The first guess takes into account only [x2,x1] and [y1].

                 By Knuth's theorem, we know that
                   q* = min (floor ([x2,x1] / [y1]), 2^LIMB_BITS - 1)
                 and
                   q = floor ([x2,x1,x0] / [y1,y0])
                 are not far away:
                   q* - 2 <= q <= q* + 1.

                 Proof:
                 a) q* * y1 <= floor ([x2,x1] / [y1]) * y1 <= [x2,x1].
                    Hence
                    [x2,x1,x0] - q* * [y1,y0]
                      = 2^LIMB_BITS * ([x2,x1] - q* * [y1]) + x0 - q* * y0
                      >= x0 - q* * y0
                      >= - q* * y0
                      > - 2^(2*LIMB_BITS)
                      >= - 2 * [y1,y0]
                    So
                      [x2,x1,x0] > (q* - 2) * [y1,y0].
                 b) If q* = floor ([x2,x1] / [y1]), then
                      [x2,x1] < (q* + 1) * y1
                    Hence
                    [x2,x1,x0] - q* * [y1,y0]
                      = 2^LIMB_BITS * ([x2,x1] - q* * [y1]) + x0 - q* * y0
                      <= 2^LIMB_BITS * (y1 - 1) + x0 - q* * y0
                      <= 2^LIMB_BITS * (2^LIMB_BITS-2) + (2^LIMB_BITS-1) - 0
                      < 2^(2*LIMB_BITS)
                      <= 2 * [y1,y0]
                    So
                      [x2,x1,x0] < (q* + 2) * [y1,y0].
                    and so
                      q < q* + 2
                    which implies
                      q <= q* + 1.
                    In the other case, q* = 2^LIMB_BITS - 1.  Then trivially
                      q < 2^LIMB_BITS = q* + 1.

                 We know that floor ([x2,x1] / [y1]) >= 2^LIMB_BITS if and
                 only if x2 >= y1.  */
              DOUBLE q =
                (x2 >= y1
                 ? TWO_LIMB_BITS - L_(1.0)
                 : TRUNC ((x2 * TWO_LIMB_BITS + x1) / y1));
              if (q > L_(0.0))
                {
                  /* Compute
                     [x2,x1,x0] - q* * [y1,y0]
                       = 2^LIMB_BITS * ([x2,x1] - q* * [y1]) + x0 - q* * y0.  */
                  DOUBLE q_y1 = q * y1; /* exact, at most 2*LIMB_BITS bits */
                  DOUBLE q_y1_1 = TRUNC (q_y1 * TWO_LIMB_BITS_INVERSE);
                  DOUBLE q_y1_0 = q_y1 - q_y1_1 * TWO_LIMB_BITS;
                  DOUBLE q_y0 = q * y0; /* exact, at most MANT_DIG bits */
                  DOUBLE q_y0_1 = TRUNC (q_y0 * TWO_LIMB_BITS_INVERSE);
                  DOUBLE q_y0_0 = q_y0 - q_y0_1 * TWO_LIMB_BITS;
                  x2 -= q_y1_1;
                  x1 -= q_y1_0;
                  x1 -= q_y0_1;
                  x0 -= q_y0_0;
                  /* Move negative carry from x0 to x1 and from x1 to x2.  */
                  if (x0 < L_(0.0))
                    {
                      x0 += TWO_LIMB_BITS;
                      x1 -= L_(1.0);
                    }
                  if (x1 < L_(0.0))
                    {
                      x1 += TWO_LIMB_BITS;
                      x2 -= L_(1.0);
                      if (x1 < L_(0.0)) /* not sure this can happen */
                        {
                          x1 += TWO_LIMB_BITS;
                          x2 -= L_(1.0);
                        }
                    }
                  if (x2 < L_(0.0))
                    {
                      /* Reduce q by 1.  */
                      x1 += y1;
                      x0 += y0;
                      /* Move overflow from x0 to x1 and from x1 to x0.  */
                      if (x0 >= TWO_LIMB_BITS)
                        {
                          x0 -= TWO_LIMB_BITS;
                          x1 += L_(1.0);
                        }
                      if (x1 >= TWO_LIMB_BITS)
                        {
                          x1 -= TWO_LIMB_BITS;
                          x2 += L_(1.0);
                        }
                      if (x2 < L_(0.0))
                        {
                          /* Reduce q by 1 again.  */
                          x1 += y1;
                          x0 += y0;
                          /* Move overflow from x0 to x1 and from x1 to x0.  */
                          if (x0 >= TWO_LIMB_BITS)
                            {
                              x0 -= TWO_LIMB_BITS;
                              x1 += L_(1.0);
                            }
                          if (x1 >= TWO_LIMB_BITS)
                            {
                              x1 -= TWO_LIMB_BITS;
                              x2 += L_(1.0);
                            }
                          if (x2 < L_(0.0))
                            /* Shouldn't happen, because we proved that
                               q >= q* - 2.  */
                            abort ();
                        }
                    }
                }
              if (x2 > L_(0.0)
                  || x1 > y1
                  || (x1 == y1 && x0 >= y0))
                {
                  /* Increase q by 1.  */
                  x1 -= y1;
                  x0 -= y0;
                  /* Move negative carry from x0 to x1 and from x1 to x2.  */
                  if (x0 < L_(0.0))
                    {
                      x0 += TWO_LIMB_BITS;
                      x1 -= L_(1.0);
                    }
                  if (x1 < L_(0.0))
                    {
                      x1 += TWO_LIMB_BITS;
                      x2 -= L_(1.0);
                    }
                  if (x2 < L_(0.0))
                    abort ();
                  if (x2 > L_(0.0)
                      || x1 > y1
                      || (x1 == y1 && x0 >= y0))
                    /* Shouldn't happen, because we proved that
                       q <= q* + 1.  */
                    abort ();
                }
              /* Here [x2,x1,x0] < [y1,y0].  */
              /* Next round.  */
              x2 = x1;
#if (MANT_DIG + 1) / 2 > LIMB_BITS /* y0 can have a fractional bit */
              x1 = TRUNC (x0);
              x0 = (x0 - x1) * TWO_LIMB_BITS;
#else
              x1 = x0;
              x0 = L_(0.0);
#endif
              /* Here [x2,x1,x0] < 2^LIMB_BITS * [y1,y0].  */
            }
          /* Here k = 0.
             The result is
               2^(yexp-3*LIMB_BITS)
               * (x2 * 2^(2*LIMB_BITS) + x1 * 2^LIMB_BITS + x0).  */
          {
            DOUBLE r =
              LDEXP ((x2 * TWO_LIMB_BITS + x1) * TWO_LIMB_BITS + x0,
                     yexp - 3 * LIMB_BITS);
            return (negate ? - r : r);
          }
        }
      }
    }
  else
    {
      if (ISNAN (x) || ISNAN (y))
        return x + y; /* NaN */
      else if (isinf (y))
        return x;
      else
        /* x infinite or y zero */
        return NAN;
    }
}
示例#17
0
int user_save(User *u){
FILE *f;
char *fn;
char *str;
char *njid;
int r;
xmlnode xml,tag,ctag,userlist;

	g_assert(u!=NULL);
	str=strchr(u->jid,'/');
	g_assert(str==NULL);

	if (!u->confirmed){
		g_message(L_("Not saving user '%s' - account not confirmed."),u->jid);
		return -1;
	}

	g_debug(L_("Saving user '%s'"),u->jid);
	njid=jid_normalized(u->jid,0);
	g_assert(njid!=NULL);
	fn=g_strdup_printf("%s.new",njid);
	f=fopen(fn,"w");
	if (!f){
		g_warning(L_("Couldn't open '%s': %s"),fn,g_strerror(errno));
		g_free(fn);
		g_free(njid);
		return -1;
	}
	xml=xmlnode_new_tag("user");
	tag=xmlnode_insert_tag(xml,"version");
	str=g_strdup_printf("%08x",USER_FILE_FORMAT_VERSION);
	xmlnode_put_attrib(tag,"file_format",str);
	g_free(str);
	tag=xmlnode_insert_tag(xml,"jid");
	xmlnode_insert_cdata(tag,u->jid,-1);
	set_subscribe(tag, u->subscribe);
	tag=xmlnode_insert_tag(xml,"uin");
	str=g_strdup_printf("%lu",(unsigned long)u->uin);
	xmlnode_insert_cdata(tag,str,-1);
	g_free(str);
	tag=xmlnode_insert_tag(xml,"password");
	xmlnode_insert_cdata(tag,u->password,-1);

	if (u->last_sys_msg>0){
		tag=xmlnode_insert_tag(xml,"last_sys_msg");
		str=g_strdup_printf("%i",u->last_sys_msg);
		xmlnode_insert_cdata(tag,str,-1);
		g_free(str);
	}

	if (u->invisible) tag=xmlnode_insert_tag(xml,"invisible");
	if (u->friends_only) tag=xmlnode_insert_tag(xml,"friendsonly");
	if (u->ignore_unknown) tag=xmlnode_insert_tag(xml,"ignore_unknown");
	if (u->locale){
		tag=xmlnode_insert_tag(xml,"locale");
		xmlnode_insert_cdata(tag,u->locale,-1);
	}
	if (u->status){
		tag=xmlnode_insert_tag(xml,"status");
		xmlnode_insert_cdata(tag,to_utf8(u->status),-1);
	}

	if (u->contacts){
		GList *it;
		Contact *c;

		userlist=xmlnode_insert_tag(xml,"userlist");
		for(it=g_list_first(u->contacts);it;it=it->next){
			c=(Contact *)it->data;
			ctag=xmlnode_insert_tag(userlist,"contact");
			str=g_strdup_printf("%lu",(unsigned long)c->uin);
			xmlnode_put_attrib(ctag,"uin",str);
			if (c->ignored) xmlnode_put_attrib(ctag,"ignored","ignored");
			if (c->blocked) xmlnode_put_attrib(ctag,"blocked","blocked");
			set_subscribe(ctag, c->subscribe);
			g_free(str);
		}
	}

	str=xmlnode2str(xml);
	r=fputs(str,f);
	if (r<0){
		g_warning(L_("Couldn't save '%s': %s"),u->jid,g_strerror(errno));
		fclose(f);
		unlink(fn);
		xmlnode_free(xml);
		g_free(fn);
		g_free(njid);
		return -1;
	}
	fclose(f);
	r=unlink(njid);
	if (r && errno!=ENOENT){
		g_warning(L_("Couldn't unlink '%s': %s"),njid,g_strerror(errno));
		xmlnode_free(xml);
		g_free(fn);
		g_free(njid);
		return -1;
	}

	r=rename(fn,njid);
	if (r){
		g_warning(L_("Couldn't rename '%s' to '%s': %s"),fn,u->jid,g_strerror(errno));
		xmlnode_free(xml);
		g_free(fn);
		g_free(njid);
		return -1;
	}

	xmlnode_free(xml);
	g_free(fn);
	g_free(njid);
	return 0;
}
示例#18
0
static int
internal_function
FCT (const CHAR *pattern, const CHAR *string, const CHAR *string_end,
     bool no_leading_period, int flags)
{
  register const CHAR *p = pattern, *n = string;
  register UCHAR c;
#ifdef _LIBC
# if WIDE_CHAR_VERSION
  const char *collseq = (const char *)
    _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
# else
  const UCHAR *collseq = (const UCHAR *)
    _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQMB);
# endif
#endif

  while ((c = *p++) != L_('\0'))
    {
      bool new_no_leading_period = false;
      c = FOLD (c);

      switch (c)
	{
	case L_('?'):
	  if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
	    {
	      int res;

	      res = EXT (c, p, n, string_end, no_leading_period,
			 flags);
	      if (res != -1)
		return res;
	    }

	  if (n == string_end)
	    return FNM_NOMATCH;
	  else if (*n == L_('/') && (flags & FNM_FILE_NAME))
	    return FNM_NOMATCH;
	  else if (*n == L_('.') && no_leading_period)
	    return FNM_NOMATCH;
	  break;

	case L_('\\'):
	  if (!(flags & FNM_NOESCAPE))
	    {
	      c = *p++;
	      if (c == L_('\0'))
		/* Trailing \ loses.  */
		return FNM_NOMATCH;
	      c = FOLD (c);
	    }
	  if (n == string_end || FOLD ((UCHAR) *n) != c)
	    return FNM_NOMATCH;
	  break;

	case L_('*'):
	  if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
	    {
	      int res;

	      res = EXT (c, p, n, string_end, no_leading_period,
			 flags);
	      if (res != -1)
		return res;
	    }

	  if (n != string_end && *n == L_('.') && no_leading_period)
	    return FNM_NOMATCH;

	  for (c = *p++; c == L_('?') || c == L_('*'); c = *p++)
	    {
	      if (*p == L_('(') && (flags & FNM_EXTMATCH) != 0)
		{
		  const CHAR *endp = END (p);
		  if (endp != p)
		    {
		      /* This is a pattern.  Skip over it.  */
		      p = endp;
		      continue;
		    }
		}

	      if (c == L_('?'))
		{
		  /* A ? needs to match one character.  */
		  if (n == string_end)
		    /* There isn't another character; no match.  */
		    return FNM_NOMATCH;
		  else if (*n == L_('/')
			   && __builtin_expect (flags & FNM_FILE_NAME, 0))
		    /* A slash does not match a wildcard under
		       FNM_FILE_NAME.  */
		    return FNM_NOMATCH;
		  else
		    /* One character of the string is consumed in matching
		       this ? wildcard, so *??? won't match if there are
		       less than three characters.  */
		    ++n;
		}
	    }

	  if (c == L_('\0'))
	    /* The wildcard(s) is/are the last element of the pattern.
	       If the name is a file name and contains another slash
	       this means it cannot match, unless the FNM_LEADING_DIR
	       flag is set.  */
	    {
	      int result = (flags & FNM_FILE_NAME) == 0 ? 0 : FNM_NOMATCH;

	      if (flags & FNM_FILE_NAME)
		{
		  if (flags & FNM_LEADING_DIR)
		    result = 0;
		  else
		    {
		      if (MEMCHR (n, L_('/'), string_end - n) == NULL)
			result = 0;
		    }
		}

	      return result;
	    }
	  else
	    {
	      const CHAR *endp;

	      endp = MEMCHR (n, (flags & FNM_FILE_NAME) ? L_('/') : L_('\0'),
			     string_end - n);
	      if (endp == NULL)
		endp = string_end;

	      if (c == L_('[')
		  || (__builtin_expect (flags & FNM_EXTMATCH, 0) != 0
		      && (c == L_('@') || c == L_('+') || c == L_('!'))
		      && *p == L_('(')))
		{
		  int flags2 = ((flags & FNM_FILE_NAME)
				? flags : (flags & ~FNM_PERIOD));
		  bool no_leading_period2 = no_leading_period;

		  for (--p; n < endp; ++n, no_leading_period2 = false)
		    if (FCT (p, n, string_end, no_leading_period2, flags2)
			== 0)
		      return 0;
		}
	      else if (c == L_('/') && (flags & FNM_FILE_NAME))
		{
		  while (n < string_end && *n != L_('/'))
		    ++n;
		  if (n < string_end && *n == L_('/')
		      && (FCT (p, n + 1, string_end, flags & FNM_PERIOD, flags)
			  == 0))
		    return 0;
		}
	      else
		{
		  int flags2 = ((flags & FNM_FILE_NAME)
				? flags : (flags & ~FNM_PERIOD));
		  int no_leading_period2 = no_leading_period;

		  if (c == L_('\\') && !(flags & FNM_NOESCAPE))
		    c = *p;
		  c = FOLD (c);
		  for (--p; n < endp; ++n, no_leading_period2 = false)
		    if (FOLD ((UCHAR) *n) == c
			&& (FCT (p, n, string_end, no_leading_period2, flags2)
			    == 0))
		      return 0;
		}
	    }

	  /* If we come here no match is possible with the wildcard.  */
	  return FNM_NOMATCH;

	case L_('['):
	  {
	    /* Nonzero if the sense of the character class is inverted.  */
	    register bool not;
	    CHAR cold;
	    UCHAR fn;

	    if (posixly_correct == 0)
	      posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;

	    if (n == string_end)
	      return FNM_NOMATCH;

	    if (*n == L_('.') && no_leading_period)
	      return FNM_NOMATCH;

	    if (*n == L_('/') && (flags & FNM_FILE_NAME))
	      /* `/' cannot be matched.  */
	      return FNM_NOMATCH;

	    not = (*p == L_('!') || (posixly_correct < 0 && *p == L_('^')));
	    if (not)
	      ++p;

	    fn = FOLD ((UCHAR) *n);

	    c = *p++;
	    for (;;)
	      {
		if (!(flags & FNM_NOESCAPE) && c == L_('\\'))
		  {
		    if (*p == L_('\0'))
		      return FNM_NOMATCH;
		    c = FOLD ((UCHAR) *p);
		    ++p;

		    if (c == fn)
		      goto matched;
		  }
		else if (c == L_('[') && *p == L_(':'))
		  {
		    /* Leave room for the null.  */
		    CHAR str[CHAR_CLASS_MAX_LENGTH + 1];
		    size_t c1 = 0;
#if defined _LIBC || WIDE_CHAR_SUPPORT
		    wctype_t wt;
#endif
		    const CHAR *startp = p;

		    for (;;)
		      {
			if (c1 == CHAR_CLASS_MAX_LENGTH)
			  /* The name is too long and therefore the pattern
			     is ill-formed.  */
			  return FNM_NOMATCH;

			c = *++p;
			if (c == L_(':') && p[1] == L_(']'))
			  {
			    p += 2;
			    break;
			  }
			if (c < L_('a') || c >= L_('z'))
			  {
			    /* This cannot possibly be a character class name.
			       Match it as a normal range.  */
			    p = startp;
			    c = L_('[');
			    goto normal_bracket;
			  }
			str[c1++] = c;
		      }
		    str[c1] = L_('\0');

#if defined _LIBC || WIDE_CHAR_SUPPORT
		    wt = IS_CHAR_CLASS (str);
		    if (wt == 0)
		      /* Invalid character class name.  */
		      return FNM_NOMATCH;

# if defined _LIBC && ! WIDE_CHAR_VERSION
		    /* The following code is glibc specific but does
		       there a good job in speeding up the code since
		       we can avoid the btowc() call.  */
		    if (_ISCTYPE ((UCHAR) *n, wt))
		      goto matched;
# else
		    if (ISWCTYPE (BTOWC ((UCHAR) *n), wt))
		      goto matched;
# endif
#else
		    if ((STREQ (str, L_("alnum")) && ISALNUM ((UCHAR) *n))
			|| (STREQ (str, L_("alpha")) && ISALPHA ((UCHAR) *n))
			|| (STREQ (str, L_("blank")) && ISBLANK ((UCHAR) *n))
			|| (STREQ (str, L_("cntrl")) && ISCNTRL ((UCHAR) *n))
			|| (STREQ (str, L_("digit")) && ISDIGIT ((UCHAR) *n))
			|| (STREQ (str, L_("graph")) && ISGRAPH ((UCHAR) *n))
			|| (STREQ (str, L_("lower")) && ISLOWER ((UCHAR) *n))
			|| (STREQ (str, L_("print")) && ISPRINT ((UCHAR) *n))
			|| (STREQ (str, L_("punct")) && ISPUNCT ((UCHAR) *n))
			|| (STREQ (str, L_("space")) && ISSPACE ((UCHAR) *n))
			|| (STREQ (str, L_("upper")) && ISUPPER ((UCHAR) *n))
			|| (STREQ (str, L_("xdigit")) && ISXDIGIT ((UCHAR) *n)))
		      goto matched;
#endif
		    c = *p++;
		  }
#ifdef _LIBC
		else if (c == L_('[') && *p == L_('='))
		  {
		    UCHAR str[1];
		    uint32_t nrules =
		      _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
		    const CHAR *startp = p;

		    c = *++p;
		    if (c == L_('\0'))
		      {
			p = startp;
			c = L_('[');
			goto normal_bracket;
		      }
		    str[0] = c;

		    c = *++p;
		    if (c != L_('=') || p[1] != L_(']'))
		      {
			p = startp;
			c = L_('[');
			goto normal_bracket;
		      }
		    p += 2;

		    if (nrules == 0)
		      {
			if ((UCHAR) *n == str[0])
			  goto matched;
		      }
		    else
		      {
			const int32_t *table;
# if WIDE_CHAR_VERSION
			const int32_t *weights;
			const int32_t *extra;
# else
			const unsigned char *weights;
			const unsigned char *extra;
# endif
			const int32_t *indirect;
			int32_t idx;
			const UCHAR *cp = (const UCHAR *) str;

			/* This #include defines a local function!  */
# if WIDE_CHAR_VERSION
#  include <locale/weightwc.h>
# else
#  include <locale/weight.h>
# endif

# if WIDE_CHAR_VERSION
			table = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
			weights = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
			extra = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
			indirect = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
# else
			table = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
			weights = (const unsigned char *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
			extra = (const unsigned char *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
			indirect = (const int32_t *)
			  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
# endif

			idx = findidx (&cp);
			if (idx != 0)
			  {
			    /* We found a table entry.  Now see whether the
			       character we are currently at has the same
			       equivalance class value.  */
			    int len = weights[idx];
			    int32_t idx2;
			    const UCHAR *np = (const UCHAR *) n;

			    idx2 = findidx (&np);
			    if (idx2 != 0 && len == weights[idx2])
			      {
				int cnt = 0;

				while (cnt < len
				       && (weights[idx + 1 + cnt]
					   == weights[idx2 + 1 + cnt]))
				  ++cnt;

				if (cnt == len)
				  goto matched;
			      }
			  }
		      }

		    c = *p++;
		  }
#endif
		else if (c == L_('\0'))
		  /* [ (unterminated) loses.  */
		  return FNM_NOMATCH;
		else
		  {
		    bool is_range = false;

#ifdef _LIBC
		    bool is_seqval = false;

		    if (c == L_('[') && *p == L_('.'))
		      {
			uint32_t nrules =
			  _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
			const CHAR *startp = p;
			size_t c1 = 0;

			while (1)
			  {
			    c = *++p;
			    if (c == L_('.') && p[1] == L_(']'))
			      {
				p += 2;
				break;
			      }
			    if (c == '\0')
			      return FNM_NOMATCH;
			    ++c1;
			  }

			/* We have to handling the symbols differently in
			   ranges since then the collation sequence is
			   important.  */
			is_range = *p == L_('-') && p[1] != L_('\0');

			if (nrules == 0)
			  {
			    /* There are no names defined in the collation
			       data.  Therefore we only accept the trivial
			       names consisting of the character itself.  */
			    if (c1 != 1)
			      return FNM_NOMATCH;

			    if (!is_range && *n == startp[1])
			      goto matched;

			    cold = startp[1];
			    c = *p++;
			  }
			else
			  {
			    int32_t table_size;
			    const int32_t *symb_table;
# ifdef WIDE_CHAR_VERSION
			    char str[c1];
			    size_t strcnt;
# else
#  define str (startp + 1)
# endif
			    const unsigned char *extra;
			    int32_t idx;
			    int32_t elem;
			    int32_t second;
			    int32_t hash;

# ifdef WIDE_CHAR_VERSION
			    /* We have to convert the name to a single-byte
			       string.  This is possible since the names
			       consist of ASCII characters and the internal
			       representation is UCS4.  */
			    for (strcnt = 0; strcnt < c1; ++strcnt)
			      str[strcnt] = startp[1 + strcnt];
# endif

			    table_size =
			      _NL_CURRENT_WORD (LC_COLLATE,
						_NL_COLLATE_SYMB_HASH_SIZEMB);
			    symb_table = (const int32_t *)
			      _NL_CURRENT (LC_COLLATE,
					   _NL_COLLATE_SYMB_TABLEMB);
			    extra = (const unsigned char *)
			      _NL_CURRENT (LC_COLLATE,
					   _NL_COLLATE_SYMB_EXTRAMB);

			    /* Locate the character in the hashing table.  */
			    hash = elem_hash (str, c1);

			    idx = 0;
			    elem = hash % table_size;
			    second = hash % (table_size - 2);
			    while (symb_table[2 * elem] != 0)
			      {
				/* First compare the hashing value.  */
				if (symb_table[2 * elem] == hash
				    && c1 == extra[symb_table[2 * elem + 1]]
				    && memcmp (str,
					       &extra[symb_table[2 * elem + 1]
						     + 1], c1) == 0)
				  {
				    /* Yep, this is the entry.  */
				    idx = symb_table[2 * elem + 1];
				    idx += 1 + extra[idx];
				    break;
				  }

				/* Next entry.  */
				elem += second;
			      }

			    if (symb_table[2 * elem] != 0)
			      {
				/* Compare the byte sequence but only if
				   this is not part of a range.  */
# ifdef WIDE_CHAR_VERSION
				int32_t *wextra;

				idx += 1 + extra[idx];
				/* Adjust for the alignment.  */
				idx = (idx + 3) & ~3;

				wextra = (int32_t *) &extra[idx + 4];
# endif

				if (! is_range)
				  {
# ifdef WIDE_CHAR_VERSION
				    for (c1 = 0;
					 (int32_t) c1 < wextra[idx];
					 ++c1)
				      if (n[c1] != wextra[1 + c1])
					break;

				    if ((int32_t) c1 == wextra[idx])
				      goto matched;
# else
				    for (c1 = 0; c1 < extra[idx]; ++c1)
				      if (n[c1] != extra[1 + c1])
					break;

				    if (c1 == extra[idx])
				      goto matched;
# endif
				  }

				/* Get the collation sequence value.  */
				is_seqval = true;
# ifdef WIDE_CHAR_VERSION
				cold = wextra[1 + wextra[idx]];
# else
				/* Adjust for the alignment.  */
				idx += 1 + extra[idx];
				idx = (idx + 3) & ~4;
				cold = *((int32_t *) &extra[idx]);
# endif

				c = *p++;
			      }
			    else if (c1 == 1)
			      {
				/* No valid character.  Match it as a
				   single byte.  */
				if (!is_range && *n == str[0])
				  goto matched;

				cold = str[0];
				c = *p++;
			      }
			    else
			      return FNM_NOMATCH;
			  }
		      }
		    else
# undef str
#endif
		      {
			c = FOLD (c);
		      normal_bracket:

			/* We have to handling the symbols differently in
			   ranges since then the collation sequence is
			   important.  */
			is_range = (*p == L_('-') && p[1] != L_('\0')
				    && p[1] != L_(']'));

			if (!is_range && c == fn)
			  goto matched;

			cold = c;
			c = *p++;
		      }

		    if (c == L_('-') && *p != L_(']'))
		      {
#if _LIBC
			/* We have to find the collation sequence
			   value for C.  Collation sequence is nothing
			   we can regularly access.  The sequence
			   value is defined by the order in which the
			   definitions of the collation values for the
			   various characters appear in the source
			   file.  A strange concept, nowhere
			   documented.  */
			uint32_t fcollseq;
			uint32_t lcollseq;
			UCHAR cend = *p++;

# ifdef WIDE_CHAR_VERSION
			/* Search in the `names' array for the characters.  */
			fcollseq = __collseq_table_lookup (collseq, fn);
			if (fcollseq == ~((uint32_t) 0))
			  /* XXX We don't know anything about the character
			     we are supposed to match.  This means we are
			     failing.  */
			  goto range_not_matched;

			if (is_seqval)
			  lcollseq = cold;
			else
			  lcollseq = __collseq_table_lookup (collseq, cold);
# else
			fcollseq = collseq[fn];
			lcollseq = is_seqval ? cold : collseq[(UCHAR) cold];
# endif

			is_seqval = false;
			if (cend == L_('[') && *p == L_('.'))
			  {
			    uint32_t nrules =
			      _NL_CURRENT_WORD (LC_COLLATE,
						_NL_COLLATE_NRULES);
			    const CHAR *startp = p;
			    size_t c1 = 0;

			    while (1)
			      {
				c = *++p;
				if (c == L_('.') && p[1] == L_(']'))
				  {
				    p += 2;
				    break;
				  }
				if (c == '\0')
				  return FNM_NOMATCH;
				++c1;
			      }

			    if (nrules == 0)
			      {
				/* There are no names defined in the
				   collation data.  Therefore we only
				   accept the trivial names consisting
				   of the character itself.  */
				if (c1 != 1)
				  return FNM_NOMATCH;

				cend = startp[1];
			      }
			    else
			      {
				int32_t table_size;
				const int32_t *symb_table;
# ifdef WIDE_CHAR_VERSION
				char str[c1];
				size_t strcnt;
# else
#  define str (startp + 1)
# endif
				const unsigned char *extra;
				int32_t idx;
				int32_t elem;
				int32_t second;
				int32_t hash;

# ifdef WIDE_CHAR_VERSION
				/* We have to convert the name to a single-byte
				   string.  This is possible since the names
				   consist of ASCII characters and the internal
				   representation is UCS4.  */
				for (strcnt = 0; strcnt < c1; ++strcnt)
				  str[strcnt] = startp[1 + strcnt];
# endif

				table_size =
				  _NL_CURRENT_WORD (LC_COLLATE,
						    _NL_COLLATE_SYMB_HASH_SIZEMB);
				symb_table = (const int32_t *)
				  _NL_CURRENT (LC_COLLATE,
					       _NL_COLLATE_SYMB_TABLEMB);
				extra = (const unsigned char *)
				  _NL_CURRENT (LC_COLLATE,
					       _NL_COLLATE_SYMB_EXTRAMB);

				/* Locate the character in the hashing
                                   table.  */
				hash = elem_hash (str, c1);

				idx = 0;
				elem = hash % table_size;
				second = hash % (table_size - 2);
				while (symb_table[2 * elem] != 0)
				  {
				/* First compare the hashing value.  */
				    if (symb_table[2 * elem] == hash
					&& (c1
					    == extra[symb_table[2 * elem + 1]])
					&& memcmp (str,
						   &extra[symb_table[2 * elem + 1]
							 + 1], c1) == 0)
				      {
					/* Yep, this is the entry.  */
					idx = symb_table[2 * elem + 1];
					idx += 1 + extra[idx];
					break;
				      }

				    /* Next entry.  */
				    elem += second;
				  }

				if (symb_table[2 * elem] != 0)
				  {
				    /* Compare the byte sequence but only if
				       this is not part of a range.  */
# ifdef WIDE_CHAR_VERSION
				    int32_t *wextra;

				    idx += 1 + extra[idx];
				    /* Adjust for the alignment.  */
				    idx = (idx + 3) & ~4;

				    wextra = (int32_t *) &extra[idx + 4];
# endif
				    /* Get the collation sequence value.  */
				    is_seqval = true;
# ifdef WIDE_CHAR_VERSION
				    cend = wextra[1 + wextra[idx]];
# else
				    /* Adjust for the alignment.  */
				    idx += 1 + extra[idx];
				    idx = (idx + 3) & ~4;
				    cend = *((int32_t *) &extra[idx]);
# endif
				  }
				else if (symb_table[2 * elem] != 0 && c1 == 1)
				  {
				    cend = str[0];
				    c = *p++;
				  }
				else
				  return FNM_NOMATCH;
			      }
# undef str
			  }
			else
			  {
			    if (!(flags & FNM_NOESCAPE) && cend == L_('\\'))
			      cend = *p++;
			    if (cend == L_('\0'))
			      return FNM_NOMATCH;
			    cend = FOLD (cend);
			  }

			/* XXX It is not entirely clear to me how to handle
			   characters which are not mentioned in the
			   collation specification.  */
			if (
# ifdef WIDE_CHAR_VERSION
			    lcollseq == 0xffffffff ||
# endif
			    lcollseq <= fcollseq)
			  {
			    /* We have to look at the upper bound.  */
			    uint32_t hcollseq;

			    if (is_seqval)
			      hcollseq = cend;
			    else
			      {
# ifdef WIDE_CHAR_VERSION
				hcollseq =
				  __collseq_table_lookup (collseq, cend);
				if (hcollseq == ~((uint32_t) 0))
				  {
				    /* Hum, no information about the upper
				       bound.  The matching succeeds if the
				       lower bound is matched exactly.  */
				    if (lcollseq != fcollseq)
				      goto range_not_matched;

				    goto matched;
				  }
# else
				hcollseq = collseq[cend];
# endif
			      }

			    if (lcollseq <= hcollseq && fcollseq <= hcollseq)
			      goto matched;
			  }
# ifdef WIDE_CHAR_VERSION
		      range_not_matched:
# endif
#else
			/* We use a boring value comparison of the character
			   values.  This is better than comparing using
			   `strcoll' since the latter would have surprising
			   and sometimes fatal consequences.  */
			UCHAR cend = *p++;

			if (!(flags & FNM_NOESCAPE) && cend == L_('\\'))
			  cend = *p++;
			if (cend == L_('\0'))
			  return FNM_NOMATCH;

			/* It is a range.  */
			if (cold <= fn && fn <= cend)
			  goto matched;
#endif

			c = *p++;
		      }
		  }

		if (c == L_(']'))
		  break;
	      }

	    if (!not)
	      return FNM_NOMATCH;
	    break;

	  matched:
	    /* Skip the rest of the [...] that already matched.  */
	    do
	      {
	      ignore_next:
		c = *p++;

		if (c == L_('\0'))
		  /* [... (unterminated) loses.  */
		  return FNM_NOMATCH;

		if (!(flags & FNM_NOESCAPE) && c == L_('\\'))
		  {
		    if (*p == L_('\0'))
		      return FNM_NOMATCH;
		    /* XXX 1003.2d11 is unclear if this is right.  */
		    ++p;
		  }
		else if (c == L_('[') && *p == L_(':'))
		  {
		    int c1 = 0;
		    const CHAR *startp = p;

		    while (1)
		      {
			c = *++p;
			if (++c1 == CHAR_CLASS_MAX_LENGTH)
			  return FNM_NOMATCH;

			if (*p == L_(':') && p[1] == L_(']'))
			  break;

			if (c < L_('a') || c >= L_('z'))
			  {
			    p = startp;
			    goto ignore_next;
			  }
		      }
		    p += 2;
		    c = *p++;
		  }
		else if (c == L_('[') && *p == L_('='))
		  {
		    c = *++p;
		    if (c == L_('\0'))
		      return FNM_NOMATCH;
		    c = *++p;
		    if (c != L_('=') || p[1] != L_(']'))
		      return FNM_NOMATCH;
		    p += 2;
		    c = *p++;
		  }
		else if (c == L_('[') && *p == L_('.'))
		  {
		    ++p;
		    while (1)
		      {
			c = *++p;
			if (c == '\0')
			  return FNM_NOMATCH;

			if (*p == L_('.') && p[1] == L_(']'))
			  break;
		      }
		    p += 2;
		    c = *p++;
		  }
	      }
	    while (c != L_(']'));
	    if (not)
	      return FNM_NOMATCH;
	  }
	  break;

	case L_('+'):
	case L_('@'):
	case L_('!'):
	  if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
	    {
	      int res;

	      res = EXT (c, p, n, string_end, no_leading_period, flags);
	      if (res != -1)
		return res;
	    }
	  goto normal_match;

	case L_('/'):
	  if (NO_LEADING_PERIOD (flags))
	    {
	      if (n == string_end || c != (UCHAR) *n)
		return FNM_NOMATCH;

	      new_no_leading_period = true;
	      break;
	    }
	  /* FALLTHROUGH */
	default:
	normal_match:
	  if (n == string_end || c != FOLD ((UCHAR) *n))
	    return FNM_NOMATCH;
	}

      no_leading_period = new_no_leading_period;
      ++n;
    }

  if (n == string_end)
    return 0;

  if ((flags & FNM_LEADING_DIR) && n != string_end && *n == L_('/'))
    /* The FNM_LEADING_DIR flag says that "foo*" matches "foobar/frobozz".  */
    return 0;

  return FNM_NOMATCH;
}
示例#19
0
void user_print(User *u,int indent){
char *space,*space1;
GList *it;
Contact *c;

	space=g_strnfill(indent*2,' ');
	space1=g_strnfill((indent+1)*2,' ');
	g_message(L_("%sUser: %p"),space,u);
	g_message(L_("%sJID: %s"),space,u->jid);
	g_message(L_("%sUIN: %u"),space,(unsigned)u->uin);
	g_message(L_("%sPassword: %p"),space,u->password);
	g_message(L_("%sLast sys message: %i"),space,u->last_sys_msg);
	g_message(L_("%sConfirmed: %i"),space,u->confirmed);
	g_message(L_("%sContacts:"),space);
	for(it=g_list_first(u->contacts);it;it=it->next){
		c=(Contact *)it->data;
		g_message(L_("%sContact: %p"),space1,c);
		g_message(L_("%sUin: %u"),space1,(unsigned)c->uin);
		g_message(L_("%sStatus: %i"),space1,c->status);
		g_message(L_("%sLast update: %s"),space1,ctime((time_t *)&c->last_update));
	}
	g_free(space1);
	g_free(space);
}
示例#20
0
internal_function
END (const CHAR *pattern)
{
  const CHAR *p = pattern;

  while (1)
    if (*++p == L_('\0'))
      /* This is an invalid pattern.  */
      return pattern;
    else if (*p == L_('['))
      {
	/* Handle brackets special.  */
	if (posixly_correct == 0)
	  posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;

	/* Skip the not sign.  We have to recognize it because of a possibly
	   following ']'.  */
	if (*++p == L_('!') || (posixly_correct < 0 && *p == L_('^')))
	  ++p;
	/* A leading ']' is recognized as such.  */
	if (*p == L_(']'))
	  ++p;
	/* Skip over all characters of the list.  */
	while (*p != L_(']'))
	  if (*p++ == L_('\0'))
	    /* This is no valid pattern.  */
	    return pattern;
      }
    else if ((*p == L_('?') || *p == L_('*') || *p == L_('+') || *p == L_('@')
	      || *p == L_('!')) && p[1] == L_('('))
      p = END (p + 1);
    else if (*p == L_(')'))
      break;

  return p + 1;
}
示例#21
0
void IBConnection::on_established(struct rdma_cm_event* /* event */)
{
    L_(debug) << "[" << index_ << "] "
              << "connection established";
}
示例#22
0
static int
internal_function
EXT (INT opt, const CHAR *pattern, const CHAR *string, const CHAR *string_end,
     bool no_leading_period, int flags)
{
  const CHAR *startp;
  size_t level;
  struct patternlist
  {
    struct patternlist *next;
    CHAR str[1];
  } *list = NULL;
  struct patternlist **lastp = &list;
  size_t pattern_len = STRLEN (pattern);
  const CHAR *p;
  const CHAR *rs;
  enum { ALLOCA_LIMIT = 8000 };

  /* Parse the pattern.  Store the individual parts in the list.  */
  level = 0;
  for (startp = p = pattern + 1; ; ++p)
    if (*p == L_('\0'))
      /* This is an invalid pattern.  */
      return -1;
    else if (*p == L_('['))
      {
	/* Handle brackets special.  */
	if (posixly_correct == 0)
	  posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;

	/* Skip the not sign.  We have to recognize it because of a possibly
	   following ']'.  */
	if (*++p == L_('!') || (posixly_correct < 0 && *p == L_('^')))
	  ++p;
	/* A leading ']' is recognized as such.  */
	if (*p == L_(']'))
	  ++p;
	/* Skip over all characters of the list.  */
	while (*p != L_(']'))
	  if (*p++ == L_('\0'))
	    /* This is no valid pattern.  */
	    return -1;
      }
    else if ((*p == L_('?') || *p == L_('*') || *p == L_('+') || *p == L_('@')
	      || *p == L_('!')) && p[1] == L_('('))
      /* Remember the nesting level.  */
      ++level;
    else if (*p == L_(')'))
      {
	if (level-- == 0)
	  {
	    /* This means we found the end of the pattern.  */
#define NEW_PATTERN \
	    struct patternlist *newp;					      \
	    size_t plen;						      \
	    size_t plensize;						      \
	    size_t newpsize;						      \
									      \
	    plen = (opt == L_('?') || opt == L_('@')			      \
		    ? pattern_len					      \
		    : p - startp + 1);					      \
	    plensize = plen * sizeof (CHAR);				      \
	    newpsize = offsetof (struct patternlist, str) + plensize;	      \
	    if ((size_t) -1 / sizeof (CHAR) < plen			      \
		|| newpsize < offsetof (struct patternlist, str)	      \
		|| ALLOCA_LIMIT <= newpsize)				      \
	      return -1;						      \
	    newp = (struct patternlist *) alloca (newpsize);		      \
	    *((CHAR *) MEMPCPY (newp->str, startp, p - startp)) = L_('\0');    \
	    newp->next = NULL;						      \
	    *lastp = newp;						      \
	    lastp = &newp->next
	    NEW_PATTERN;
	    break;
	  }
      }
    else if (*p == L_('|'))
      {
	if (level == 0)
	  {
	    NEW_PATTERN;
	    startp = p + 1;
	  }
      }
  assert (list != NULL);
  assert (p[-1] == L_(')'));
#undef NEW_PATTERN

  switch (opt)
    {
    case L_('*'):
      if (FCT (p, string, string_end, no_leading_period, flags) == 0)
	return 0;
      /* FALLTHROUGH */

    case L_('+'):
      do
	{
	  for (rs = string; rs <= string_end; ++rs)
	    /* First match the prefix with the current pattern with the
	       current pattern.  */
	    if (FCT (list->str, string, rs, no_leading_period,
		     flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0
		/* This was successful.  Now match the rest with the rest
		   of the pattern.  */
		&& (FCT (p, rs, string_end,
			 rs == string
			 ? no_leading_period
			 : rs[-1] == '/' && NO_LEADING_PERIOD (flags),
			 flags & FNM_FILE_NAME
			 ? flags : flags & ~FNM_PERIOD) == 0
		    /* This didn't work.  Try the whole pattern.  */
		    || (rs != string
			&& FCT (pattern - 1, rs, string_end,
				rs == string
				? no_leading_period
				: rs[-1] == '/' && NO_LEADING_PERIOD (flags),
				flags & FNM_FILE_NAME
				? flags : flags & ~FNM_PERIOD) == 0)))
	      /* It worked.  Signal success.  */
	      return 0;
	}
      while ((list = list->next) != NULL);

      /* None of the patterns lead to a match.  */
      return FNM_NOMATCH;

    case L_('?'):
      if (FCT (p, string, string_end, no_leading_period, flags) == 0)
	return 0;
      /* FALLTHROUGH */

    case L_('@'):
      do
	/* I cannot believe it but `strcat' is actually acceptable
	   here.  Match the entire string with the prefix from the
	   pattern list and the rest of the pattern following the
	   pattern list.  */
	if (FCT (STRCAT (list->str, p), string, string_end,
		 no_leading_period,
		 flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0)
	  /* It worked.  Signal success.  */
	  return 0;
      while ((list = list->next) != NULL);

      /* None of the patterns lead to a match.  */
      return FNM_NOMATCH;

    case L_('!'):
      for (rs = string; rs <= string_end; ++rs)
	{
	  struct patternlist *runp;

	  for (runp = list; runp != NULL; runp = runp->next)
	    if (FCT (runp->str, string, rs,  no_leading_period,
		     flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0)
	      break;

	  /* If none of the patterns matched see whether the rest does.  */
	  if (runp == NULL
	      && (FCT (p, rs, string_end,
		       rs == string
		       ? no_leading_period
		       : rs[-1] == '/' && NO_LEADING_PERIOD (flags),
		       flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD)
		  == 0))
	    /* This is successful.  */
	    return 0;
	}

      /* None of the patterns together with the rest of the pattern
	 lead to a match.  */
      return FNM_NOMATCH;

    default:
      assert (! "Invalid extended matching operator");
      break;
    }

  return -1;
}
示例#23
0
  void parse_options(int argc, char* argv[]) {

    std::string config_file;
    unsigned log_level;
    std::string log_file;

    po::options_description generic("Generic options");
    auto generic_add = generic.add_options();
    generic_add("help,h", "produce help message");
    generic_add("config-file,c",
                po::value<std::string>(&config_file)->default_value("flib.cfg"),
                "name of a configuration file");
    generic_add("log-level,l",
                po::value<unsigned>(&log_level)->default_value(2),
                "set the log level (all:0)");
    generic_add("log-file,L", po::value<std::string>(&log_file),
                "name of target log file");

    po::options_description config("Configuration (flib.cfg or cmd line)");
    auto config_add = config.add_options();
    config_add("flib-addr,i", po::value<pci_addr>(),
               "PCI BDF address of target FLIB in BB:DD.F format");
    config_add("identify", po::value<bool>(&_identify)->default_value(false),
               "toggle FLIB ID led");
    config_add("mc-size,t", po::value<uint32_t>(),
               "size of pattern generator microslices in units of "
               "1024 ns (31 bit wide)");
    config_add("pgen-rate,r", po::value<float>(),
               "MS fill level of pattern generator in [0,1]");
    config_add("mc-size-limit", po::value<uint32_t>(&_mc_size_limit),
               "Threshold of microslice size limiter in bytes.");

    config_add("l0_source", po::value<std::string>(),
               "Link 0 data source <disable|flim|pgen_far|pgen_near>");
    config_add("l0_eq_id", po::value<std::string>(),
               "Equipment identifier of link 0 pgen data source (16 Bit)");
    config_add("l1_source", po::value<std::string>(),
               "Link 1 data source <disable|flim|pgen_far|pgen_near>");
    config_add("l1_eq_id", po::value<std::string>(),
               "Equipment identifier of link 1 pgen data source (16 Bit)");
    config_add("l2_source", po::value<std::string>(),
               "Link 2 data source <disable|flim|pgen_far|pgen_near>");
    config_add("l2_eq_id", po::value<std::string>(),
               "Equipment identifier of link 2 pgen data source (16 Bit)");
    config_add("l3_source", po::value<std::string>(),
               "Link 3 data source <disable|flim|pgen_far|pgen_near>");
    config_add("l3_eq_id", po::value<std::string>(),
               "Equipment identifier of link 3 pgen data source (16 Bit)");
    config_add("l4_source", po::value<std::string>(),
               "Link 4 data source <disable|flim|pgen_far|pgen_near>");
    config_add("l4_eq_id", po::value<std::string>(),
               "Equipment identifier of link 4 pgen data source (16 Bit)");
    config_add("l5_source", po::value<std::string>(),
               "Link 5 data source <disable|flim|pgen_far|pgen_near>");
    config_add("l5_eq_id", po::value<std::string>(),
               "Equipment identifier of link 5 pgen data source (16 Bit)");
    config_add("l6_source", po::value<std::string>(),
               "Link 6 data source <disable|flim|pgen_far|pgen_near>");
    config_add("l6_eq_id", po::value<std::string>(),
               "Equipment identifier of link 6 pgen data source (16 Bit)");
    config_add("l7_source", po::value<std::string>(),
               "Link 7 data source <disable|flim|pgen_far|pgen_near>");
    config_add("l7_eq_id", po::value<std::string>(),
               "Equipment identifier of link 7 pgen data source (16 Bit)");

    po::options_description cmdline_options("Allowed options");
    cmdline_options.add(generic).add(config);

    po::options_description config_file_options;
    config_file_options.add(config);

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, cmdline_options), vm);
    po::notify(vm);

    std::ifstream ifs(config_file.c_str());
    if (!ifs) {
      throw ParametersException("cannot open config file: " + config_file);
    } else {
      po::store(po::parse_config_file(ifs, config_file_options), vm);
      notify(vm);
    }

    if (vm.count("help")) {
      std::cout << cmdline_options << "\n";
      exit(EXIT_SUCCESS);
    }

    logging::add_console(static_cast<severity_level>(log_level));
    if (vm.count("log-file")) {
      L_(info) << "Logging output to " << log_file;
      logging::add_file(log_file, static_cast<severity_level>(log_level));
    }

    L_(info) << "Device config:";

    if (vm.count("flib-addr")) {
      _flib_addr = vm["flib-addr"].as<pci_addr>();
      _flib_autodetect = false;
      L_(info) << " FLIB address: " << std::hex << std::setw(2)
               << std::setfill('0') << static_cast<unsigned>(_flib_addr.bus)
               << ":" << std::setw(2) << std::setfill('0')
               << static_cast<unsigned>(_flib_addr.dev) << "."
               << static_cast<unsigned>(_flib_addr.func) << std::dec;
    } else {
      _flib_autodetect = true;
      L_(info) << " FLIB address: autodetect";
    }

    if (vm.count("mc-size")) {
      _mc_size = vm["mc-size"].as<uint32_t>();
      if (_mc_size > 2147483647) { // 31 bit check
        throw ParametersException("Pgen microslice size out of range");
      } else {
        L_(info) << " Pgen microslice size: "
                 << human_readable_mc_size(_mc_size);
      }
    } else {
      L_(info) << " Pgen microslice size: " << human_readable_mc_size(_mc_size)
               << " (default)";
    }

    if (vm.count("pgen-rate")) {
      _pgen_rate = vm["pgen-rate"].as<float>();
      if (_pgen_rate < 0 || _pgen_rate > 1) { // range check
        throw ParametersException("Pgen rate out of range");
      } else {
        L_(info) << " Pgen rate: " << _pgen_rate;
      }
    }

    L_(info) << " FLIB microslice size limit: " << _mc_size_limit << " bytes";

    for (size_t i = 0; i < _num_flib_links; ++i) {
      L_(info) << "Link " << i << " config:";
      parse_data_source(vm, i);
    } // end loop over links
  }
示例#24
0
void Parameters::parse_options(int argc, char* argv[])
{
    unsigned log_level = 2;
    std::string log_file;

    po::options_description general("General options");
    auto general_add = general.add_options();
    general_add("version,V", "print version string");
    general_add("help,h", "produce help message");
    general_add("log-level,l", po::value<unsigned>(&log_level),
                "set the log level (default:2, all:0)");
    general_add("log-file,L", po::value<std::string>(&log_file),
                "name of target log file");
    general_add("maximum-number,n", po::value<uint64_t>(&maximum_number),
                "set the maximum number of microslices to process (default: "
                "unlimited)");

    po::options_description source("Source options");
    auto source_add = source.add_options();
    source_add("shm-channel,c", po::value<size_t>(&shm_channel),
               "use given shared memory channel as data source");
    source_add("input-shm,I", po::value<std::string>(&input_shm),
               "name of a shared memory to use as data source");
    source_add("input-archive,i", po::value<std::string>(&input_archive),
               "name of an input file archive to read");

    po::options_description opmode("Operation mode options");
    auto opmode_add = opmode.add_options();
    opmode_add("debugger,d", po::value<bool>(&debugger)->implicit_value(true),
             "enable/disable debugger (raw message unpacking and printout)");
    opmode_add("sorter,s", po::value<bool>(&sorter)->implicit_value(true),
             "enable/disable sorting by epoch in epoch buffer for sink(s) (build output ms from epochs)");
    opmode_add("ep_in_ms,N", po::value<uint32_t>(&epoch_per_ms),
             "Number of epochs stored in each output MS in case sorter is used (default:1)");
    opmode_add("sortmesg", po::value<bool>(&sortmesg)->implicit_value(true),
             "enable/disable message sorting inside epoch buffer before creation of new ms");

    po::options_description sink("Sink options");
    auto sink_add = sink.add_options();
    sink_add("dump_verbosity,v", po::value<size_t>(&dump_verbosity),
             "set output debug dump verbosity");
    sink_add("output-shm,O", po::value<std::string>(&output_shm),
             "name of a shared memory to write to");
    sink_add("output-archive,o", po::value<std::string>(&output_archive),
             "name of an output file archive to write");

    po::options_description desc;
    desc.add(general).add(source).add(opmode).add(sink);

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help") != 0u) {
        std::cout << "ngdpbtool, git revision " << g_GIT_REVISION << std::endl;
        std::cout << desc << std::endl;
        exit(EXIT_SUCCESS);
    }

    if (vm.count("version") != 0u) {
        std::cout << "ngdpbtool, git revision " << g_GIT_REVISION << std::endl;
        exit(EXIT_SUCCESS);
    }

    logging::add_console(static_cast<severity_level>(log_level));
    if (vm.count("log-file")) {
        L_(info) << "Logging output to " << log_file;
        logging::add_file(log_file, static_cast<severity_level>(log_level));
    }

    size_t input_sources = vm.count("input-archive") + vm.count("input-shm");
    if (input_sources == 0) {
        throw ParametersException("no input source specified");
    }
    if (input_sources > 1) {
        throw ParametersException("more than one input source specified");
    }
}
示例#25
0
__parse_one_specmb (const UCHAR_T *format, size_t posn,
		    struct printf_spec *spec, size_t *max_ref_arg)
#endif
{
  unsigned int n;
  size_t nargs = 0;

  /* Skip the '%'.  */
  ++format;

  /* Clear information structure.  */
  spec->data_arg = -1;
  spec->info.alt = 0;
  spec->info.space = 0;
  spec->info.left = 0;
  spec->info.showsign = 0;
  spec->info.group = 0;
  spec->info.i18n = 0;
  spec->info.extra = 0;
  spec->info.pad = ' ';
  spec->info.wide = sizeof (UCHAR_T) > 1;

  /* Test for positional argument.  */
  if (ISDIGIT (*format))
    {
      const UCHAR_T *begin = format;

      n = read_int (&format);

      if (n > 0 && *format == L_('$'))
	/* Is positional parameter.  */
	{
	  ++format;		/* Skip the '$'.  */
	  spec->data_arg = n - 1;
	  *max_ref_arg = MAX (*max_ref_arg, n);
	}
      else
	/* Oops; that was actually the width and/or 0 padding flag.
	   Step back and read it again.  */
	format = begin;
    }

  /* Check for spec modifiers.  */
  do
    {
      switch (*format)
	{
	case L_(' '):
	  /* Output a space in place of a sign, when there is no sign.  */
	  spec->info.space = 1;
	  continue;
	case L_('+'):
	  /* Always output + or - for numbers.  */
	  spec->info.showsign = 1;
	  continue;
	case L_('-'):
	  /* Left-justify things.  */
	  spec->info.left = 1;
	  continue;
	case L_('#'):
	  /* Use the "alternate form":
	     Hex has 0x or 0X, FP always has a decimal point.  */
	  spec->info.alt = 1;
	  continue;
	case L_('0'):
	  /* Pad with 0s.  */
	  spec->info.pad = '0';
	  continue;
	case L_('\''):
	  /* Show grouping in numbers if the locale information
	     indicates any.  */
	  spec->info.group = 1;
	  continue;
	case L_('I'):
	  /* Use the internationalized form of the output.  Currently
	     means to use the `outdigits' of the current locale.  */
	  spec->info.i18n = 1;
	  continue;
	default:
	  break;
	}
      break;
    }
  while (*++format);

  if (spec->info.left)
    spec->info.pad = ' ';

  /* Get the field width.  */
  spec->width_arg = -1;
  spec->info.width = 0;
  if (*format == L_('*'))
    {
      /* The field width is given in an argument.
	 A negative field width indicates left justification.  */
      const UCHAR_T *begin = ++format;

      if (ISDIGIT (*format))
	{
	  /* The width argument might be found in a positional parameter.  */
	  n = read_int (&format);

	  if (n > 0 && *format == L_('$'))
	    {
	      spec->width_arg = n - 1;
	      *max_ref_arg = MAX (*max_ref_arg, n);
	      ++format;		/* Skip '$'.  */
	    }
	}

      if (spec->width_arg < 0)
	{
	  /* Not in a positional parameter.  Consume one argument.  */
	  spec->width_arg = posn++;
	  ++nargs;
	  format = begin;	/* Step back and reread.  */
	}
    }
  else if (ISDIGIT (*format))
    /* Constant width specification.  */
    spec->info.width = read_int (&format);

  /* Get the precision.  */
  spec->prec_arg = -1;
  /* -1 means none given; 0 means explicit 0.  */
  spec->info.prec = -1;
  if (*format == L_('.'))
    {
      ++format;
      if (*format == L_('*'))
	{
	  /* The precision is given in an argument.  */
	  const UCHAR_T *begin = ++format;

	  if (ISDIGIT (*format))
	    {
	      n = read_int (&format);

	      if (n > 0 && *format == L_('$'))
		{
		  spec->prec_arg = n - 1;
		  *max_ref_arg = MAX (*max_ref_arg, n);
		  ++format;
		}
	    }

	  if (spec->prec_arg < 0)
	    {
	      /* Not in a positional parameter.  */
	      spec->prec_arg = posn++;
	      ++nargs;
	      format = begin;
	    }
	}
      else if (ISDIGIT (*format))
	spec->info.prec = read_int (&format);
      else
	/* "%.?" is treated like "%.0?".  */
	spec->info.prec = 0;
    }

  /* Check for type modifiers.  */
  spec->info.is_long_double = 0;
  spec->info.is_short = 0;
  spec->info.is_long = 0;
  spec->info.is_char = 0;
  spec->info.user = 0;

  if (__builtin_expect (__printf_modifier_table == NULL, 1)
      || __printf_modifier_table[*format] == NULL
      || HANDLE_REGISTERED_MODIFIER (&format, &spec->info) != 0)
    switch (*format++)
      {
      case L_('h'):
	/* ints are short ints or chars.  */
	if (*format != L_('h'))
	  spec->info.is_short = 1;
	else
	  {
	    ++format;
	    spec->info.is_char = 1;
	  }
	break;
      case L_('l'):
	/* ints are long ints.  */
	spec->info.is_long = 1;
	if (*format != L_('l'))
	  break;
	++format;
	/* FALLTHROUGH */
      case L_('L'):
	/* doubles are long doubles, and ints are long long ints.  */
      case L_('q'):
	/* 4.4 uses this for long long.  */
	spec->info.is_long_double = 1;
	break;
      case L_('z'):
      case L_('Z'):
	/* ints are size_ts.  */
	assert (sizeof (size_t) <= sizeof (unsigned long long int));
#if LONG_MAX != LONG_LONG_MAX
	spec->info.is_long_double = (sizeof (size_t)
				     > sizeof (unsigned long int));
#endif
	spec->info.is_long = sizeof (size_t) > sizeof (unsigned int);
	break;
      case L_('t'):
	assert (sizeof (ptrdiff_t) <= sizeof (long long int));
#if LONG_MAX != LONG_LONG_MAX
	spec->info.is_long_double = (sizeof (ptrdiff_t) > sizeof (long int));
#endif
	spec->info.is_long = sizeof (ptrdiff_t) > sizeof (int);
	break;
      case L_('j'):
	assert (sizeof (uintmax_t) <= sizeof (unsigned long long int));
#if LONG_MAX != LONG_LONG_MAX
	spec->info.is_long_double = (sizeof (uintmax_t)
				     > sizeof (unsigned long int));
#endif
	spec->info.is_long = sizeof (uintmax_t) > sizeof (unsigned int);
	break;
      default:
	/* Not a recognized modifier.  Backup.  */
	--format;
	break;
      }

  /* Get the format specification.  */
  spec->info.spec = (wchar_t) *format++;
  spec->size = -1;
  if (__builtin_expect (__printf_function_table == NULL, 1)
      || spec->info.spec > UCHAR_MAX
      || __printf_arginfo_table[spec->info.spec] == NULL
      /* We don't try to get the types for all arguments if the format
	 uses more than one.  The normal case is covered though.  If
	 the call returns -1 we continue with the normal specifiers.  */
      || (int) (spec->ndata_args = (*__printf_arginfo_table[spec->info.spec])
				   (&spec->info, 1, &spec->data_arg_type,
				    &spec->size)) < 0)
    {
      /* Find the data argument types of a built-in spec.  */
      spec->ndata_args = 1;

      switch (spec->info.spec)
	{
	case L'i':
	case L'd':
	case L'u':
	case L'o':
	case L'X':
	case L'x':
#if LONG_MAX != LONG_LONG_MAX
	  if (spec->info.is_long_double)
	    spec->data_arg_type = PA_INT|PA_FLAG_LONG_LONG;
	  else
#endif
	    if (spec->info.is_long)
	      spec->data_arg_type = PA_INT|PA_FLAG_LONG;
	    else if (spec->info.is_short)
	      spec->data_arg_type = PA_INT|PA_FLAG_SHORT;
	    else if (spec->info.is_char)
	      spec->data_arg_type = PA_CHAR;
	    else
	      spec->data_arg_type = PA_INT;
	  break;
	case L'e':
	case L'E':
	case L'f':
	case L'F':
	case L'g':
	case L'G':
	case L'a':
	case L'A':
	  if (spec->info.is_long_double)
	    spec->data_arg_type = PA_DOUBLE|PA_FLAG_LONG_DOUBLE;
	  else
	    spec->data_arg_type = PA_DOUBLE;
	  break;
	case L'c':
	  spec->data_arg_type = PA_CHAR;
	  break;
	case L'C':
	  spec->data_arg_type = PA_WCHAR;
	  break;
	case L's':
	  spec->data_arg_type = PA_STRING;
	  break;
	case L'S':
	  spec->data_arg_type = PA_WSTRING;
	  break;
	case L'p':
	  spec->data_arg_type = PA_POINTER;
	  break;
	case L'n':
	  spec->data_arg_type = PA_INT|PA_FLAG_PTR;
	  break;

	case L'm':
	default:
	  /* An unknown spec will consume no args.  */
	  spec->ndata_args = 0;
	  break;
	}
    }

  if (spec->data_arg == -1 && spec->ndata_args > 0)
    {
      /* There are args consumed, but no positional spec.  Use the
	 next sequential arg position.  */
      spec->data_arg = posn;
      nargs += spec->ndata_args;
    }

  if (spec->info.spec == L'\0')
    /* Format ended before this spec was complete.  */
    spec->end_of_fmt = spec->next_fmt = format - 1;
  else
    {
      /* Find the next format spec.  */
      spec->end_of_fmt = format;
#ifdef COMPILE_WPRINTF
      spec->next_fmt = __find_specwc (format);
#else
      spec->next_fmt = __find_specmb (format);
#endif
    }

  return nargs;
}
void perform_front_propagation_2d(T_callback_intert_node callback_insert_node)
{
	// create the Fibonacci heap
	struct fibheap* open_heap = fh_makeheap();
	fh_setcmp(open_heap, compare_points);

	double h = 1.0/n;
	
	// initialize points
	for( int i=0; i<n; ++i )
	for( int j=0; j<p; ++j )
	{
		D_(i,j) = GW_INFINITE;
		S_(i,j) = kFar;
		Q_(i,j) = -1;
	}

	// record all the points
	heap_pool = new fibheap_el*[n*p]; 
	memset( heap_pool, NULL, n*p*sizeof(fibheap_el*) );

	// inialize open list
	point_list existing_points;
	for( int k=0; k<nb_start_points; ++k )
	{
		int i = (int) start_points_(0,k);
		int j = (int) start_points_(1,k);

		if( D_( i,j )==0 )
			ERROR_MSG("start_points should not contain duplicates.");

		point* pt = new point( i,j );
		existing_points.push_back( pt );			// for deleting at the end
		heap_pool_(i,j) = fh_insert( open_heap, pt );			// add to heap
		if( values==NULL ) 
			D_( i,j ) = 0;
		else
			D_( i,j ) = values[k];
		S_( i,j ) = kOpen;
		Q_(i,j) = k;
	}

	// perform the front propagation
	int num_iter = 0;
	bool stop_iteration = GW_False;
	while( !fh_isempty(open_heap) && num_iter<nb_iter_max && !stop_iteration )
	{
		num_iter++;

		// current point
		point& cur_point = * ((point*) fh_extractmin( open_heap ));
		int i = cur_point.i;
		int j = cur_point.j;
		heap_pool_(i,j) = NULL;
		S_(i,j) = kDead;
		stop_iteration = end_points_reached(i,j);
		
		/*
		char msg[200];
		sprintf(msg, "Cool %f", Q_(i,j) );
		WARN_MSG( msg ); 
		*/
		
		CHECK_HEAP;

		// recurse on each neighbor
		int nei_i[4] = {i+1,i,i-1,i};
		int nei_j[4] = {j,j+1,j,j-1};
		for( int k=0; k<4; ++k )
		{
			int ii = nei_i[k];
			int jj = nei_j[k];
			bool bInsert = true;
			if( callback_insert_node!=NULL )
				bInsert = callback_insert_node(i,j,ii,jj);
			// check that the contraint distance map is ok
			if( ii>=0 && jj>=0 && ii<n && jj<p && bInsert )
			{
				double P = h/W_(ii,jj);
				// compute its neighboring values
				double a1 = GW_INFINITE;
				int k1 = -1;
				if( ii<n-1 )
				{
					bool bParticipate = true;
					if( callback_insert_node!=NULL )
						bParticipate = callback_insert_node(ii,jj,ii+1,jj);
					if( bParticipate )
					{
						a1 = D_(ii+1,jj);
						k1 = Q_(ii+1,jj);
					}
				}
				if( ii>0 )
				{
					bool bParticipate = true;
					if( callback_insert_node!=NULL )
						bParticipate = callback_insert_node(ii,jj,ii-1,jj);
					if( bParticipate )
					{
						if( D_(ii-1,jj)<a1 )
							k1 = Q_(ii-1,jj);
						a1 = GW_MIN( a1, D_(ii-1,jj) );
					}
				}
				double a2 = GW_INFINITE;
				int k2 = -1;
				if( jj<p-1 )
				{

					bool bParticipate = true;
					if( callback_insert_node!=NULL )
						bParticipate = callback_insert_node(ii,jj,ii,jj+1);
					if( bParticipate )
					{
						a2 = D_(ii,jj+1);
						k2 = Q_(ii,jj+1);
					}
				}
				if( jj>0 )
				{
					bool bParticipate = true;
					if( callback_insert_node!=NULL )
						bParticipate = callback_insert_node(ii,jj,ii,jj-1);
					if( bParticipate )
					{
						if( D_(ii,jj-1)<a2 )
							k2 = Q_(ii,jj-1);
						a2 = GW_MIN( a2, D_(ii,jj-1) );
					}
				}
				if( a1>a2 )	// swap so that a1<a2
				{
					double tmp = a1; a1 = a2; a2 = tmp;
					int tmpi = k1; k1 = k2; k2 = tmpi;
				}
				// update its distance
				// now the equation is   (a-a1)^2+(a-a2)^2 = P, with a >= a2 >= a1.
				double A1 = 0;
				if( P*P > (a2-a1)*(a2-a1) )
				{
					double delta = 2*P*P-(a2-a1)*(a2-a1);
					A1 = (a1+a2+sqrt(delta))/2.0;
				}
				else
					A1 = a1 + P;
				if( ((int) S_(ii,jj)) == kDead )
				{
					// check if action has change. Should not happen for FM
					// if( A1<D_(ii,jj) )
					//	WARN_MSG("The update is not monotone");
#if 1
					if( A1<D_(ii,jj) )	// should not happen for FM
					{
						D_(ii,jj) = A1;
						// update the value of the closest starting point
						//if( GW_ABS(a1-A1)<GW_ABS(a2-A1) && k1>=0  )
							Q_(ii,jj) = k1;
						//else
						//	Q_(ii,jj) = k2;
						//Q_(ii,jj) = Q_(i,j);
					}
#endif
				}
				else if( ((int) S_(ii,jj)) == kOpen )
				{
					// check if action has change.
					if( A1<D_(ii,jj) )
					{
						D_(ii,jj) = A1;
						// update the value of the closest starting point
						//if( GW_ABS(a1-A1)<GW_ABS(a2-A1) && k1>=0  )
							Q_(ii,jj) = k1;
						//else
						//	Q_(ii,jj) = k2;
						//Q_(ii,jj) = Q_(i,j);
						// Modify the value in the heap
						fibheap_el* cur_el = heap_pool_(ii,jj);
						if( cur_el!=NULL )
							fh_replacedata( open_heap, cur_el, cur_el->fhe_data );	// use same data for update
						else
							ERROR_MSG("Error in heap pool allocation."); 
					}
				}
				else if( ((int) S_(ii,jj)) == kFar )
				{
					if( D_(ii,jj)!=GW_INFINITE )
						ERROR_MSG("Distance must be initialized to Inf");
					if( L==NULL || A1<=L_(ii,jj) )
					{
						S_(ii,jj) = kOpen;
						// distance must have change.
						D_(ii,jj) = A1;
						// update the value of the closest starting point
						//if( GW_ABS(a1-A1)<GW_ABS(a2-A1) && k1>=0 )
							Q_(ii,jj) = k1;
						//else
						//	Q_(ii,jj) = k2;
						//Q_(ii,jj) = Q_(i,j);
						// add to open list
						point* pt = new point(ii,jj);
						existing_points.push_back( pt );
						heap_pool_(ii,jj) = fh_insert( open_heap, pt );			// add to heap	
					}
				}
				else 
					ERROR_MSG("Unkwnown state."); 
					
			}	// end switch
		}		// end for
	}			// end while

//				char msg[200];
//				sprintf(msg, "Cool %f", Q_(100,100) );
//				 WARN_MSG( msg ); 

	// free heap
	fh_deleteheap(open_heap);
	// free point pool
	for( point_list::iterator it = existing_points.begin(); it!=existing_points.end(); ++it )
		GW_DELETE( *it );
	// free fibheap pool
	GW_DELETEARRAY(heap_pool);
}
示例#27
0
文件: Win32Wnd.cpp 项目: koz4k/soccer
void Ctrl::InitWin32(HINSTANCE hInstance)
{
	GuiLock __;
	LLOG("InitWin32");

	InstallPanicMessageBox(&Win32PanicMessageBox);
//	RLOGBLOCK("Ctrl::InitWin32");
	sMainThreadId = GetCurrentThreadId();
#define ILOG(x) // RLOG(x)
	Ctrl::hInstance = hInstance;
	ILOG("RegisterClassW");
#ifndef PLATFORM_WINCE
	if(IsWinNT())
#endif
	{
		WNDCLASSW  wc;
		Zero(wc);
		wc.style         = CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW;
		wc.lpfnWndProc   = (WNDPROC)Ctrl::WndProc;
		wc.hInstance     = hInstance;
		wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
		wc.hbrBackground = IsWinVista() ? (HBRUSH)(COLOR_WINDOW+1) : (HBRUSH)NULL;
		wc.lpszClassName = L"UPP-CLASS-W";
		RegisterClassW(&wc);
		wc.style         = 0x20000|CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW;
		wc.lpszClassName = L"UPP-CLASS-DS-W";
		RegisterClassW(&wc);
		wc.style         = CS_SAVEBITS|CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW;
		wc.lpszClassName = L"UPP-CLASS-SB-W";
		RegisterClassW(&wc);
		wc.style         = 0x20000|CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW|CS_SAVEBITS;
		wc.lpszClassName = L"UPP-CLASS-SB-DS-W";
		RegisterClassW(&wc);
	}

	ILOG("RegisterClassA");
	WNDCLASS  wc;
	Zero(wc);
	wc.style         = CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW;
	wc.lpfnWndProc   = (WNDPROC)Ctrl::WndProc;
	wc.hInstance     = hInstance;
	wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = IsWinVista() ? (HBRUSH)(COLOR_WINDOW+1) : (HBRUSH)NULL;
	wc.lpszClassName = L_("UPP-CLASS-A");
	RegisterClass(&wc);
	if(IsWinXP()) {
		wc.style         = 0x20000|CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW;
		wc.lpszClassName = L_("UPP-CLASS-DS-A");
		RegisterClass(&wc);
	}
	wc.style         = CS_SAVEBITS|CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW;
	wc.lpszClassName = L_("UPP-CLASS-SB-A");
	RegisterClass(&wc);
	if(IsWinXP()) {
		wc.style         = 0x20000|CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW|CS_SAVEBITS;
		wc.lpszClassName = L_("UPP-CLASS-SB-DS-A");
		RegisterClass(&wc);
	}
	wc.style         = 0;
	wc.lpszClassName = L_("UPP-TIMER");
	wc.hCursor       = NULL;
	wc.lpfnWndProc   = &Ctrl::UtilityProc;
	RegisterClass(&wc);

	ILOG("InitTimer");
	InitTimer();
	ILOG("SetTimer");
	utilityHWND = CreateWindow(L_("UPP-TIMER"), L_(""), WS_OVERLAPPED,
		CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
		NULL, NULL, hInstance, NULL);
	SetTimer(utilityHWND, 1, 10, NULL);
	ILOG("Windows");
	Windows(); //?? TRC: what's the use of this?

	ReSkin();

	OleInitialize(NULL);

/* TRC 05/11/14: moved to GuiSleep to avoid thread creation in OCX DllMain
	DWORD dummy;
	OverwatchThread = CreateThread(NULL, 0x100000, Win32OverwatchThread, NULL, 0, &dummy);
	ExitLoopEvent().Wait();
*/

// TRC 05/11/18: pSetLayeredWindowAttributes moved to GLOBAL_VAR (see below) to make OCX initialization simpler

	Csizeinit();
#undef ILOG

	if(IsWin7())
		GlobalBackPaint();
}
int main(int argc, char *argv[])
{
    if (argc < 4) {
        g_critical(L_("Expecting 3 arguments."));
        return 1;
    } else {
        GtkLabel *lbl;
        GladeXML *glade_xml;
        GError *err = NULL;
        GConfClient *gconf;
        gboolean keep_password;
        gchar *password;
        const gchar *gconf_keep_password;
        const gchar *gconf_password;
        gtk_init(&argc, &argv);
        gconf_password = g_getenv("PPP_GCONF_PASSWORD");
        gconf_keep_password = g_getenv("PPP_GCONF_KEEP_PASSWORD");
        if (!gconf_password || !gconf_keep_password) {
            g_critical(L_("Environment variables not set."));
            exit(1);
        }
        if (argv[3] != NULL) {
            output_file_descriptor = atoi(argv[3]);
        }
        gconf = gconf_client_get_default();
        keep_password = gconf_client_get_bool(gconf, gconf_keep_password, &err);

        /* user has password in database, spit it out */
        if (!err && keep_password) {
            password = gconf_client_get_string(gconf, gconf_password, &err);
            if (!err && password) {
                int len = strlen(password);

                if (write(output_file_descriptor, password, len) != len) {
                    g_warning(L_("could not write to file descriptor\n"));
                }
                /* all went fine, say bye */
                return 0;
            }
        }

        glade_init();
        glade_xml =
            glade_xml_new(BR_DATADIR("/gnome-ppx/ppp_get_password.glade"), NULL,
                          NULL);
        glade_xml_signal_autoconnect(glade_xml);

        password_entry =
            GTK_ENTRY(glade_xml_get_widget
                      (glade_xml, "gtk_entry_password"));
        lbl =
            GTK_LABEL(glade_xml_get_widget
                      (glade_xml, "msg_label"));
        g_object_unref(glade_xml);

        username = argv[1];
        server = argv[2];

        change_gtk_label(lbl);
        gtk_main();
    }

    return ret;
}
示例#29
0
void Parameters::parse_options(int argc, char* argv[])
{
    unsigned log_level = 2;
    std::string log_file;

    po::options_description desc("Allowed options");
    auto desc_add = desc.add_options();
    desc_add("version,V", "print version string");
    desc_add("help,h", "produce help message");
    desc_add("log-level,l", po::value<unsigned>(&log_level),
             "set the log level (default:2, all:0)");
    desc_add("log-file,L", po::value<std::string>(&log_file),
             "name of target log file");
    desc_add("client-index,c", po::value<int32_t>(&client_index_),
             "index of this executable in the list of processor tasks");
    desc_add("analyze-pattern,a",
             po::value<bool>(&analyze_)->implicit_value(true),
             "enable/disable pattern check");
    desc_add("benchmark,b", po::value<bool>(&benchmark_)->implicit_value(true),
             "run benchmark test only");
    desc_add("verbose,v", po::value<size_t>(&verbosity_),
             "set output verbosity");
    desc_add("shm-identifier,s", po::value<std::string>(&shm_identifier_),
             "shared memory identifier used for receiving timeslices");
    desc_add("input-archive,i", po::value<std::string>(&input_archive_),
             "name of an input file archive to read");
    desc_add("output-archive,o", po::value<std::string>(&output_archive_),
             "name of an output file archive to write");
    desc_add("publish,P", po::value<std::string>(&publish_address_)
                              ->implicit_value("tcp://*:5556"),
             "enable timeslice publisher on given address");
    desc_add("subscribe,S", po::value<std::string>(&subscribe_address_)
                                ->implicit_value("tcp://localhost:5556"),
             "subscribe to timeslice publisher on given address");
    desc_add("maximum-number,n", po::value<uint64_t>(&maximum_number_),
             "set the maximum number of microslices to process (default: "
             "unlimited)");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help") != 0u) {
        std::cout << desc << std::endl;
        exit(EXIT_SUCCESS);
    }

    if (vm.count("version") != 0u) {
        std::cout << "tsclient, version 0.0" << std::endl;
        exit(EXIT_SUCCESS);
    }

    logging::add_console(static_cast<severity_level>(log_level));
    if (vm.count("log-file")) {
        L_(info) << "Logging output to " << log_file;
        logging::add_file(log_file, static_cast<severity_level>(log_level));
    }

    size_t input_sources = vm.count("shm-identifier") +
                           vm.count("input-archive") + vm.count("subscribe");
    if (input_sources == 0 && !benchmark_) {
        throw ParametersException("no input source specified");
    }
    if (input_sources > 1) {
        throw ParametersException("more than one input source specified");
    }
}
示例#30
0
Application::Application(Parameters const& par) : par_(par)
{

    // Source setup
    if (!par_.input_shm.empty()) {
        L_(info) << "using shared memory as data source: " << par_.input_shm;

        shm_device_ = std::make_shared<flib_shm_device_client>(par_.input_shm);

        if (par_.channel_idx < shm_device_->num_channels()) {
            data_source_.reset(
                new flib_shm_channel_client(shm_device_, par_.channel_idx));

        } else {
            throw std::runtime_error("shared memory channel not available");
        }
    } else if (par_.use_pattern_generator) {
        L_(info) << "using pattern generator as data source";

        constexpr uint32_t typical_content_size = 10000;
        constexpr std::size_t desc_buffer_size_exp = 19; // 512 ki entries
        constexpr std::size_t data_buffer_size_exp = 27; // 128 MiB

        switch (par_.pattern_generator) {
        case 1:
            data_source_.reset(new FlibPatternGenerator(
                data_buffer_size_exp, desc_buffer_size_exp, par_.channel_idx,
                typical_content_size, true, true));
            break;
        case 2:
            data_source_.reset(new EmbeddedPatternGenerator(
                data_buffer_size_exp, desc_buffer_size_exp, par_.channel_idx,
                typical_content_size, true, true));
            break;
        default:
            throw std::runtime_error("pattern generator type not available");
        }
    }

    if (data_source_) {
        source_.reset(new fles::MicrosliceReceiver(*data_source_));
    } else if (!par_.input_archive.empty()) {
        source_.reset(new fles::MicrosliceInputArchive(par_.input_archive));
    }

    // Sink setup
    if (par_.analyze) {
        sinks_.push_back(std::unique_ptr<fles::MicrosliceSink>(
            new MicrosliceAnalyzer(1000000, std::cout, "", par_.channel_idx)));
    }

    if (par_.dump_verbosity > 0) {
        sinks_.push_back(std::unique_ptr<fles::MicrosliceSink>(
            new MicrosliceDumper(std::cout, par_.dump_verbosity)));
    }

    if (!par_.output_archive.empty()) {
        sinks_.push_back(std::unique_ptr<fles::MicrosliceSink>(
            new fles::MicrosliceOutputArchive(par_.output_archive)));
    }

    if (!par_.output_shm.empty()) {
        L_(info) << "providing output in shared memory: " << par_.output_shm;

        constexpr std::size_t desc_buffer_size_exp = 19; // 512 ki entries
        constexpr std::size_t data_buffer_size_exp = 27; // 128 MiB

        output_shm_device_.reset(new flib_shm_device_provider(
            par_.output_shm, 1, data_buffer_size_exp, desc_buffer_size_exp));
        InputBufferWriteInterface* data_sink =
            output_shm_device_->channels().at(0);
        sinks_.push_back(std::unique_ptr<fles::MicrosliceSink>(
            new fles::MicrosliceTransmitter(*data_sink)));
    }
}