Пример #1
0
void search(const board_t * board, int depth_max, double time_max) {

   char string[256];

   ASSERT(board_is_ok(board));
   ASSERT(depth_max>=1&&depth_max<DepthMax);
   ASSERT(time_max>=0.0);

   // engine

   Depth = 0;

   BestMove = MoveNone;
   BestValue = 0;
   line_clear(BestPV);

   NodeNb = 0;
   LeafNb = 0;
   Time = 0.0;

   Move = MoveNone;
   MovePos = 0;
   MoveNb = 0;

   // init

   uci_send_ucinewgame(Uci);
   uci_send_isready_sync(Uci);

   // position

   if (!board_to_fen(board,string,256)) ASSERT(false);
   engine_send(Engine,"position fen %s",string);

   // search

   engine_send_queue(Engine,"go");

   engine_send_queue(Engine," movetime %.0f",time_max*1000.0);
   engine_send_queue(Engine," depth %d",depth_max);

   engine_send(Engine,""); // newline

   // wait for feed-back

   while (true) {

      engine_get(Engine,string,256);

      if (false) {

      } else if (match(string,"bestmove * ponder *")) {

         BestMove = move_from_can(Star[0],board);
         ASSERT(BestMove!=MoveNone&&move_is_legal(BestMove,board));

         break;

      } else if (match(string,"bestmove *")) {

         BestMove = move_from_can(Star[0],board);
         ASSERT(BestMove!=MoveNone&&move_is_legal(BestMove,board));

         break;
      }
   }

   printf("\n");
}
Пример #2
0
double castelo_prior(SEXP beta, SEXP target, SEXP parents, SEXP children,
    int debuglevel) {

int i = 0, k = 0, t = 0, nnodes = 0, cur_arc = 0;
int nbeta = length(VECTOR_ELT(beta, 0));
int *temp = NULL, *aid = INTEGER(VECTOR_ELT(beta, 2));
double prior = 0, result = 0;
double *bkwd = REAL(VECTOR_ELT(beta, 4)), *fwd = REAL(VECTOR_ELT(beta, 3));
short int *adjacent = NULL;
SEXP nodes, try;

  /* get the node labels. */
  nodes = getAttrib(beta, BN_NodesSymbol);
  nnodes = length(nodes);

  /* match the target node. */
  PROTECT(try = match(nodes, target, 0));
  t = INT(try);
  UNPROTECT(1);

  /* find out which nodes are parents and which nodes are children. */
  adjacent = allocstatus(nnodes);

  PROTECT(try = match(nodes, parents, 0));
  temp = INTEGER(try);
  for (i = 0; i < length(try); i++)
    adjacent[temp[i] - 1] = PARENT;
  UNPROTECT(1);

  PROTECT(try = match(nodes, children, 0));
  temp = INTEGER(try);
  for (i = 0; i < length(try); i++)
    adjacent[temp[i] - 1] = CHILD;
  UNPROTECT(1);

  /* prior probabilities table lookup. */
  for (i = t + 1; i <= nnodes; i++) {

    /* compute the arc id. */
    cur_arc = UPTRI3(t, i, nnodes);

    /* look up the prior probability. */
    for (/*k,*/ prior = ((double)1/3); k < nbeta; k++) {

      /* arcs are ordered, so we can stop early in the lookup. */
      if (aid[k] > cur_arc)
        break;

      if (aid[k] == cur_arc) {

        switch(adjacent[i - 1]) {

          case PARENT:
            prior = bkwd[k];
            break;
          case CHILD:
            prior = fwd[k];
            break;
          default:
            prior = fmax2(0, 1 - bkwd[k] - fwd[k]);

        }/*SWITCH*/

        break;

      }/*THEN*/

    }/*FOR*/

    if (debuglevel > 0) {

      switch(adjacent[i - 1]) {

        case PARENT:
          Rprintf("  > found arc %s -> %s, prior pobability is %lf.\n",
            NODE(i - 1), NODE(t - 1), prior);
          break;
        case CHILD:
          Rprintf("  > found arc %s -> %s, prior probability is %lf.\n",
            NODE(t - 1), NODE(i - 1), prior);
          break;
        default:
          Rprintf("  > no arc between %s and %s, prior probability is %lf.\n",
            NODE(t - 1), NODE(i - 1), prior);

      }/*SWITCH*/

    }/*THEN*/

    /* move to log-scale and divide by the non-informative log(1/3), so that
     * the contribution of each arc whose prior has not been specified by the
     * user is zero; overflow is likely otherwise. */
    result += log(prior / ((double)1/3));

  }/*FOR*/

  return result;

}/*CASTELO_PRIOR*/

/* complete a prior as per Castelo & Siebes. */
SEXP castelo_completion(SEXP prior, SEXP nodes, SEXP learning)  {

int i = 0, k = 0, cur = 0, narcs1 = 0, narcs2 = 0, nnodes = length(nodes);
int *m1 = NULL, *m2 = NULL, *und = NULL, *aid = NULL, *poset = NULL, *id = NULL;
double *d1 = NULL, *d2 = NULL, *p = NULL;
SEXP df, arc_id, undirected, a1, a2, match1, match2, prob;
SEXP result, from, to, nid, dir1, dir2;

  /* compute numeric IDs for the arcs. */
  a1 = VECTOR_ELT(prior, 0);
  a2 = VECTOR_ELT(prior, 1);
  narcs1 = length(a1);
  PROTECT(match1 = match(nodes, a1, 0));
  PROTECT(match2 = match(nodes, a2, 0));
  m1 = INTEGER(match1);
  m2 = INTEGER(match2);
  PROTECT(arc_id = allocVector(INTSXP, narcs1));
  aid = INTEGER(arc_id);

  c_arc_hash(narcs1, nnodes, m1, m2, aid, NULL, FALSE);

  /* duplicates correspond to undirected arcs. */
  PROTECT(undirected = dupe(arc_id));
  und = INTEGER(undirected);

  /* extract the components from the prior. */
  prob = VECTOR_ELT(prior, 2);
  p = REAL(prob);

  /* count output arcs. */
  for (i = 0; i < narcs1; i++)
    narcs2 += 2 - und[i];
  narcs2 /= 2;

  /* allocate the columns of the return value. */
  PROTECT(from = allocVector(STRSXP, narcs2));
  PROTECT(to = allocVector(STRSXP, narcs2));
  PROTECT(nid = allocVector(INTSXP, narcs2));
  id = INTEGER(nid);
  PROTECT(dir1 = allocVector(REALSXP, narcs2));
  d1 = REAL(dir1);
  PROTECT(dir2 = allocVector(REALSXP, narcs2));
  d2 = REAL(dir2);

  /* sort the strength coefficients. */
  poset = alloc1dcont(narcs1);
  for (k = 0; k < narcs1; k++)
    poset[k] = k;
  R_qsort_int_I(aid, poset, 1, narcs1);

  for (i = 0, k = 0; i < narcs1; i++) {

    cur = poset[i];

#define ASSIGN(A1, A2, D1, D2) \
  SET_STRING_ELT(from,  k, STRING_ELT(A1, cur)); \
  SET_STRING_ELT(to,  k, STRING_ELT(A2, cur)); \
  id[k] = aid[i]; \
  D1[k] = p[cur]; \
  if ((und[cur] == TRUE) && (i < narcs1 - 1)) \
    D2[k] = p[poset[++i]]; \
  else \
    D2[k] = (1 - D1[k])/2;

    /* copy the node labels. */
    if (m1[cur] < m2[cur]) {

      ASSIGN(a1, a2, d1, d2);

    }/*THEN*/
    else {

      ASSIGN(a2, a1, d2, d1);

    }/*ELSE*/

    /* check the probabilities do not exceed 1; fail only for large errors. */
    if (d1[k] + d2[k] > 1) {

      if (d1[k] + d2[k] < 1 + 2 * MACHINE_TOL) {

        d1[k] = d1[k] / (d1[k] + d2[k]);
        d2[k] = d2[k] / (d1[k] + d2[k]);

      }/*THEN*/
      else {

        UNPROTECT(9);

        error("the probabilities for arc %s -> %s sum to %lf.",
          CHAR(STRING_ELT(from, k)), CHAR(STRING_ELT(to, k)), d1[k] + d2[k]);

      }/*ELSE*/

    }/*THEN*/

    /* bound the probability of not including an arc away from zero, structure
     * learning otherwise fails when starting from the empty graph and gets
     * stuck very easily in general. */
    if (isTRUE(learning) && (fabs(1 - d1[k] - d2[k]) < MACHINE_TOL)) {

      d1[k] = d1[k] - MACHINE_TOL;
      d2[k] = d2[k] - MACHINE_TOL;

    }/*THEN*/

    /* move to the next arc. */
    k++;

  }/*FOR*/

  /* set up the return value. */
  PROTECT(result = allocVector(VECSXP, 5));
  SET_VECTOR_ELT(result, 0, from);
  SET_VECTOR_ELT(result, 1, to);
  SET_VECTOR_ELT(result, 2, nid);
  SET_VECTOR_ELT(result, 3, dir1);
  SET_VECTOR_ELT(result, 4, dir2);
  setAttrib(result, R_NamesSymbol,
    mkStringVec(5, "from", "to", "aid", "fwd", "bkwd"));
  PROTECT(df = minimal_data_frame(result));

  UNPROTECT(11);

  return df;

}/*CASTELO_COMPLETION*/
Пример #3
0
/** Interpret \a client as a client specifier and show which Client
 * block(s) match that client.
 *
 * The client specifier may contain an IP address, hostname, listener
 * port, or a combination of those separated by commas.  IP addresses
 * and hostnamese may be preceded by "username@"; the last given
 * username will be used for the match.
 *
 * @param[in] client Client specifier.
 * @return Matching Client block structure.
 */
struct ConfItem *conf_debug_iline(const char *client)
{
  struct irc_in_addr address;
  struct ConfItem *aconf;
  struct DenyConf *deny;
  char *sep;
  unsigned short listener;
  char username[USERLEN+1], hostname[HOSTLEN+1], realname[REALLEN+1];

  /* Initialize variables. */
  listener = 0;
  memset(&address, 0, sizeof(address));
  memset(&username, 0, sizeof(username));
  memset(&hostname, 0, sizeof(hostname));
  memset(&realname, 0, sizeof(realname));

  /* Parse client specifier. */
  while (*client) {
    struct irc_in_addr tmpaddr;
    long tmp;

    /* Try to parse as listener port number first. */
    tmp = strtol(client, &sep, 10);
    if (tmp && (*sep == '\0' || *sep == ',')) {
      listener = tmp;
      client = sep + (*sep != '\0');
      continue;
    }

    /* Maybe username@ before an IP address or hostname? */
    tmp = strcspn(client, ",@");
    if (client[tmp] == '@') {
      if (tmp > USERLEN)
        tmp = USERLEN;
      ircd_strncpy(username, client, tmp);
      /* and fall through */
      client += tmp + 1;
    }

    /* Looks like an IP address? */
    tmp = ircd_aton(&tmpaddr, client);
    if (tmp && (client[tmp] == '\0' || client[tmp] == ',')) {
        memcpy(&address, &tmpaddr, sizeof(address));
        client += tmp + (client[tmp] != '\0');
        continue;
    }

    /* Realname? */
    if (client[0] == '$' && client[1] == 'R') {
      client += 2;
      for (tmp = 0; *client != '\0' && *client != ',' && tmp < REALLEN; ++client, ++tmp) {
        if (*client == '\\')
          realname[tmp] = *++client;
        else
          realname[tmp] = *client;
      }
      continue;
    }

    /* Else must be a hostname. */
    tmp = strcspn(client, ",");
    if (tmp > HOSTLEN)
      tmp = HOSTLEN;
    ircd_strncpy(hostname, client, tmp);
    client += tmp + (client[tmp] != '\0');
  }

  /* Walk configuration to find matching Client block. */
  for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
    if (aconf->status != CONF_CLIENT)
      continue;
    if (aconf->address.port && aconf->address.port != listener) {
      fprintf(stdout, "Listener port mismatch: %u != %u\n", aconf->address.port, listener);
      continue;
    }
    if (aconf->username && match(aconf->username, username)) {
      fprintf(stdout, "Username mismatch: %s != %s\n", aconf->username, username);
      continue;
    }
    if (aconf->host && match(aconf->host, hostname)) {
      fprintf(stdout, "Hostname mismatch: %s != %s\n", aconf->host, hostname);
      continue;
    }
    if ((aconf->addrbits >= 0)
        && !ipmask_check(&address, &aconf->address.addr, aconf->addrbits)) {
      fprintf(stdout, "IP address mismatch: %s != %s\n", aconf->name, ircd_ntoa(&address));
      continue;
    }
    fprintf(stdout, "Match! username=%s host=%s ip=%s class=%s maxlinks=%u password=%s\n",
            (aconf->username ? aconf->username : "******"),
            (aconf->host ? aconf->host : "(null)"),
            (aconf->name ? aconf->name : "(null)"),
            ConfClass(aconf), aconf->maximum,
            (aconf->passwd ? aconf->passwd : "(null)"));
    break;
  }

  /* If no authorization, say so and exit. */
  if (!aconf)
  {
    fprintf(stdout, "No authorization found.\n");
    return NULL;
  }

  /* Look for a Kill block with the user's name on it. */
  for (deny = denyConfList; deny; deny = deny->next) {
    if (deny->usermask && match(deny->usermask, username))
      continue;
    if (deny->realmask && match(deny->realmask, realname))
      continue;
    if (deny->bits > 0) {
      if (!ipmask_check(&address, &deny->address, deny->bits))
        continue;
    } else if (deny->hostmask && match(deny->hostmask, hostname))
      continue;

    /* Looks like a match; report it. */
    fprintf(stdout, "Denied! usermask=%s realmask=\"%s\" hostmask=%s (bits=%u)\n",
            deny->usermask ? deny->usermask : "(null)",
            deny->realmask ? deny->realmask : "(null)",
            deny->hostmask ? deny->hostmask : "(null)",
            deny->bits);
  }

  return aconf;
}
Пример #4
0
static mowgli_node_t *charybdis_next_matching_ban(channel_t *c, user_t *u, int type, mowgli_node_t *first)
{
	chanban_t *cb;
	mowgli_node_t *n;
	char hostbuf[NICKLEN+USERLEN+HOSTLEN];
	char realbuf[NICKLEN+USERLEN+HOSTLEN];
	char ipbuf[NICKLEN+USERLEN+HOSTLEN];
	char strippedmask[NICKLEN+USERLEN+HOSTLEN+CHANNELLEN+2];
	char *p;
	bool negate, matched;
	int exttype;
	channel_t *target_c;

	snprintf(hostbuf, sizeof hostbuf, "%s!%s@%s", u->nick, u->user, u->vhost);
	snprintf(realbuf, sizeof realbuf, "%s!%s@%s", u->nick, u->user, u->host);
	/* will be nick!user@ if ip unknown, doesn't matter */
	snprintf(ipbuf, sizeof ipbuf, "%s!%s@%s", u->nick, u->user, u->ip);

	MOWGLI_ITER_FOREACH(n, first)
	{
		cb = n->data;

		if (cb->type != type)
			continue;

		/*
		 * strip any banforwards from the mask. (SRV-73)
		 * charybdis itself doesn't support banforward but i don't feel like copying
		 * this stuff into ircd-seven and it is possible that charybdis may support them
		 * one day.
		 *   --nenolod
		 */
		mowgli_strlcpy(strippedmask, cb->mask, sizeof strippedmask);
		p = strrchr(strippedmask, '$');
		if (p != NULL && p != strippedmask)
			*p = 0;

		if ((!match(strippedmask, hostbuf) || !match(strippedmask, realbuf) || !match(strippedmask, ipbuf) || !match_cidr(strippedmask, ipbuf)))
			return n;
		if (strippedmask[0] == '$')
		{
			p = strippedmask + 1;
			negate = *p == '~';
			if (negate)
				p++;
			exttype = *p++;
			if (exttype == '\0')
				continue;
			/* check parameter */
			if (*p++ != ':')
				p = NULL;
			switch (exttype)
			{
				case 'a':
					matched = u->myuser != NULL && !(u->myuser->flags & MU_WAITAUTH) && (p == NULL || !match(p, entity(u->myuser)->name));
					break;
				case 'c':
					if (p == NULL)
						continue;
					target_c = channel_find(p);
					if (target_c == NULL || (target_c->modes & (CMODE_PRIV | CMODE_SEC)))
						continue;
					matched = chanuser_find(target_c, u) != NULL;
					break;
				case 'o':
					matched = is_ircop(u);
					break;
				case 'r':
					if (p == NULL)
						continue;
					matched = !match(p, u->gecos);
					break;
				case 's':
					if (p == NULL)
						continue;
					matched = !match(p, u->server->name);
					break;
				case 'x':
					if (p == NULL)
						continue;
					matched = extgecos_match(p, u);
					break;
				default:
					continue;
			}
			if (negate ^ matched)
				return n;
		}
	}
Пример #5
0
void match(QNFAMatchContext *lexer, const QChar *d, int length, QNFAMatchNotifier notify)
{
	if ( !lexer || !lexer->context )
	{
		//qWarning("get off you scum!");
		return;
	}
	
	// restore message buffering
	
	notify.clear();
	
	int olvls = lexer->parents.count(),
		nlvls = 0,
		lvls = olvls;
	
	if ( lvls )
		notify.startBuffering();
	
	//
	
	quint16 c = 0;
	const QChar *di = d;
	QNFA *chain = 0, *start = 0;
	int index = 0, lastCxt = 0, len, idx;
	bool bFound, bEscape = false, bEscaped = false;
	bool wPrev = false, wCur = false;
	
	while ( index < length )
	{
		bFound = false;
		bEscaped = false;
		//bEscape &= !lexer->meaningless.contains(d[index].unicode());
		
		//while ( lexer->meaningless.contains(d[index].unicode()) && ((index + 1) < length) )
		//	++index;
		
		if ( index >= length )
			break;
		
		c = di->unicode();
		
		wCur = isWord(*di);

		int plainIndex = -1, plainMatch, plainLength;
		
		// try fast plain matching
		if ( !(wPrev && wCur) )
		{
			//qDebug("trying plain...");
			
			//len = 0;
			idx = index;
			QCharTree::const_iterator it, match, end;
			
			it = lexer->context->tree.constFind(c);
			
			if ( it != lexer->context->tree.constEnd() )
			{
				//qDebug("plain on %c", c);
				do
				{
					++di;
					++idx;
					
					end = it->next.constEnd();
					match = it->next.constFind(0);
					
					if ( idx < length )
					{
						c = di->unicode();
						it = it->next.constFind(c);
					} else {
						it = end;
					}
					
					if ( it == end )
					{
						if ( (match != end) && !isWord(*di) )
						{
							//word boundary found
							// corresponding token end found
							wPrev = isWord(*(di - 1));
							bFound = true;
							if ( match->value.action & 0x40000000 )
							{
								// try regexps before notifying
								plainIndex = index;
								plainLength = idx - index;
								plainMatch = match->value.action;
								//qDebug("ambiguity.");
							} else {
								notify(index, idx - index, match->value.action);
								index = idx;
							}
							//qDebug("next step : %c", d[index].toLatin1());
							//bMonitor = true;
						}
						
						break;
					}
				} while ( idx < length ) ;
				
				if ( bFound )
				{
					bEscape = false;

					if ( plainIndex == -1 )
						continue;
					
					bFound = false;
				}

				di -= idx - index;
			}
		}
		
		// fallback on regexp-like NFA-based matching
		QNFABranch* children = lexer->context->out.branch;
		
		if ( children )
		{
			//qDebug("trying %i sub nfas on %c", children->count(), d[index].toLatin1());
			int max = children->count();
			
			for ( quint16 i = 0; i < max; ++i )
			{
				len = 0;
				idx = index;
				start = chain = children->at(i);
				
				//qDebug("%ith attempt on %c", i, d[index + len].toLatin1());
				
				while ( (idx < length) || (chain->type & Match) )
				{
					bEscaped = false;
					
					if ( chain->type & Match )
					{
						if (
								(chain->assertion & WordEnd)
							&&
								(idx < length)
							&&
								isWord(*di)
							&&
								isWord(*(di - 1))
							)
						{
							//qDebug("end assertion failed...");
							break;
						}
						
						//qDebug("matched to end");
						
						if ( chain->type & CxtBeg )
						{
							//qDebug("entering context : 0x%x", chain);
							
							++nlvls;
							
							bool notifySub = notify.bufferLevel();
							
							if ( notifySub )
							{
								// pop one message buffer
								notify.stopBuffering();
							}
							
							// notify content of previous context until nest
							notify(lastCxt, index - lastCxt, lexer->context->actionid | 0x80000000);
							
							if ( notifySub )
							{
								// notify sub matches so far to avoid tricky handling later on
								notify.flush();
								
								//notify.startBuffering();
							}
							
							// notify begin marker
							notify(index, len, start->actionid ? start->actionid : chain->actionid);
							
							// update context stack
							lexer->parents.push(lexer->context);
							lexer->context = chain;
							
							// update nest index
							lastCxt = idx;
							
							// push a message buffer
							notify.startBuffering();
							
						} else if ( chain->type & CxtEnd ) {
							//qDebug("leaving context :");
							
							if ( lexer->parents.isEmpty() )
								qFatal("context nesting problem");
							
							if ( bEscape )
							{
								// not really end : escape found...
								
								bEscape = false;
								bEscaped = true;
							} else {
								
								if ( nlvls )
									--nlvls;
								else
									--lvls;
								
								// pop one message buffer
								notify.stopBuffering();
								
								// notify context content from last nest
								notify(lastCxt, index - lastCxt, lexer->context->actionid | 0x80000000);
								
								// flush sub matches
								notify.flush();
								
								// update context stack
								lexer->context = lexer->parents.pop();
								
								if ( lexer->parents.count() )
									notify.startBuffering();
								
								// update nest index
								lastCxt = idx;
								
								// notify end marker
								notify(index, len, chain->actionid);
								
								//qDebug("cxt notif...");
								
								if ( chain->type & Exclusive )
									index = idx;
								
								--index;
								--di;
								
								bFound = true;
								break;
							}
						} else if ( chain->type & CxtEsc )  {
							//qDebug("matched %s", qPrintable(QString(index, len)));
							
							//notify(index, len, chain->actionid);
							bEscape = !bEscape;
						} else {
							//qDebug("matched %s", qPrintable(QString(d + index, len)));
							
							if ( plainIndex != -1 && plainLength >= len )
							{
								break;
							}
							
							notify(index, len, chain->actionid);
							bEscape = false;
						}
						
						bFound = true;
						index = idx;
						--index;
						--di;
						
						//qDebug("next step : %c", d[index + 1].toLatin1());
						//bMonitor = true;
						
						break;
					} else {
						// "regular" nfa match (no match yet...)
						
						if (
								(chain->assertion & WordStart)
							&&
								(idx >= 1)
							&&
								(
									isWord(*(di - 1))
								&&
									isWord(*di)
								)
							)
						{
							//qDebug("beg assertion failed...");
							
							break;
						}
						
						QChar cc = *di;
						bool found = match(cc, chain);
						
						if (
								!(chain->assertion & ZeroOrOne)
							&&
								!(chain->assertion & ZeroOrMore)
							&&
								!found
							)
						{
							//if ( cc.toLatin1() == ')' )
							//	qDebug("mismatch : %c != %c", cc.toLatin1(), chain->c.at(0));
							
							break;
						}
						
						if ( found )
						{
							//qDebug("%c", d[index + len].toLatin1());
							
							if (
									(chain->assertion & OneOrMore)
								||
									(chain->assertion & ZeroOrMore)
								)
							{
								do
								{
									++di;
									++len;
									++idx;
								} while (
											(idx < length)
										&&
											match(*di, chain)
										);
								
							} else {
								++len;
								++idx;
								++di;
							}
							
						} else {
							//qDebug("! %c", d[index + len].toLatin1());
						}
						
						chain = chain->out.next;
					}
				}
				
				if ( bFound )
					break;
				
				di -= len;
			}
		}
		
		if ( !bFound )
		{
			if ( plainIndex != -1 )
			{
				notify(plainIndex, plainLength, plainMatch);
				index = plainIndex + plainLength;
				di += plainLength;
				continue;
			}

			bEscape = false;
			//++index;
			wPrev = wCur;
		} else {
			wPrev = isWord(*di);
		}
		
		++index;
		++di;
	}
	
	// flush messages
	
	if ( !notify.bufferLevel() )
		return;
	
	//qDebug("%i context nests", notify.bufferLevel());
	//qDebug("[%i;+00[ : 0x%x", lastCxt, lexer->context->actionid | 0x80000000);
	
	// pop down one buffer
	notify.stopBuffering();
	
	// notify overlapping context so far
	notify(lastCxt, length - lastCxt, lexer->context->actionid | 0x80000000);
	
	// notify sub matches
	notify.flush();
	
	// make sure we leave a blank notifier...
	notify.clear();
	
	// preserve escape power...
	if ( bEscaped )
		return;
	
	// some existing left AND new one(s)
	if ( (olvls == lvls) && nlvls )
		++lvls;
	
	// close stay-on-line contexts, if any
	QStack<QNFA*>::iterator it = lexer->parents.begin() + lvls;
	
	while ( it != lexer->parents.end() )
	{
		if ( (*it)->type & StayOnLine )
		{
			//qDebug("staid...");
			it = lexer->parents.erase(it);
		} else {
			++it;
		}
	}
	
	if ( (lexer->context->type & StayOnLine) && nlvls && lexer->parents.count() )
		lexer->context = lexer->parents.pop();
	
}
Пример #6
0
static void
process()
{
/*
    Loop through the program text, looking for patterns.
*/
    int c, i, left = 0;
    line_nr = 1;
    c = get(FALSE);
    for (;;) {
        if (c == EOF) {
            break;
        } else if (c == '\'' || c == '"' || c == '`') {
            emit(c);
            string(c, FALSE);
            c = 0;
/*
    The most complicated case is the slash. It can mean division or a regexp
    literal or a line comment or a block comment. A block comment can also be
    a pattern to be expanded.
*/
        } else if (c == '/') {
/*
    A slash slash comment skips to the end of the file.
*/
            if (peek() == '/') {
                emit('/');
                for (;;) {
                    c = get(TRUE);
                    if (c == '\n' || c == '\r' || c == EOF) {
                        break;
                    }
                }
                c = get(FALSE);
/*
    The first component of a slash star comment might be the tag.
*/
            } else {
                if (peek() == '*') {
                    get(FALSE);
                    for (i = 0; i < MAX_TAG_LENGTH; i += 1) {
                        c = get(FALSE);
                        if (!is_alphanum(c)) {
                            break;
                        }
                        tag[i] = (char)c;
                    }
                    tag[i] = 0;
                    unget(c);
/*
    Did the tag match something?
*/
                    i = (i == 0)
                        ? -1
                        : match();
                    if (i >= 0) {
                        expand(i);
                        c = get(FALSE);
                    } else {
/*
    If the tag didn't match, then echo the comment.
*/
                        emits("/*");
                        emits(tag);
                        for (;;) {
                            if (c == EOF) {
                                error("unterminated comment.");
                            }
                            if (c == '/') {
                                c = get(TRUE);
                                if (c == '*') {
                                    error("nested comment.");
                                }
                            } else if (c == '*') {
                                c = get(TRUE);
                                if (c == '/') {
                                    break;
                                }
                            } else {
                                c = get(TRUE);
                            }
                        }
                        c = get(FALSE);
                    }
                } else {
                    emit('/');
/*
    We are looking at a single slash. Is it a division operator, or is it the
    start of a regexp literal? It is not possible to tell for sure without doing
    a complete parse of the program, and we are not going to do that. Instead,
    we are adopting the convention that a regexp literal must have one of a
    small set of characters to its left.
*/
                    if (pre_regexp(left)) {
                        regexp(FALSE);
                    }
                    left = '/';
                    c = get(FALSE);
                }
            }
        } else {
/*
    The character was nothing special, so just echo it.
    If it wasn't whitespace, remember it as the character to the left of the
    next character.
*/
            emit(c);
            if (c > ' ') {
                left = c;
            }
            c = get(FALSE);
        }
    }
}
Пример #7
0
static const char *match (MatchState *ms, const char *s, const char *p) {
  if (ms->matchdepth-- == 0)
    luaL_error(ms->L, "pattern too complex");
  init: /* using goto's to optimize tail recursion */
  if (p != ms->p_end) {  /* end of pattern? */
    switch (*p) {
      case '(': {  /* start capture */
        if (*(p + 1) == ')')  /* position capture? */
          s = start_capture(ms, s, p + 2, CAP_POSITION);
        else
          s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
        break;
      }
      case ')': {  /* end capture */
        s = end_capture(ms, s, p + 1);
        break;
      }
      case '$': {
        if ((p + 1) != ms->p_end)  /* is the `$' the last char in pattern? */
          goto dflt;  /* no; go to default */
        s = (s == ms->src_end) ? s : NULL;  /* check end of string */
        break;
      }
      case L_ESC: {  /* escaped sequences not in the format class[*+?-]? */
        switch (*(p + 1)) {
          case 'b': {  /* balanced string? */
            s = matchbalance(ms, s, p + 2);
            if (s != NULL) {
              p += 4; goto init;  /* return match(ms, s, p + 4); */
            }  /* else fail (s == NULL) */
            break;
          }
          case 'f': {  /* frontier? */
            const char *ep; char previous;
            p += 2;
            if (*p != '[')
              luaL_error(ms->L, "missing " LUA_QL("[") " after "
                                 LUA_QL("%%f") " in pattern");
            ep = classend(ms, p);  /* points to what is next */
            previous = (s == ms->src_init) ? '\0' : *(s - 1);
            if (!matchbracketclass(uchar(previous), p, ep - 1) &&
               matchbracketclass(uchar(*s), p, ep - 1)) {
              p = ep; goto init;  /* return match(ms, s, ep); */
            }
            s = NULL;  /* match failed */
            break;
          }
          case '0': case '1': case '2': case '3':
          case '4': case '5': case '6': case '7':
          case '8': case '9': {  /* capture results (%0-%9)? */
            s = match_capture(ms, s, uchar(*(p + 1)));
            if (s != NULL) {
              p += 2; goto init;  /* return match(ms, s, p + 2) */
            }
            break;
          }
          default: goto dflt;
        }
        break;
      }
      default: dflt: {  /* pattern class plus optional suffix */
        const char *ep = classend(ms, p);  /* points to optional suffix */
        /* does not match at least once? */
        if (!singlematch(ms, s, p, ep)) {
          if (*ep == '*' || *ep == '?' || *ep == '-') {  /* accept empty? */
            p = ep + 1; goto init;  /* return match(ms, s, ep + 1); */
          }
          else  /* '+' or no suffix */
            s = NULL;  /* fail */
        }
        else {  /* matched once */
          switch (*ep) {  /* handle optional suffix */
            case '?': {  /* optional */
              const char *res;
              if ((res = match(ms, s + 1, ep + 1)) != NULL)
                s = res;
              else {
                p = ep + 1; goto init;  /* else return match(ms, s, ep + 1); */
              }
              break;
            }
            case '+':  /* 1 or more repetitions */
              s++;  /* 1 match already done */
              /* go through */
            case '*':  /* 0 or more repetitions */
              s = max_expand(ms, s, p, ep);
              break;
            case '-':  /* 0 or more repetitions (minimum) */
              s = min_expand(ms, s, p, ep);
              break;
            default:  /* no suffix */
              s++; p = ep; goto init;  /* return match(ms, s + 1, ep); */
          }
        }
        break;
      }
    }
  }
  ms->matchdepth++;
  return s;
}
Пример #8
0
void JudgeTask::doRun()
{
    ILogger *logger = LoggerFactory::getLogger(LoggerId::AppInitLoggerId);

    OJString infoBuffer;

    FormatString(infoBuffer, OJStr("[JudgeTask] task %d"), Input.SolutionID);
    logger->logInfo(infoBuffer);

    //编译
    if(!compile())
    {
        return;
    }

    //搜索测试数据

    OJString path;
    FormatString(path, OJStr("%s/%d"), AppConfig::Path::TestDataPath.c_str(), Input.ProblemID);
    
    DebugMessage(OJStr("[JudgeTask] %d search path: %s"), Input.SolutionID, path.c_str());

    //TODO: 根据是否specialJudge,决定搜索.out还是.in文件。
    FileTool::FileNameList fileList;
    FileTool::GetSpecificExtFiles(fileList, path, OJStr(".out"), true);

    OJUInt32_t testCount = fileList.size();
    if(testCount <= 0)//没有测试数据
    {
        output_.Result = AppConfig::JudgeCode::SystemError;

        FormatString(infoBuffer, OJStr("[JudgeTask] not found test data for solution %d problem %d."),
            Input.SolutionID, Input.ProblemID);
        logger->logError(infoBuffer);
        return;
    }

    //测试多组数据
    OJUInt32_t accepted = 0;
    for(OJUInt32_t i=0; i<testCount; ++i)
    {
        answerOutputFile_ = fileList[i];
        answerInputFile_ = FileTool::RemoveFileExt(answerOutputFile_);
        answerInputFile_ += OJStr(".in");

        DebugMessage(OJStr("[JudgeTask] %d input file: %s"), 
            Input.SolutionID, answerInputFile_.c_str());
        DebugMessage(OJStr("[JudgeTask] %d output file: %s"), 
            Input.SolutionID, answerOutputFile_.c_str());

        if(!safeRemoveFile(userOutputFile_))
        {
            output_.Result = AppConfig::JudgeCode::SystemError;
            break;
        }

        if(!excute())
        {
            break;
        }
            
        if(!match())
        {
            break;
        }
        
        ++accepted;
    }

    output_.PassRate = float(accepted)/testCount;
}
Пример #9
0
static const char *
match(MatchState * ms, const char *s, const char *p)
{
init:                          /* using goto's to optimize tail recursion */
  switch (*p) {
  case '(':
    {                           /* start capture */
      if (*(p + 1) == ')')      /* position capture? */
        return start_capture(ms, s, p + 2, CAP_POSITION);
      else
        return start_capture(ms, s, p + 1, CAP_UNFINISHED);
    }
  case ')':
    {                           /* end capture */
      return end_capture(ms, s, p + 1);
    }
  case ESC:
    {
      switch (*(p + 1)) {
      case 'b':
        {                       /* balanced string? */
          s = matchbalance(ms, s, p + 2);
          if (s == NULL)
            return NULL;
          p += 4;
          goto init;            /* else return match(ms, s, p+4); */
        }
      case 'f':
        {                       /* frontier? */
          const char *ep;
          char previous;
          p += 2;
          if (*p != '[')
            luaL_error(ms->L, "missing `[' after `%%f' in pattern");
          ep = luaI_classend(ms, p);    /* points to what is next */
          previous = (s == ms->src_init) ? '\0' : *(s - 1);
          if (matchbracketclass(uchar(previous), p, ep - 1) || !matchbracketclass(uchar(*s), p, ep - 1))
            return NULL;
          p = ep;
          goto init;            /* else return match(ms, s, ep); */
        }
      default:
        {
          if (isdigit(uchar(*(p + 1)))) {       /* capture results (%0-%9)? */
            s = match_capture(ms, s, *(p + 1));
            if (s == NULL)
              return NULL;
            p += 2;
            goto init;          /* else return match(ms, s, p+2) */
          }
          goto dflt;            /* case default */
        }
      }
    }
  case '\0':
    {                           /* end of pattern */
      return s;                 /* match succeeded */
    }
  case '$':
    {
      if (*(p + 1) == '\0')     /* is the `$' the last char in pattern? */
        return (s == ms->src_end) ? s : NULL;   /* check end of string */
      else
        goto dflt;
    }
  default:
  dflt:{                       /* it is a pattern item */
      const char *ep = luaI_classend(ms, p);    /* points to what is next */
      int m = s < ms->src_end && luaI_singlematch(uchar(*s), p, ep);
      switch (*ep) {
      case '?':
        {                       /* optional */
          const char *res;
          if (m && ((res = match(ms, s + 1, ep + 1)) != NULL))
            return res;
          p = ep + 1;
          goto init;            /* else return match(ms, s, ep+1); */
        }
      case '*':
        {                       /* 0 or more repetitions */
          return max_expand(ms, s, p, ep);
        }
      case '+':
        {                       /* 1 or more repetitions */
          return (m ? max_expand(ms, s + 1, p, ep) : NULL);
        }
      case '-':
        {                       /* 0 or more repetitions (minimum) */
          return min_expand(ms, s, p, ep);
        }
      default:
        {
          if (!m)
            return NULL;
          s++;
          p = ep;
          goto init;            /* else return match(ms, s+1, ep); */
        }
      }
    }
  }
}
Пример #10
0
static mowgli_node_t *inspircd_next_matching_ban(channel_t *c, user_t *u, int type, mowgli_node_t *first)
{
	chanban_t *cb;
	mowgli_node_t *n;
	char hostbuf[NICKLEN+USERLEN+HOSTLEN];
	char realbuf[NICKLEN+USERLEN+HOSTLEN];
	char ipbuf[NICKLEN+USERLEN+HOSTLEN];
	char *p;

	snprintf(hostbuf, sizeof hostbuf, "%s!%s@%s", u->nick, u->user, u->vhost);
	snprintf(realbuf, sizeof realbuf, "%s!%s@%s", u->nick, u->user, u->host);
	/* will be nick!user@ if ip unknown, doesn't matter */
	snprintf(ipbuf, sizeof ipbuf, "%s!%s@%s", u->nick, u->user, u->ip);

	MOWGLI_ITER_FOREACH(n, first)
	{
		channel_t *target_c;

		cb = n->data;

		if (cb->type != type)
			continue;

		if ((!match(cb->mask, hostbuf) || !match(cb->mask, realbuf) || !match(cb->mask, ipbuf)) || !match_cidr(cb->mask, ipbuf))
			return n;

		if (cb->mask[1] == ':' && strchr("MRUjrm", cb->mask[0]))
		{
			bool matched = false;

			p = cb->mask + 2;
			if (*(p - 1) != ':')
				p = NULL;

			switch (cb->mask[0])
			{
			case 'M':
			case 'R':
				matched = u->myuser != NULL && !(u->myuser->flags & MU_WAITAUTH) && (p == NULL || !match(p, entity(u->myuser)->name));
				break;
			case 'U':
				matched = u->myuser == NULL;
				break;
			case 'j':
				if (p == NULL)
					continue;
				target_c = channel_find(p);
				if (target_c == NULL || (target_c->modes & (CMODE_PRIV | CMODE_SEC)))
					continue;
				matched = chanuser_find(target_c, u) != NULL;
				break;
			case 'r':
				if (p == NULL)
					continue;
				matched = !match(p, u->gecos);
				break;
			case 'm':
				matched = (!match(p, hostbuf) || !match(p, realbuf) || !match(p, ipbuf)) || !match_cidr(p, ipbuf);
				break;
			default:
				continue;
			}

			if (matched)
				return n;
		}
	}
Пример #11
0
int m_stats(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
{
  struct Message* mptr;
  struct Client*  acptr;
  char            l_stat = parc > 1 ? parv[1][0] : '\0';
  int             i;
  int             doall = 0;
  int             wilds = 0;
  int             ignore_request = 0;
  int             valid_stats = 0;
  char*           name;
  char *mename = me.name;
  
  if(sptr->user && sptr->user->vlink)
    mename = sptr->user->vlink->name;

  if(!IsClient(sptr))
    {
      return 0;
    }

  if(!IsAnOper(sptr))
    {
      sendto_one(sptr, form_str(ERR_NOPRIVILEGES), mename, parv[0]);
	  return -1;
    }

  if (hunt_server(cptr,sptr,":%s STATS %s :%s",2,parc,parv)!=HUNTED_ISME)
    return 0;

  if (parc > 2)
    {
      name = parv[2];
      if (!irccmp(name, mename))
        doall = 2;
      else if (match(name, mename))
        doall = 1;
      if (strchr(name, '*') || strchr(name, '?'))
        wilds = 1;
    }
  else
    name = mename;

  switch (l_stat)
    {
    case 'L' : case 'l' :
      /*
       * send info about connections which match, or all if the
       * mask matches mename.  Only restrictions are on those who
       * are invisible not being visible to 'foreigners' who use
       * a wild card based search to list it.
       */
      for (i = 0; i <= highest_fd; i++)
        {
          if (!(acptr = local[i]))
            continue;

			
          if (!doall && wilds && !match(name, acptr->name))
            continue;
          if (!(doall || wilds) && irccmp(name, acptr->name))
            continue;

          /* I've added a sanity test to the "CurrentTime - acptr->since"
           * occasionally, acptr->since is larger than CurrentTime.
           * The code in parse.c "randomly" increases the "since",
           * which means acptr->since is larger then CurrentTime at times,
           * this gives us very high odd number.. 
           * So, I am going to return 0 for ->since if this happens.
           * - Dianora
           */
          /* trust opers not on this server */
          /* if(IsAnOper(sptr)) */

          /* Don't trust opers not on this server */
#ifdef HIDE_SERVERS_IPS
          if(MyClient(sptr) && IsAnOper(sptr) && !IsServer(acptr) &&
	    !IsConnecting(acptr) && !IsHandshake(acptr)) 
#else
          if(MyClient(sptr) && IsAnOper(sptr))
#endif
            {
              sendto_one(sptr, Lformat, mename,
                     RPL_STATSLINKINFO, parv[0],
                     get_client_name(acptr, TRUE),
                     (int)DBufLength(&acptr->sendQ),
                     (int)acptr->sendM, (int)acptr->sendK,
                     (int)acptr->receiveM, (int)acptr->receiveK,
                     CurrentTime - acptr->firsttime,
                     (CurrentTime > acptr->since) ? (CurrentTime - acptr->since):0,
                     IsServer(acptr) ? show_capabilities(acptr) : "-");
              }
            else
              {
                if(IsServer(acptr))
                  sendto_one(sptr, Lformat, mename,
                     RPL_STATSLINKINFO, parv[0],
                     get_client_name(acptr, HIDEME),
                     (int)DBufLength(&acptr->sendQ),
                     (int)acptr->sendM, (int)acptr->sendK,
                     (int)acptr->receiveM, (int)acptr->receiveK,
                     CurrentTime - acptr->firsttime,
                     (CurrentTime > acptr->since) ? (CurrentTime - acptr->since):0,
                     IsServer(acptr) ? show_capabilities(acptr) : "-");
                 else
                  sendto_one(sptr, Lformat, mename,
                     RPL_STATSLINKINFO, parv[0],
                     (IsUpper(lstat)) ?
                     get_client_name(acptr, TRUE) :
                     get_client_name(acptr, FALSE),
                     (int)DBufLength(&acptr->sendQ),
                     (int)acptr->sendM, (int)acptr->sendK,
                     (int)acptr->receiveM, (int)acptr->receiveK,
                     CurrentTime - acptr->firsttime,
                     (CurrentTime > acptr->since) ? (CurrentTime - acptr->since):0,
                     IsServer(acptr) ? show_capabilities(acptr) : "-");
              }
        }
      valid_stats++;
      break;
    case 'C' : case 'c' :
      report_configured_links(sptr, CONF_CONNECT_SERVER|CONF_NOCONNECT_SERVER);
      valid_stats++;
      break;

    case 'B' : case 'b' :
      sendto_one(sptr,":%s NOTICE %s :Use stats I instead", mename, parv[0]);
      break;

    case 'D':
      report_dlines(sptr);
      valid_stats++;
      break;
      
    case 'd':
      report_domain_stats(sptr);
      valid_stats++;
      break;

    case 'E' : case 'e' :
      sendto_one(sptr,":%s NOTICE %s :Use stats I instead", mename, parv[0]);
      break;

    case 'F' : case 'f' :
      report_channel_stats(sptr);
      break;

    case 'g' :
      report_sxlines(sptr);
      valid_stats++;
      break;


    case 'G' :
      report_glines(sptr, NULL);
      valid_stats++;
      break;

    case 'H' : case 'h' :
      report_configured_links(sptr, CONF_HUB|CONF_LEAF);
      valid_stats++;
      break;

    case 'i' :
      report_vlinks(sptr);
      valid_stats++;
      break;

    case 'I' :
      report_mtrie_conf_links(sptr, CONF_CLIENT);
      valid_stats++;
      break;

    case 'k' :
      report_temp_klines(sptr);
      valid_stats++;
      break;

    case 'K' :
      if(parc > 3)
        report_matching_host_klines(sptr,parv[3]);
      else
        report_mtrie_conf_links(sptr, CONF_KILL);
      valid_stats++;
      break;

    case 'M' : case 'm' :
      for (mptr = msgtab; mptr->cmd; mptr++)
          sendto_one(sptr, form_str(RPL_STATSCOMMANDS),
                     mename, parv[0], mptr->cmd,
                     mptr->count, mptr->bytes);
      valid_stats++;
      break;

    case 'o' : case 'O' :
      report_configured_links(sptr, CONF_OPS);
      valid_stats++;
      break;

    case 'P' :
      show_ports(sptr);
      valid_stats++;
      break;

    case 'p' :
      show_opers(sptr);
      valid_stats++;
      break;

    case 'Q' :
      report_qlines(sptr);
      valid_stats++;
      break;

    case 'q' :
      report_sqlines(sptr);
      valid_stats++;
      break;	  

    case 'R' : case 'r' :
      send_usage(sptr,parv[0]);
      valid_stats++;
      break;

    case 'S' :
      list_scache(cptr,sptr,parc,parv);
      valid_stats++;
      break;

    case 'T' : case 't' :
      tstats(sptr, parv[0]);
      valid_stats++;
      break;

    case 'U' :
      report_specials(sptr,CONF_ULINE,RPL_STATSULINE);
      valid_stats++;
      break;

    case 'u' :
      {
        time_t now;
        
        now = CurrentTime - me.since;
        sendto_one(sptr, form_str(RPL_STATSUPTIME), mename, parv[0],
                   now/86400, (now/3600)%24, (now/60)%60, now%60);
        sendto_one(sptr, form_str(RPL_STATSCONN), mename, parv[0],
                   MaxConnectionCount, MaxClientCount,
                   Count.totalrestartcount);
        valid_stats++;
        break;
      }

    case 'V' :
      show_servers(sptr);
      valid_stats++;
      break;

    case 'v' :
      report_svlines(sptr);
      valid_stats++;
      break;
    case 'x' :
        report_specials(sptr,CONF_XLINE,RPL_STATSXLINE);
        valid_stats++;
      break;
	  
    case 'X' :        
	report_configured_links(sptr, CONF_MISSING);
        valid_stats++;
      break;;
	  

    case 'Y' : case 'y' :
        report_classes(sptr);
        valid_stats++;
      break;
	  
    case 'Z' :
      report_zlines(sptr);
      valid_stats++;
      break;

	case 'z' :
      count_memory(sptr, parv[0]);
      valid_stats++;
      break;

    case '?':
      serv_info(sptr, parv[0]);
      valid_stats++;
      break;

    default :
      l_stat = '*';
      break;
    }
  sendto_one(sptr, form_str(RPL_ENDOFSTATS), mename, parv[0], l_stat);

  /* personally, I don't see why opers need to see stats requests
   * at all. They are just "noise" to an oper, and users can't do
   * any damage with stats requests now anyway. So, why show them?
   * -Dianora
   */

  if (valid_stats)
    {
      if ( (l_stat == 'L') || (l_stat == 'l') )
        {
          sendto_ops_imodes(IMODE_SPY,
                "STATS %c requested by %s (%s@%s) [%s] on %s%s",
                l_stat,
                sptr->name,
                sptr->username,
                sptr->host,
                sptr->user->server,
                parc > 2 ? parv[2] : "<no recipient>",
                ignore_request > 0 ? " [request ignored]" : "\0"
                );
        }
      else
        {
          sendto_ops_imodes(IMODE_SPY,
                "STATS %c requested by %s (%s@%s) [%s]%s",
                l_stat,
                sptr->name,
                sptr->username,
                sptr->host,
                sptr->user->server,
                ignore_request > 0 ? " [request ignored]" : "\0"
                );
        }
    }

  return 0;
}
Пример #12
0
int
main(int argc, char **argv)
{
	struct passwd *pwd;
	int ch, count, newline;
	const char *file;
	char *sender, *p;
#if MAXPATHLEN > BUFSIZ
	char buf[MAXPATHLEN];
#else
	char buf[BUFSIZ];
#endif

	file = sender = NULL;
	count = -1;
	while ((ch = getopt(argc, argv, "cf:s:")) != -1)
		switch (ch) {
		case 'c':
			count = 0;
			break;
		case 'f':
			file = optarg;
			break;
		case 's':
			sender = optarg;
			for (p = sender; *p; ++p)
				*p = tolower(*p);
			break;
		case '?':
		default:
			usage();
		}
	argv += optind;

	if (file == NULL) {
		if (*argv) {
			snprintf(buf, sizeof(buf), "%s/%s", _PATH_MAILDIR, *argv);
			file  = buf;
		} else {
			if ((file = getenv("MAIL")) == NULL) {
				if (!(pwd = getpwuid(getuid())))
					errx(1, "no password file entry for you");
				file = pwd->pw_name;
				snprintf(buf, sizeof(buf),
				    "%s/%s", _PATH_MAILDIR, file);
				file = buf;
			}
		}
	}

	/* read from stdin */
	if (strcmp(file, "-") == 0) {
	} 
	else if (freopen(file, "r", stdin) == NULL) {
		err(1, "can't read %s", file);
	}
	for (newline = 1; fgets(buf, sizeof(buf), stdin);) {
		if (*buf == '\n') {
			newline = 1;
			continue;
		}
		if (newline && !strncmp(buf, "From ", 5) &&
		    (!sender || match(buf + 5, sender))) {
			if (count != -1)
				count++;
			else
				printf("%s", buf);
		}
		newline = 0;
	}
	if (count != -1)
		printf("There %s %d message%s in your incoming mailbox.\n",
		    count == 1 ? "is" : "are", count, count == 1 ? "" : "s"); 
	exit(0);
}
 void mk_quantifier_instantiation::instantiate_quantifier(quantifier* q, app* pat, expr_ref_vector & conjs) {
     m_binding.reset();
     m_binding.resize(q->get_num_decls());
     term_pairs todo;
     match(0, pat, 0, todo, q, conjs);
 }
Пример #14
0
/*
 * parse a buffer.
 *
 * NOTE: parse() should not be called recusively by any other functions!
 */
int parse(aClient *cptr, char *pbuffer, char *bufend)
{
  aClient *from = cptr;
  char  *ch;
  char  *s;
  char  parsebuf[2048];
  int   i;
  char* numeric = 0;
  int   paramcount;
  struct Message *mptr;

  Debug((DEBUG_DEBUG, "Parsing %s: %s",
         get_client_name(cptr, TRUE), pbuffer));

  if (IsDead(cptr))
    return -1;

        if (MyClient(cptr) && cptr->codepage) {
                char *trans = codepage_to_unicode(pbuffer, cptr->codepage - 1);
                if (trans != pbuffer) {
                        strncpy(parsebuf, trans, sizeof(parsebuf));
                        pbuffer = parsebuf;
                        bufend = parsebuf + strlen(parsebuf) - 1;
                }
        }

  s = sender;
  *s = '\0';

  for (ch = pbuffer; *ch == ' '; ch++)   /* skip spaces */
    /* null statement */ ;

  para[0] = from->name;
  if (*ch == ':')
    {
      ch++;

      /*
      ** Copy the prefix to 'sender' assuming it terminates
      ** with SPACE (or NULL, which is an error, though).
      */
      for (i = 0; *ch && *ch != ' '; i++ )
	{
	  if (i < (sizeof(sender)-1))
	    *s++ = *ch; /* leave room for NULL */
	  ch++;
	}
      *s = '\0';
      i = 0;

      /*
      ** Actually, only messages coming from servers can have
      ** the prefix--prefix silently ignored, if coming from
      ** a user client...
      **
      ** ...sigh, the current release "v2.2PL1" generates also
      ** null prefixes, at least to NOTIFY messages (e.g. it
      ** puts "sptr->nickname" as prefix from server structures
      ** where it's null--the following will handle this case
      ** as "no prefix" at all --msa  (": NOTICE nick ...")
      */
      if (*sender && IsServer(cptr))
        {
          from = find_client(sender, (aClient *) NULL);
          if (!from || !match(from->name, sender))
            from = find_server(sender);

          para[0] = sender;
          
          /* Hmm! If the client corresponding to the
           * prefix is not found--what is the correct
           * action??? Now, I will ignore the message
           * (old IRC just let it through as if the
           * prefix just wasn't there...) --msa
           */
          if (!from)
            {
              Debug((DEBUG_ERROR, "Unknown prefix (%s)(%s) from (%s)",
                     sender, pbuffer, cptr->name));
              ServerStats->is_unpf++;

              remove_unknown(cptr, sender, pbuffer);

              return -1;
            }
          if (from->from != cptr)
            {
              ServerStats->is_wrdi++;
              Debug((DEBUG_ERROR, "Message (%s) coming from (%s)",
                     pbuffer, cptr->name));

              return cancel_clients(cptr, from, pbuffer);
            }
        }
      while (*ch == ' ')
        ch++;
    }

  if (*ch == '\0')
    {
      ServerStats->is_empt++;
      Debug((DEBUG_NOTICE, "Empty message from host %s:%s",
             cptr->name, from->name));
      return(-1);
    }

  /*
  ** Extract the command code from the packet.  Point s to the end
  ** of the command code and calculate the length using pointer
  ** arithmetic.  Note: only need length for numerics and *all*
  ** numerics must have parameters and thus a space after the command
  ** code. -avalon
  *
  * ummm???? - Dianora
  */
  
  /* Lets log any message we receive except nickserv/chanserv and
     privmsgs/notices - Lamego
  */
  if(debug_opt)
    {
      if(strncasecmp(ch,"PRIVMSG",7)==0 || strncasecmp(ch,"NOTICE",6)==0)
        irclog(L_NOTICE,"Recv: (%s) PRIVMSG/NOTICE ...", from->name);
      else if(strncasecmp(ch,"NICKSERV",8)==0 || strncasecmp(ch,"CHANSERV",8)==0)
        irclog(L_NOTICE,"Recv: (%s) NICKSERV/CHANSERV ...", from->name);
      else
        irclog(L_NOTICE,"Recv: (%s) %s", from->name, ch);
    }
  if( *(ch + 3) == ' ' && /* ok, lets see if its a possible numeric.. */
      IsDigit(*ch) && IsDigit(*(ch + 1)) && IsDigit(*(ch + 2)) )
    {
      mptr = (struct Message *)NULL;
      numeric = ch;
      paramcount = MAXPARA;
      ServerStats->is_num++;
      s = ch + 3;       /* I know this is ' ' from above if */
      *s++ = '\0';      /* blow away the ' ', and point s to next part */
    }
  else
    {
      s = strchr(ch, ' ');      /* moved from above,now need it here */
      if (s)
        *s++ = '\0';

      mptr = tree_parse(ch);

      if (!mptr || !mptr->cmd)
        {
          /*
          ** Note: Give error message *only* to recognized
          ** persons. It's a nightmare situation to have
          ** two programs sending "Unknown command"'s or
          ** equivalent to each other at full blast....
          ** If it has got to person state, it at least
          ** seems to be well behaving. Perhaps this message
          ** should never be generated, though...  --msa
          ** Hm, when is the buffer empty -- if a command
          ** code has been found ?? -Armin
          */
          if (pbuffer[0] != '\0')
            {
              if (IsPerson(from))
                sendto_one(from,
                           ":%s %d %s %s :Unknown command",
                           me.name, ERR_UNKNOWNCOMMAND,
                           from->name, ch);
              Debug((DEBUG_ERROR,"Unknown (%s) from %s",
                     ch, get_client_name(cptr, TRUE)));
            }
          ServerStats->is_unco++;
          return(-1);
        }

      paramcount = mptr->parameters;
      i = bufend - ((s) ? s : ch);
      mptr->bytes += i;

#ifdef FLOOD_DELAY
      /* Allow only 1 msg per 2 seconds
       * (on average) to prevent dumping.
       * to keep the response rate up,
       * bursts of up to 5 msgs are allowed
       * -SRB
       * Opers can send 1 msg per second, burst of ~20
       * -Taner
       */
      if ((mptr->flags & 1) && !(IsServer(cptr)) && !IsFloodEx(cptr) )
        {
#ifdef NO_OPER_FLOOD
#ifndef TRUE_NO_OPER_FLOOD
/* note: both have to be defined for the real no-flood */
          if (IsAnOper(cptr))
            /* "randomly" (weighted) increase the since */
            cptr->since += (cptr->receiveM % 5) ? 1 : 0;
          else
#else
          if (!IsAnOper(cptr))
#endif
#endif
            cptr->since += (2 + i / 120);
        }
#endif /* FLOOD_DELAY */            
    }

  /*
  ** Must the following loop really be so devious? On
  ** surface it splits the message to parameters from
  ** blank spaces. But, if paramcount has been reached,
  ** the rest of the message goes into this last parameter
  ** (about same effect as ":" has...) --msa
  */

  /* Note initially true: s==NULL || *(s-1) == '\0' !! */

  /* ZZZ hmmmmmmmm whats this then? */
#if 0
  if (me.user)
    para[0] = sender;
#endif

  i = 1;

  if (s)
    {
      if (paramcount > MAXPARA)
        paramcount = MAXPARA;

      for (;;)
        {
	  while(*s == ' ')	/* tabs are not considered space */
	    *s++ = '\0';

          if(!*s)
            break;

          if (*s == ':')
            {
              /*
              ** The rest is single parameter--can
              ** include blanks also.
              */
              para[i++] = s + 1;
              break;
            }
	  else
	    {
	      para[i++] = s;
              if (i >= paramcount)
                {
                  break;
                }
              /* scan for end of string, either ' ' or '\0' */
              while (IsNonEOS(*s))
                s++;
	    }
        }
    }

  para[i] = NULL;
  if (mptr == (struct Message *)NULL)
    return (do_numeric(numeric, cptr, from, i, para));

  mptr->count++;

  /* patch to avoid server flooding from unregistered connects */
  /* check allow_unregistered_use flag I've set up instead of function
     comparing *yech* - Dianora */

  if ((!IsRegistered(cptr) || (hvc_enabled && cptr->hvc)) && !mptr->allow_unregistered_use)
    {
      /* if its from a possible server connection
       * ignore it.. more than likely its a header thats sneaked through
       */

      if(IsHandshake(cptr) || IsConnecting(cptr) || IsServer(cptr))
        return -1;

      sendto_one(from,
                 ":%s %d %s %s :Register first.",
                 me.name, ERR_NOTREGISTERED,
                 BadPtr(from->name) ? "*" : from->name, ch);
      return -1;
    }

  /* Again, instead of function address comparing, see if
   * this function resets idle time as given from mptr
   * if IDLE_FROM_MSG is undefined, the sense of the flag is reversed.
   * i.e. if the flag is 0, then reset idle time, otherwise don't reset it.
   *
   * - Dianora
   */

#ifdef IDLE_FROM_MSG
  if (IsRegisteredUser(cptr) && mptr->reset_idle)
    from->user->last = CurrentTime;
#else
  if (IsRegisteredUser(cptr) && !mptr->reset_idle)
    from->user->last = CurrentTime;
#endif
  
  /* don't allow other commands while a list is blocked. since we treat
     them specially with respect to sendq. */
  if ((IsDoingList(cptr)) && (*mptr->func != m_list))
      return -1;
  return (*mptr->func)(cptr, from, i, para);
}
Пример #15
0
Lexeme *init(Parser *p) {
  match(p,ASSIGN);
  return expression(p);
}
Пример #16
0
/* determine version of OS by mem
 * 1.To get signature of multiply versions of os, which is the md5 of kernel code
 * 2.scan all pages of input memory, generate the md5 checksum of one page, compare to all the signature,
 * 	 if they are match, output the version of the os.
 * 3.Done!
 * 4.abandoned*/
void determineOsVersion2(Mem * mem) {
	//get signature
//	initHashTable();
	int osNumber = initDb();

	int pageSize = 4 * 1024; //4k
	int totalPageNumber = mem->mem_size / (4 * 1024); //assume that every page has 4k

	//record when two page have different page index and the same sharp
	int calledPages[totalPageNumber];
	int dsmPages[totalPageNumber];
	//record virtual address
	int i;
	unsigned virtualAddrs[totalPageNumber];
	for (i = 0; i < totalPageNumber; i++) {
		calledPages[i] = 0;
		dsmPages[i] = 0;
		virtualAddrs[i] = 0;
	}

	//start address
	unsigned start_vaddr = 0x80000000;
	unsigned vaddr = start_vaddr;
	int matchCount = 0;
	int matchPageIndex = 0;
	int availableOs[FINGERPRINT_NO];
	for (i = 0; i < FINGERPRINT_NO; i++)
		availableOs[i] = 1;
	for (; vaddr > start_vaddr - 1; vaddr += 0x1000) {
		int rw = 0, us = 0, g = 0, ps = 0; //page size 4M or 4k
		unsigned pAddr = vtopPageProperty(mem->mem, mem->mem_size, mem->pgd, vaddr, &rw, &us, &g, &ps);
		if (pAddr == -1 || pAddr > mem->mem_size)
			continue;
		int pageIndex = pAddr / pageSize;

		if (us == 0 && g == 256 && is_code_page(mem, vaddr, pageSize, virtualAddrs) == 0) {
			page_init(mem, pageIndex, pageSize, dsmPages, 0, vaddr, calledPages);
			if (dsmPages[pageIndex] != 1)
				continue;

			void * startAdress = (void *) ((unsigned) mem->mem + pageIndex * pageSize);
			unsigned char md5digest[16];
			MDMem(startAdress, pageSize, md5digest);
			MDPrint(md5digest);
			printf("\n");

			//search hash table
			int ret = match(osNumber, md5digest, &matchPageIndex, availableOs);
			while (ret == 2) {
				matchPageIndex++;
				ret = match(osNumber, md5digest, &matchPageIndex, availableOs);
			}
			if (ret >= 0) {
				matchPageIndex++;
				matchCount++;
				if (ret == 1)
					break;
			}

//			char * version = hashTableGet(md5digest);
//			if (version != NULL) {
//				printf("OS is %s\n", version);
//				matchCount++;
//				break;
//			}
		}

	}

//	hashTableCleanup();

	if (matchCount == 0)
		puts("Unknown OS!");
	printf("match Count:%d\n", matchCount);
}
Пример #17
0
/*
 * ms_encap()
 *
 * inputs	- destination server, subcommand, parameters
 * output	- none
 * side effects	- propogates subcommand to locally connected servers
 */
static void
ms_encap(struct Client *client_p, struct Client *source_p,
         int parc, char *parv[])
{
  char buffer[BUFSIZE], *ptr = buffer;
  unsigned int cur_len = 0, len, i;
  int paramcount, mpara = 0;
  struct Message *mptr = NULL;
  MessageHandler handler = 0;

  for (i = 1; i < (unsigned int)parc - 1; i++)
  {
    len = strlen(parv[i]) + 1;

    if ((cur_len + len) >= sizeof(buffer))
      return;

    ircsprintf(ptr, "%s ", parv[i]);
    cur_len += len;
    ptr += len;
  }

  len = strlen(parv[i]);

  /*
   * if the final parameter crosses our buffer size, should we bail, 
   * like the rest, or should we truncate?  ratbox seems to think truncate,
   * so i'll do that for now until i can talk to lee.  -bill
   *
   * if the rest bail, we should too, but i'll make it optional for now.
   * frankily, bailing shouldn't matter, as ENCAP is basically worthless anyway.
   * infact, it will most likely not make final release.
   *                                       --nenolod
   */

  if (parc == 3)
    ircsprintf(ptr, "%s", parv[2]);
  else
    ircsprintf(ptr, ":%s", parv[parc-1]);

#ifdef RATBOX_STYLE_ENCAP
  if ((cur_len + len) >= sizeof(buffer))
    buffer[sizeof(buffer)-1] = '\0';
#else
  if ((cur_len + len) >= sizeof(buffer))
    return;
#endif

  sendto_match_servs(source_p, parv[1], CAP_ENCAP,
                     "ENCAP %s", buffer);

  if (!match(parv[1], me.name))
    return;

  mptr = find_command(parv[2]);
  if ((mptr == NULL) || (mptr->cmd == NULL))
    return;

  paramcount = mptr->parameters;
  mpara      = mptr->maxpara;

  mptr->bytes += strlen(buffer);

  /*
   * yes this is an ugly hack, but it is quicker than copying the entire array again
   * note: this hack wouldnt be needed if parv[0] were set to the command name, rather
   * than being derived from the prefix, as it should have been from the beginning.
   */
  ptr = parv[0];
  parv+=2;
  parc-=2;
  parv[0] = ptr;

  if ((handler = mptr->handlers[2]) == NULL)
    return;

  (*handler)(client_p, source_p, parc, parv);
}
Пример #18
0
/*
 * m_kline
 * Add a local user@host ban.
 *
 *    parv[0] = sender
 *    parv[1] = duration (optional)
 *    parv[2] = nick or user@host mask
 *    parv[3] = reason (optional)
 */
int
m_kline(aClient *cptr, aClient *sptr, int parc, char *parv[])
{
    char rbuf[512];
    char hostbuf[HOSTIPLEN+3+1];
    char *target;
    char *user;
    char *host;
    char *reason = "<no reason>";
    int tkminutes = DEFAULT_KLINE_TIME;
    int tkseconds;
    long lval;
    struct userBan *ban;
    struct userBan *existing;
    aClient *acptr;

    if (!OPCanKline(sptr))
    {
        sendto_one(sptr, err_str(ERR_NOPRIVILEGES), me.name, parv[0]);
        return 0;
    }

    if (parc < 2)
    {
        sendto_one(sptr, err_str(ERR_NEEDMOREPARAMS), me.name, parv[0],
                   "KLINE");
        return 0;
    }

    lval = strtol(parv[1], &target, 10);
    if (*target != 0)
    {
        target = parv[1];
        if (parc > 2 && !BadPtr(parv[2]))
            reason = parv[2];
    }
    else
    {
        /* valid expiration time */
        tkminutes = lval;

        if (parc < 3)
        {
            sendto_one(sptr, err_str(ERR_NEEDMOREPARAMS), me.name, parv[0],
                       "KLINE");
            return 0;
        }

        target = parv[2];

        if (parc > 3 && !BadPtr(parv[3]))
            reason = parv[3];
    }

    /* negative times, or times greater than a year, are permanent */
    if (tkminutes < 0 || tkminutes > (365 * 24 * 60))
        tkminutes = 0;
    tkseconds = tkminutes * 60;

    if ((host = strchr(target, '@')))
    {
        *host++ = 0;
        user = target;
    }
    else if (strchr(target, '*'))
    {
        user = "******";
        host = target;
    }
    else
    {
        if (!(acptr = find_chasing(sptr, target, NULL)))
            return 0;
        
        if (!acptr->user)
            return 0;
        
        user = acptr->user->username;
	if (acptr->ip_family == AF_INET)
	{
	    ircsprintf(hostbuf, "%s/24", acptr->hostip);
	    host = hostbuf;
	}
	else
	    host = acptr->hostip;
    }

    if (!match(user, "akjhfkahfasfjd") &&
        !match(host, "ldksjfl.kss...kdjfd.jfklsjf"))
    {
        sendto_one(sptr, ":%s NOTICE %s :KLINE: %s@%s mask is too wide",
                   me.name, parv[0], user, host);
        return 0;
    }

    if (strchr(host, ' ') || !(ban = make_hostbased_ban(user, host)))
    {
        sendto_one(sptr, ":%s NOTICE %s :KLINE: invalid ban mask %s@%s",
                   me.name, parv[0], user, host);
        return 0;
    }

    ban->flags |= UBAN_LOCAL;

    /* only looks for duplicate klines, not akills */
    if ((existing = find_userban_exact(ban, UBAN_LOCAL)))
    {
        sendto_one(sptr, ":%s NOTICE %s :KLINE: %s@%s is already %s: %s",
                   me.name, parv[0], user, host, LOCAL_BANNED_NAME,
                   existing->reason ? existing->reason : "<no reason>");
        userban_free(ban);
        return 0;
    }

    if (user_match_ban(sptr, ban))
    {
        sendto_one(sptr, ":%s NOTICE %s :KLINE: %s@%s matches you, rejected",
                   me.name, parv[0], user, host);
        userban_free(ban);
        return 0;
    }

    ircsnprintf(rbuf, sizeof(rbuf), "%s (%s)", reason, smalldate(0));
    ban->reason = MyMalloc(strlen(rbuf) + 1);
    strcpy(ban->reason, rbuf);

    if (tkseconds)
    {
        ban->flags |= UBAN_TEMPORARY;
        ban->timeset = NOW;
        ban->duration = tkseconds;
    }

    add_hostbased_userban(ban);

    if (!tkminutes || tkminutes >= KLINE_MIN_STORE_TIME)
        klinestore_add(ban);

    userban_sweep(ban);

    host = get_userban_host(ban, rbuf, sizeof(rbuf));

    if (tkminutes)
        sendto_realops("%s added temporary %d min. "LOCAL_BAN_NAME" for"
                       " [%s@%s] [%s]", parv[0], tkminutes, user, host,
                       reason);
    else
        sendto_realops("%s added "LOCAL_BAN_NAME" for [%s@%s] [%s]", parv[0],
                       user, host, reason);

    return 0;
}
Пример #19
0
bool
Reader::readToken( Token &token )
{
   skipSpaces();
   token.start_ = current_;
   Char c = getNextChar();
   bool ok = true;
   switch ( c )
   {
   case '{':
      token.type_ = tokenObjectBegin;
      break;
   case '}':
      token.type_ = tokenObjectEnd;
      break;
   case '[':
      token.type_ = tokenArrayBegin;
      break;
   case ']':
      token.type_ = tokenArrayEnd;
      break;
   case '"':
      token.type_ = tokenString;
      ok = readString();
      break;
   case '/':
      token.type_ = tokenComment;
      ok = readComment();
      break;
   case '0':
   case '1':
   case '2':
   case '3':
   case '4':
   case '5':
   case '6':
   case '7':
   case '8':
   case '9':
   case '-':
      token.type_ = tokenNumber;
      readNumber();
      break;
   case 't':
      token.type_ = tokenTrue;
      ok = match( "rue", 3 );
      break;
   case 'f':
      token.type_ = tokenFalse;
      ok = match( "alse", 4 );
      break;
   case 'n':
      token.type_ = tokenNull;
      ok = match( "ull", 3 );
      break;
   case ',':
      token.type_ = tokenArraySeparator;
      break;
   case ':':
      token.type_ = tokenMemberSeparator;
      break;
   case 0:
      token.type_ = tokenEndOfStream;
      break;
   default:
      ok = false;
      break;
   }
   if ( !ok )
      token.type_ = tokenError;
   token.end_ = current_;
   return true;
}
bool
OpenDDS::DCPS::ReceivedDataElementList::remove(ReceivedDataElement *data_sample)
{
  IdentityFilter match(data_sample);
  return remove(match, false); // short-circuit evaluation
}
Пример #21
0
int
cmd_set (struct session *sess, char *tbuf, char *word[], char *word_eol[])
{
	int wild = FALSE;
	int or = FALSE;
	int off = FALSE;
	int quiet = FALSE;
	int erase = FALSE;
	int i = 0, finds = 0, found;
	int idx = 2;
	int prev_numeric;
	char *var, *val, *prev_string;

	if (g_ascii_strcasecmp (word[2], "-e") == 0)
	{
		idx++;
		erase = TRUE;
	}

	/* turn a bit OFF */
	if (g_ascii_strcasecmp (word[idx], "-off") == 0)
	{
		idx++;
		off = TRUE;
	}

	/* turn a bit ON */
	if (g_ascii_strcasecmp (word[idx], "-or") == 0 || g_ascii_strcasecmp (word[idx], "-on") == 0)
	{
		idx++;
		or = TRUE;
	}

	if (g_ascii_strcasecmp (word[idx], "-quiet") == 0)
	{
		idx++;
		quiet = TRUE;
	}

	var = word[idx];
	val = word_eol[idx+1];

	if (!*var)
	{
		set_list (sess, tbuf);
		return TRUE;
	}

	if ((strchr (var, '*') || strchr (var, '?')) && !*val)
	{
		wild = TRUE;
	}

	if (*val == '=')
	{
		val++;
	}

	do
	{
		if (wild)
		{
			found = !match (var, vars[i].name);
		}
		else
		{
			found = g_ascii_strcasecmp (var, vars[i].name);
		}

		if (found == 0)
		{
			finds++;
			switch (vars[i].type)
			{
			case TYPE_STR:
				if (erase || *val)
				{
					/* save the previous value until we print it out */
					prev_string = (char*) malloc (vars[i].len + 1);
					strncpy (prev_string, (char *) &prefs + vars[i].offset, vars[i].len);

					/* update the variable */
					strncpy ((char *) &prefs + vars[i].offset, val, vars[i].len);
					((char *) &prefs)[vars[i].offset + vars[i].len - 1] = 0;

					if (!quiet)
					{
						PrintTextf (sess, "%s set to: %s (was: %s)\n", var, (char *) &prefs + vars[i].offset, prev_string);
					}

					free (prev_string);
				}
				else
				{
					set_showval (sess, &vars[i], tbuf);
				}
				break;
			case TYPE_INT:
			case TYPE_BOOL:
				if (*val)
				{
					prev_numeric = *((int *) &prefs + vars[i].offset);
					if (vars[i].type == TYPE_BOOL)
					{
						if (atoi (val))
						{
							*((int *) &prefs + vars[i].offset) = 1;
						}
						else
						{
							*((int *) &prefs + vars[i].offset) = 0;
						}
						if (!g_ascii_strcasecmp (val, "YES") || !g_ascii_strcasecmp (val, "ON"))
						{
							*((int *) &prefs + vars[i].offset) = 1;
						}
						if (!g_ascii_strcasecmp (val, "NO") || !g_ascii_strcasecmp (val, "OFF"))
						{
							*((int *) &prefs + vars[i].offset) = 0;
						}
					}
					else
					{
						if (or)
						{
							*((int *) &prefs + vars[i].offset) |= atoi (val);
						}
						else if (off)
						{
							*((int *) &prefs + vars[i].offset) &= ~(atoi (val));
						}
						else
						{
							*((int *) &prefs + vars[i].offset) = atoi (val);
						}
					}
					if (!quiet)
					{
						PrintTextf (sess, "%s set to: %d (was: %d)\n", var, *((int *) &prefs + vars[i].offset), prev_numeric);
					}
				}
				else
				{
					set_showval (sess, &vars[i], tbuf);
				}
				break;
			}
		}
		i++;
	}
	while (vars[i].name);

	if (!finds && !quiet)
	{
		PrintText (sess, "No such variable.\n");
	}
	else if (!save_config ())
	{
		PrintText (sess, "Error saving changes to disk.\n");
	}

	return TRUE;
}
Пример #22
0
static int str_format (lua_State *L) {
  int arg = 1;
  const char *strfrmt = luaL_check_string(L, arg);
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  while (*strfrmt) {
    if (*strfrmt != '%')
      luaL_putchar(&b, *strfrmt++);
    else if (*++strfrmt == '%')
      luaL_putchar(&b, *strfrmt++);  /* %% */
    else { /* format item */
      struct Capture cap;
      char form[MAX_FORMAT];  /* to store the format ('%...') */
      char buff[MAX_ITEM];  /* to store the formatted item */
      const char *initf = strfrmt;
      form[0] = '%';
      if (isdigit((unsigned char)*initf) && *(initf+1) == '$') {
        arg = *initf - '0';
        initf += 2;  /* skip the 'n$' */
      }
      arg++;
      cap.src_end = strfrmt+strlen(strfrmt)+1;
      cap.level = 0;
      strfrmt = match(L, initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
      if (cap.capture[0].len > 2 || cap.capture[1].len > 2 ||  /* < 100? */
          strfrmt-initf > MAX_FORMAT-2)
        lua_error(L, "invalid format (width or precision too long)");
      strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */
      form[strfrmt-initf+2] = 0;
      switch (*strfrmt++) {
        case 'c':  case 'd':  case 'i':
          sprintf(buff, form, luaL_check_int(L, arg));
          break;
        case 'o':  case 'u':  case 'x':  case 'X':
          sprintf(buff, form, (unsigned int)luaL_check_number(L, arg));
          break;
        case 'e':  case 'E': case 'f': case 'g': case 'G':
          sprintf(buff, form, luaL_check_number(L, arg));
          break;
        case 'q':
          luaI_addquoted(L, &b, arg);
          continue;  /* skip the "addsize" at the end */
        case 's': {
          size_t l;
          const char *s = luaL_check_lstr(L, arg, &l);
          if (cap.capture[1].len == 0 && l >= 100) {
            /* no precision and string is too long to be formatted;
               keep original string */
            lua_pushvalue(L, arg);
            luaL_addvalue(&b);
            continue;  /* skip the "addsize" at the end */
          }
          else {
            sprintf(buff, form, s);
            break;
          }
        }
        default:  /* also treat cases 'pnLlh' */
          lua_error(L, "invalid option in `format'");
      }
      luaL_addlstring(&b, buff, strlen(buff));
    }
  }
  luaL_pushresult(&b);
  return 1;
}
Пример #23
0
bool match(const wchar* pattern, const wchar* string, bool ForceCase)
{
    for (;; ++string)
    {
        wchar stringc = touppercw(*string, ForceCase);
        wchar patternc = touppercw(*pattern++, ForceCase);

        switch (patternc)
        {
            case 0:
                return(stringc == 0);

            case '?':
                if (stringc == 0)
                    return(false);

                break;

            case '*':
                if (*pattern == 0)
                    return(true);

                if (*pattern == '.')
                {
                    if (pattern[1] == '*' && pattern[2] == 0)
                        return(true);

                    const wchar* dot = wcschr(string, '.');

                    if (pattern[1] == 0)
                        return (dot == NULL || dot[1] == 0);

                    if (dot != NULL)
                    {
                        string = dot;

                        if (wcspbrk(pattern, L"*?") == NULL && wcschr(string + 1, '.') == NULL)
                            return(mwcsicompc(pattern + 1, string + 1, ForceCase) == 0);
                    }
                }

                while (*string)
                    if (match(pattern, string++, ForceCase))
                        return(true);

                return(false);

            default:
                if (patternc != stringc)
                {
                    // Allow "name." mask match "name" and "name.\" match "name\".
                    if (patternc == '.' && (stringc == 0 || stringc == '\\' || stringc == '.'))
                        return(match(pattern, string, ForceCase));

                    else
                        return(false);
                }

                break;
        }
    }
}
Пример #24
0
//------------------------------------------------------------------------------
void ClassDefinition::bindPropertyImpl(
	const char * name,
	const ObjectHandle & pBase,
	PropertyAccessor & o_PropertyAccessor ) const
{
	if (!*name)
	{
		// empty name causes noop
		return;
	}

	// find property operator
	auto propOperator = name;
	while (true)
	{
		if( !*propOperator ||
			*propOperator == INDEX_OPEN ||
			*propOperator == DOT_OPERATOR )
		{
			break;
		}

		propOperator += 1;
	}

	auto propName = name;
	auto propLength = propOperator - propName;

	auto baseProp = findProperty( propName, propLength );
	if (baseProp == nullptr)
	{
		// error: property `propName` is not found
		o_PropertyAccessor.setBaseProperty( nullptr );
		return;
	}

	o_PropertyAccessor.setObject( pBase );
	o_PropertyAccessor.setBaseProperty( baseProp );

	assert( strncmp( propName, o_PropertyAccessor.getName(), propLength ) == 0 );

	if (!*propOperator)
	{
		// no operator, so that's it
		return;
	}

	Variant propVal = o_PropertyAccessor.getValue();
	if (*propOperator == INDEX_OPEN)
	{
		auto wholeIndex = propOperator;

		// read "multidimensional" indices without recursive bind (optimization)
		while (true)
		{
			Collection collection;
			if (!propVal.tryCast( collection ))
			{
				// error: index operator is applicable to collections only
				o_PropertyAccessor.setBaseProperty( nullptr );
				return;
			}

			// determine key type (heterogeneous keys are not supported yet)
			const auto begin = collection.begin();
			const auto end = collection.end();
			if (begin == end)
			{
				// error: can't index empty collection
				o_PropertyAccessor.setBaseProperty( nullptr );
				return;
			}

			// read key
			Variant key( begin.key().type() );
			{
				propOperator += 1; // skip INDEX_OPEN

				FixedMemoryStream dataStream( propOperator );
				TextStream stream( dataStream );

				stream >> key >> match( INDEX_CLOSE );

				if (stream.fail())
				{
					// error: either key can't be read, or it isn't followed by INDEX_CLOSE
					o_PropertyAccessor.setBaseProperty( nullptr );
					return;
				}

				// skip key and closing bracket
				propOperator += stream.seek( 0, std::ios_base::cur );
			}

			auto it = collection.find( key );

			// If (it == end), still return a valid property accessor to end,
			// rather than an invalid property accessor.
			if (!*propOperator || (it == end))
			{
				// name parsing is completed
				auto baseProp = std::make_shared< CollectionElementHolder >(
					collection,
					it,
					collection.valueType(),
					wholeIndex );
				// o_PropertyAccessor.setObject(); - keep current base
				o_PropertyAccessor.setBaseProperty( baseProp );
				return;
			}

			propVal = it.value();

			if (*propOperator == INDEX_OPEN)
			{
				continue;
			}

			// parse next operator
			break;
		}
	}
Пример #25
0
static int
glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
      Char *pattern, Char *restpattern,
      glob_t *pglob, size_t *limit)
{
	struct dirent *dp;
	DIR *dirp;
	int err;
	char buf[MAXPATHLEN];

	/*
	 * The readdirfunc declaration can't be prototyped, because it is
	 * assigned, below, to two functions which are prototyped in glob.h
	 * and dirent.h as taking pointers to differently typed opaque
	 * structures.
	 */
	struct dirent *(*readdirfunc)();

	if (pathend > pathend_last)
		return (GLOB_ABORTED);
	*pathend = EOS;
	errno = 0;

	if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
		/* TODO: don't call for ENOENT or ENOTDIR? */
		if (pglob->gl_errfunc) {
			if (g_Ctoc(pathbuf, buf, sizeof(buf)))
				return (GLOB_ABORTED);
			if (pglob->gl_errfunc(buf, errno) ||
			    pglob->gl_flags & GLOB_ERR)
				return (GLOB_ABORTED);
		}
		return(0);
	}

	err = 0;

	/* Search directory for matching names. */
	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
		readdirfunc = pglob->gl_readdir;
	else
		readdirfunc = readdir;
	while ((dp = (*readdirfunc)(dirp))) {
		char *sc;
		Char *dc;
		wchar_t wc;
		size_t clen;
		mbstate_t mbs;

		/* Initial DOT must be matched literally. */
		if (dp->d_name[0] == DOT && *pattern != DOT)
			continue;
		memset(&mbs, 0, sizeof(mbs));
		dc = pathend;
		sc = dp->d_name;
		while (dc < pathend_last) {
			clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
			if (clen == (size_t)-1 || clen == (size_t)-2) {
				wc = *sc;
				clen = 1;
				memset(&mbs, 0, sizeof(mbs));
			}
			if ((*dc++ = wc) == EOS)
				break;
			sc += clen;
		}
		if (!match(pathend, pattern, restpattern)) {
			*pathend = EOS;
			continue;
		}
		err = glob2(pathbuf, --dc, pathend_last, restpattern,
		    pglob, limit);
		if (err)
			break;
	}

	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
		(*pglob->gl_closedir)(dirp);
	else
		closedir(dirp);
	return(err);
}
Пример #26
0
Файл: Glob.cpp Проект: 119/vdc
bool Glob::matchAfterAsterisk(TextIterator itp, const TextIterator& endp, TextIterator its, const TextIterator& ends)
{
	return match(itp, endp, its, ends);
}
Пример #27
0
/** Searches for a K/G-line for a client.  If one is found, notify the
 * user and disconnect them.
 * @param cptr Client to search for.
 * @return 0 if client is accepted; -1 if client was locally denied
 * (K-line); -2 if client was globally denied (G-line); -3 if client
 * was globally IP denied (Z-line).
 */
int find_kill(struct Client *cptr)
{
  const char*      host;
  const char*      name;
  const char*      realname;
  const char*      country;
  const char*      continent;
  const char*      version;
  struct DenyConf* deny;
  struct Gline*    agline = NULL;
  struct Zline*    azline = NULL;

  assert(0 != cptr);

  if (!cli_user(cptr))
    return 0;

  host = cli_sockhost(cptr);
  name = cli_user(cptr)->username;
  realname = cli_info(cptr);
  country = cli_countrycode(cptr);
  continent = cli_continentcode(cptr);
  version = cli_version(cptr);

  assert(strlen(host) <= HOSTLEN);
  assert((name ? strlen(name) : 0) <= HOSTLEN);
  assert((realname ? strlen(realname) : 0) <= REALLEN);
  assert((country ? strlen(country) : 0) <= 3);
  assert((continent ? strlen(continent) : 0) <= 3);
  assert((version ? strlen(version) : 0) <= VERSIONLEN);

  /* 2000-07-14: Rewrote this loop for massive speed increases.
   *             -- Isomer
   */
  if (!find_except_conf(cptr, EFLAG_KLINE)) {
    for (deny = denyConfList; deny; deny = deny->next) {
      if (deny->usermask && match(deny->usermask, name))
        continue;
      if (deny->realmask && match(deny->realmask, realname))
        continue;
      if (deny->countrymask && country && match(deny->countrymask, country))
        continue;
      if (deny->continentmask && continent && match(deny->continentmask, continent))
        continue;
      if (feature_bool(FEAT_CTCP_VERSIONING) && feature_bool(FEAT_CTCP_VERSIONING_KILL)) {
        if (deny->version && version && match(deny->version, version))
          continue;
      }
      if (deny->bits > 0) {
        if (!ipmask_check(&cli_ip(cptr), &deny->address, deny->bits))
          continue;
      } else if (deny->hostmask && match(deny->hostmask, host))
        continue;

      if ((deny->flags & DENY_FLAGS_AUTHEX) && IsAccount(cptr)) {
        if (!EmptyString(deny->mark) && EmptyString(cli_killmark(cptr)))
          ircd_strncpy(cli_killmark(cptr), deny->mark, BUFSIZE);
        continue;
      }

      if (EmptyString(deny->message))
        send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP,
                   ":Connection from your host is refused on this server.");
      else {
        if (deny->flags & DENY_FLAGS_FILE)
          killcomment(cptr, deny->message);
        else
          send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP, ":%s.", deny->message);
      }
      return -1;
    }
  }

  /* Check Zlines here just in case a spoofed IP matches */
  if (!feature_bool(FEAT_DISABLE_ZLINES) && (azline = zline_lookup(cptr, 0))) {
    /*
     * find active zlines
     * added a check against the user's IP address to find_zline()
     */
    send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP, ":%s.", ZlineReason(azline));
    return -3;
  }

  /* Don't need to do an except lookup here as it's done in gline_lookup() */
  if (!feature_bool(FEAT_DISABLE_GLINES) && (agline = gline_lookup(cptr, 0))) {
    /*
     * find active glines
     * added a check against the user's IP address to find_gline() -Kev
     */
    send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP, ":%s.", GlineReason(agline));
    return -2;
  }

  return 0;
}
Пример #28
0
// TODO fix?
Lexeme *operator(Parser *p) {
  return match(p,p->pending->type);
}
Пример #29
0
int
main(int argc, char **argv)
{
	wchar_t t;
	int i, opt_end = 0;
	int sigs[] = {SIGHUP, SIGINT, SIGPIPE, 0};

#if defined(__lint)
	yydebug = 0;
#endif

	for (i = 0; sigs[i]; ++i) {
		if (signal(sigs[i], SIG_IGN) != SIG_IGN)
			(void) signal(sigs[i], catchsig);
	}
	tempfile = mktemp(tmp_name);
	(void) close(creat(tempfile, 0));

	(void) setlocale(LC_ALL, "");

#if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
#define	TEXT_DOMAIN "SYS_TEST"
#endif
	(void) textdomain(TEXT_DOMAIN);

	if ((mb_cur_max = MB_CUR_MAX) > 1)
		wide = 1;

	procnam = argv[0];
	getflags(&argc, &argv, &opt_end);
	initalloc();

	setfname("-");
	if (argc > 1) {
		--argc;
		++argv;
		if (strcmp(argv[0], "-")) {
			ifile[ifx] = m4open(&argv, "r", &argc);
			setfname(argv[0]);
		}
	}

	for (;;) {
		token[0] = t = getchr();
		token[1] = EOS;

		if (t == WEOF) {
			if (ifx > 0) {
				(void) fclose(ifile[ifx]);
				ipflr = ipstk[--ifx];
				continue;
			}

			getflags(&argc, &argv, &opt_end);

			if (argc <= 1)
				/*
				 * If dowrap() has been called, the m4wrap
				 * macro has been processed, and a linked
				 * list of m4wrap strings has been created.
				 * The list starts at wrapstart.
				 */
				if (wrapstart) {
					/*
					 * Now that EOF has been processed,
					 * display the m4wrap strings.
					 */
					showwrap();
					continue;
				} else
					break;
			--argc;
			++argv;

			if (ifile[ifx] != stdin)
				(void) fclose(ifile[ifx]);

			if (strcmp(argv[0], "-"))
				ifile[ifx] = m4open(&argv, "r", &argc);
			else
				ifile[ifx] = stdin;

			setfname(argv[0]);
			continue;
		}

		if (is_alpha(t) || t == '_') {
			wchar_t	*tp = token+1;
			int tlim = toksize;
			struct nlist	*macadd;  /* temp variable */

			while ((*tp = getchr()) != WEOF &&
			    (is_alnum(*tp) || *tp == '_')) {
				tp++;
				if (--tlim <= 0)
					error2(gettext(
					    "more than %d chars in word"),
					    toksize);
			}
			putbak(*tp);
			*tp = EOS;

			macadd = lookup(token);
			*Ap = (wchar_t *)macadd;
			if (macadd->def) {
				if ((wchar_t *)(++Ap) >= astklm) {
					--Ap;
					error2(gettext(
					    "more than %d items on "
					    "argument stack"),
					    stksize);
				}

				if (Cp++ == NULL)
					Cp = callst;

				Cp->argp = Ap;
				*Ap++ = op;
				puttok(token);
				stkchr(EOS);
				t = getchr();
				putbak(t);

				if (t != '(')
					pbstr(L"()");
				else	/* try to fix arg count */
					*Ap++ = op;

				Cp->plev = 0;
			} else {
				puttok(token);
			}
		} else if (match(t, lquote)) {
			int	qlev = 1;

			for (;;) {
				token[0] = t = getchr();
				token[1] = EOS;

				if (match(t, rquote)) {
					if (--qlev > 0)
						puttok(token);
					else
						break;
				} else if (match(t, lquote)) {
					++qlev;
					puttok(token);
				} else {
					if (t == WEOF)
						error(gettext(
						"EOF in quote"));
					putchr(t);
				}
			}
		} else if (match(t, lcom) &&
		    ((lcom[0] != L'#' || lcom[1] != L'\0') ||
		    prev_char != '$')) {

			/*
			 * Don't expand commented macro (between lcom and
			 * rcom).
			 * What we know so far is that we have found the
			 * left comment char (lcom).
			 * Make sure we haven't found '#' (lcom) immediately
			 * preceded by '$' because we want to expand "$#".
			 */

			puttok(token);
			for (;;) {
				token[0] = t = getchr();
				token[1] = EOS;
				if (match(t, rcom)) {
					puttok(token);
					break;
				} else {
					if (t == WEOF)
						error(gettext(
						"EOF in comment"));
					putchr(t);
				}
			}
		} else if (Cp == NULL) {
			putchr(t);
		} else if (t == '(') {
			if (Cp->plev)
				stkchr(t);
			else {
				/* skip white before arg */
				while ((t = getchr()) != WEOF && is_space(t))
					;

				putbak(t);
			}

			++Cp->plev;
		} else if (t == ')') {
			--Cp->plev;

			if (Cp->plev == 0) {
				stkchr(EOS);
				expand(Cp->argp, Ap-Cp->argp-1);
				op = *Cp->argp;
				Ap = Cp->argp-1;

				if (--Cp < callst)
					Cp = NULL;
			} else
				stkchr(t);
		} else if (t == ',' && Cp->plev <= 1) {
			stkchr(EOS);
			*Ap = op;

			if ((wchar_t *)(++Ap) >= astklm) {
				--Ap;
				error2(gettext(
				    "more than %d items on argument stack"),
				    stksize);
			}

			while ((t = getchr()) != WEOF && is_space(t))
				;

			putbak(t);
		} else {
			stkchr(t);
		}
	}

	if (Cp != NULL)
		error(gettext(
		"EOF in argument list"));

	delexit(exitstat, 1);
	return (0);
}
Пример #30
0
/** Splits into at most maxfields.  If maxfields is unspecified or 0, 
 ** trailing empty matches are discarded.  If maxfields is positive,
 ** no more than maxfields fields will be returned and trailing empty
 ** matches are preserved.  If maxfields is empty, all fields (including
 ** trailing empty ones) are returned.  This *should* be the same as the
 ** perl behaviour
 */
int
PME::split(const std::string & s, unsigned maxfields)
{
	/// stores the marks for the split
	vector<markers> oMarks;

	// this is a list of current trailing empty matches if maxfields is 
	//   unspecified or 0.  If there is stuff in it and a non-empty match
	//   is found, then everything in here is pushed into oMarks and then 
	//   the new match is pushed on.  If the end of the string is reached
	//   and there are empty matches in here, they are discarded.
	vector<markers> oCurrentTrailingEmpties; 

	int nOffset = 0;
	unsigned int nMatchesFound = 0;

	// while we are still finding matches and maxfields is 0 or negative
	//   (meaning we get all matches), or we haven't gotten to the number
	//   of specified matches
	int nMatchStatus;
	while ( ( nMatchStatus = match ( s, nOffset ) ) &&
			( ( maxfields < 1 ) ||
			  nMatchesFound < maxfields ) ) {
		nMatchesFound++;
//		printf ( "nMatchesFound = %d\n", nMatchesFound );
		// check to see if the match is empty
		if ( nOffset != m_marks [ 0 ].first ) {
			//fprintf ( stderr, "Match is not empty\n" );
			// if this one isn't empty, then make sure to push anything from 
			//   oCurrentTrailingEmpties into oMarks
			oMarks.insert ( oMarks.end ( ),
							oCurrentTrailingEmpties.begin ( ),
							oCurrentTrailingEmpties.end ( ) );

			// grab from nOffset to m_marks[0].first and again from m_marks[0].second to 
			//   the end of the string
			oMarks.push_back ( markers ( nOffset, m_marks [ 0 ].first ) );

		} 
		// else the match was empty and we have to do some checking
		//   to see what to do
		else {
			//fprintf ( stderr, "match was empty\n" );
			// if maxfields == 0, discard empty trailing matches
			if ( maxfields == 0 ) {
				//fprintf ( stderr, "putting empty into trailing empties list");
				oCurrentTrailingEmpties.push_back ( markers ( nOffset, m_marks [ 0 ].first ) );

			}
			// else we keep all the matches, empty or no
			else {
				//fprintf ( stderr, "Keeping empty match\n" );
				// grab from nOffset to m_marks[0].first and again from m_marks[0].second to 
				//   the end of the string
				oMarks.push_back ( markers ( nOffset, m_marks [ 0 ].first ) );

			}

		}

		// set nOffset to the beginning of the second part of the split
		nOffset = m_marks [ 0 ].second;
		
		fflush ( stdout );

	} // end while ( match ( ... ) ) 

	//fprintf ( stderr, "***match status = %d offset = %d\n", nMatchStatus, nOffset);


	// if there were no matches found, push the whole thing on
	if ( nMatchesFound == 0 ) {
//		printf ( "Putting the whole thing in..\n" );
		oMarks.push_back ( markers ( 0, s.length ( ) ) );
	} 	
	// if we ran out of matches, then append the rest of the string 
	//   onto the end of the last split field
	else if ( maxfields > 0 && 
		 nMatchesFound >= maxfields ) {
//		printf ( "Something else..\n" );
		oMarks [ oMarks.size ( ) - 1 ].second = s.length ( );
	} 
	// else we have to add another entry for the end of the string
	else {
//		printf ( "Something REALLY else..\n" );
		oMarks.push_back ( markers ( m_marks [ 0 ].second, s.length ( ) ) );
	}

	
	m_marks = oMarks;

	//fprintf ( stderr, "match returning %d\n", m_marks.size ( ) );
	nMatches = m_marks.size ( );
	return m_marks.size ( );
}