Esempio n. 1
0
// Interpret one line of scripting language; returns false on QUIT
bool scrInterpret(const char *str, uint lineno)
{
    ScriptLine = lineno;

    const char *x = str;
    if (! peek_char(&x))
        return true;

    // Output command being executed to the log.
    Output(C_LOG "HaRET(%d)# %s", lineno, str);

    char tok[MAX_CMDLEN];
    get_token(&x, tok, sizeof(tok), 1);

    // Okay, now see what keyword is this :)
    for (int i = 0; i < commands_count; i++) {
        regCommand *hc = regCommand::cast(commands_start[i]);
        if (hc && IsToken(tok, hc->name)) {
            hc->func(tok, x);
            return true;
        }
    }

    if (IsToken(tok, "Q|UIT"))
        return false;

    Output(C_ERROR "Unknown keyword: `%s'", tok);
    return true;
}
Esempio n. 2
0
int  sendmodeto_one(aClient *cptr, char *from, char *name, char *mode, char *param, TS creationtime)
{
	if ((IsServer(cptr) && DoesOp(mode) && creationtime) ||
	    IsULine(cptr))
		sendto_one(cptr, ":%s %s %s %s %s %lu", from,
		    (IsToken(cptr) ? TOK_MODE : MSG_MODE), name, mode,
		    param, creationtime);
	else
		sendto_one(cptr, ":%s %s %s %s %s", from,
		    (IsToken(cptr) ? TOK_MODE : MSG_MODE), name, mode, param);
	return 0;
}
Esempio n. 3
0
static char *
skip_ident(Oid index, char *sql)
{
    while (*sql && isspace((unsigned char) *sql))
        sql++;

    if (*sql == '"')
    {
        sql++;
        for (;;)
        {
            char *end = strchr(sql, '"');
            if (end == NULL)
                return parse_error(index);
            else if (end[1] != '"')
            {
                end[1] = '\0';
                return end + 2;
            }
            else	/* escaped quote ("") */
                sql = end + 2;
        }
    }
    else
    {
        while (*sql && IsToken(*sql))
            sql++;
        *sql = '\0';
        return sql + 1;
    }

    /* error */
    return parse_error(index);
}
Esempio n. 4
0
DLLFUNC int m_rawto(aClient *cptr, aClient *sptr, int parc, char *parv[])
{
	aClient *acptr = NULL;
	if (!IsULine(sptr))
	{
		sendto_one(sptr, err_str(ERR_NOPRIVILEGES), me.name, parv[0]);
		return -1;
	}
	if (parc < 3)
	{
		sendto_one(sptr, err_str(ERR_NEEDMOREPARAMS),
		    me.name, parv[0], "RAWTO");
		return -1;
	}
	if ((acptr = find_client(parv[1], NULL)))
	{
		if (MyConnect(acptr))
		{
			sendto_one(acptr, "%s", parv[2]);
			return 0;
		}		
		else
		{
			sendto_one(acptr, ":%s %s %s :%s",
				parv[0], IsToken(acptr->from) ? TOK_RAWTO : MSG_RAWTO,
					parv[1], parv[2]);
			return 0;
		}
	}
	return 0;
}
Esempio n. 5
0
void send_user_joins(aClient *cptr, aClient *user)
{
	Membership *lp;
	aChannel *chptr;
	int  cnt = 0, len = 0, clen;
	char *mask;

	snprintf(buf, sizeof buf, ":%s %s ", user->name,	
	    (IsToken(cptr) ? TOK_JOIN : MSG_JOIN));
	len = strlen(buf);

	for (lp = user->user->channel; lp; lp = lp->next)
	{
		chptr = lp->chptr;
		if ((mask = index(chptr->chname, ':')))
			if (match(++mask, cptr->name))
				continue;
		if (*chptr->chname == '&')
			continue;
		clen = strlen(chptr->chname);
		if (clen + 1 + len > BUFSIZE - 3)
		{
			if (cnt)
			{
				buf[len - 1] = '\0';
				sendto_one(cptr, "%s", buf);
			}
			snprintf(buf, sizeof buf, ":%s %s ", user->name,
			    (IsToken(cptr) ? TOK_JOIN : MSG_JOIN));
			len = strlen(buf);
			cnt = 0;
		}
		(void)strlcpy(buf + len, chptr->chname, sizeof buf-len);
		cnt++;
		len += clen;
		if (lp->next)
		{
			len++;
			(void)strlcat(buf, ",", sizeof buf);
		}
	}
	if (*buf && cnt)
		sendto_one(cptr, "%s", buf);

	return;
}
bool GetBool(char** sIn, bool* bVal)
{
    if (IsToken(sIn, "true"))
    {
        *bVal = true;
    }
    else if (IsToken(sIn, "false"))
    {
        *bVal = false;
    }
    else
    {
        return false;
    }

    return true;
}
Esempio n. 7
0
//-----------------------------------------------------------------------------
// Purpose: 
// Input  : ttype - 
//			pszToken - 
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool TokenReader::Expecting(trtoken_t ttype, const char *pszToken)
{
	char szBuf[1024];
	if (NextToken(szBuf, sizeof(szBuf)) != ttype || !IsToken(pszToken, szBuf))
	{
		return false;
	}
	return true;
}
Esempio n. 8
0
void dcc_sync(aClient *sptr)
{
	ConfigItem_deny_dcc *p;
	for (p = conf_deny_dcc; p; p = (ConfigItem_deny_dcc *) p->next)
	{
		if (p->flag.type2 == CONF_BAN_TYPE_AKILL)
			sendto_one(sptr, ":%s %s + %s :%s", me.name,
			    (IsToken(sptr) ? TOK_SVSFLINE : MSG_SVSFLINE),
			    p->filename, p->reason);
	}
}
bool IsVariable(char** sIn, const char* sTok)
{
    if (IsToken(sIn, sTok))
    {
        if (Expect(sIn , '='))
        {
            return true;
        }
    }

    return false;
}
Esempio n. 10
0
//-----------------------------------------------------------------------------
// Purpose: Returns the enumerated type of a string token.
// Input  : pszToken - Sting containing the token.
// Output : GDIV_TYPE corresponding to the token in the string, ivBadType if the
//			string does not correspond to a valid type.
//-----------------------------------------------------------------------------
GDIV_TYPE GDinputvariable::GetTypeFromToken(const char *pszToken)
{
	for (int i = 0; i < sizeof(TypeMap) / sizeof(TypeMap[0]); i++)
	{
		if (IsToken(pszToken, TypeMap[i].pszName))
		{
			return(TypeMap[i].eType);
		}
	}

	return(ivBadType);
}
Esempio n. 11
0
// -----------------------------------------------------------------------------
// SdpUtil::IsTokenTextPair
// Checks if aValue is valid pair ("valid token":"valid byte-string")
// -----------------------------------------------------------------------------
//
TBool SdpUtil::IsTokenTextPair(
    const TDesC8& aValue, 
    TInt aStart,
    TInt aEnd )
	{
	// token ":" text
	TBool result = EFalse;
	if ( aStart >= 0 && aEnd <= aValue.Length() && aStart < aEnd )
		{
		TPtrC8 subVal = aValue.Mid( aStart, aEnd - aStart );
		TInt colonPos = subVal.Locate( KColonChar );
		result = colonPos != KErrNone &&
                 IsToken( subVal, 0, colonPos ) &&
                 IsByteString( subVal, colonPos + 1, subVal.Length() );
		}
	return result;
	}
//-----------------------------------------------------------------------------
/// GetRequestText
///
/// This provides a method of accessing the text of a request.
///
/// \param requestID An ID for a particular request; the plugin will get this
///  id as a parameter to the ProcessRequest( ) function
///
/// \return pointer to the characters of the requests
//-----------------------------------------------------------------------------
const char* GetRequestText(CommunicationID requestID)
{
    HTTPRequestHeader* pRequest = (HTTPRequestHeader*) GetRequestBinary(requestID);

    if (pRequest == NULL)
    {
        return NULL;
    }

    char* pUrl = pRequest->GetUrl();

    // skip any leading '/' that may preceed the text
    while (IsToken(&pUrl, "/"))
    {
    }

    return (pUrl);
}
Esempio n. 13
0
void CHPGLParser::Parse()
{
	if (IsToken(F("SP"), false, false) || IsToken(F("LT"), false, false))	{ IgnoreCommand();		return; }
	if (IsToken(F("IN"), false, false))										{ InitCommand();		return; }
	if (IsToken(F("PD"), false, false))										{ PenMoveCommand(PD);	return; }
	if (IsToken(F("PU"), false, false))										{ PenMoveCommand(PU);	return; }
	if (IsToken(F("PA"), false, false))										{ PenMoveCommand(PA);	return; }
	if (IsToken(F("PR"), false, false))										{ PenMoveCommand(PR);	return; }

	// command escape to "own" extension

	CHelpParser mycommand(GetReader(),GetOutput());
	mycommand.ParseCommand();

	if (mycommand.IsError()) Error(mycommand.GetError());
	_OkMessage = mycommand.GetOkMessage();
}
int cTemplateViewList::GetAverageFontWidth(void) {
    int defaultAverageFontWidth = 20;

    if (!listElement)
        return defaultAverageFontWidth;

    int numItems = GetNumericParameter(ptNumElements);
    int listHeight = GetNumericParameter(ptHeight);
    if (listHeight <= 0)
        return defaultAverageFontWidth;
    int itemHeight = (double)listHeight / (double)numItems;
    string fontFuncName = parameters->GetParameter(ptDeterminateFont);

    cTemplateFunction *fontFunc = listElement->GetFunction(fontFuncName);
    if (!fontFunc)
        return defaultAverageFontWidth;

    string fontNameToken = fontFunc->GetParameter(ptFont);
    string paramFontSize = fontFunc->GetParameter(ptFontSize);

    string fontName = "";
    if (IsToken(fontNameToken)) {
        if (!globals->GetFont(fontNameToken, fontName)) {
            if (!globals->GetFont("{vdrOsd}", fontName)) {
                return defaultAverageFontWidth;
            }
        }
    } else {
        //if no token, directly use input
        fontName = fontNameToken;
    }

    cNumericParameter pFontSize(paramFontSize);
    pFontSize.SetGlobals(globals);
    pFontSize.SetAreaSize(1000, itemHeight);
    pFontSize.SetVertical();
    int fontSize = pFontSize.Parse(paramFontSize);
    if (!pFontSize.Valid())
        return defaultAverageFontWidth;

    int averageFontWidth = fontManager->Width(fontName, fontSize, "x") + 3;
    return averageFontWidth;
}
Esempio n. 15
0
/*
** m_ping
**	parv[0] = sender prefix
**	parv[1] = origin
**	parv[2] = destination
*/
DLLFUNC int  m_ping(aClient *cptr, aClient *sptr, int parc, char *parv[])
{
	aClient *acptr;
	char *origin, *destination;

	if (parc < 2 || *parv[1] == '\0')
	{
		sendto_one(sptr, err_str(ERR_NOORIGIN), me.name, parv[0]);
		return 0;
	}
	origin = parv[1];
	destination = parv[2];	/* Will get NULL or pointer (parc >= 2!!) */

	if (!MyClient(sptr))
	{
		/* I've no idea who invented this or what it is supposed to do.. */
		acptr = find_client(origin, NULL);
		if (!acptr)
			acptr = find_server_quick(origin);
		if (acptr && acptr != sptr)
			origin = cptr->name;
	}

	if (!BadPtr(destination) && mycmp(destination, me.name) != 0)
	{
		if (MyClient(sptr))
			origin = sptr->name; /* Make sure origin is not spoofed */
		if ((acptr = find_server_quick(destination)) && (acptr != &me))
			sendto_one(acptr, ":%s PING %s :%s", parv[0], origin, destination);
		else
		{
			sendto_one(sptr, err_str(ERR_NOSUCHSERVER),
			    me.name, parv[0], destination);
			return 0;
		}
	}
	else
		sendto_one(sptr, ":%s %s %s :%s", me.name,
		    IsToken(cptr) ? TOK_PONG : MSG_PONG,
		    (destination) ? destination : me.name, origin);
	return 0;
}
Esempio n. 16
0
//-----------------------------------------------------------------------------
// Purpose: 
// Input  : ttype - 
//			*pszToken - 
//-----------------------------------------------------------------------------
void TokenReader::IgnoreTill(trtoken_t ttype, const char *pszToken)
{
	trtoken_t _ttype;
	char szBuf[1024];

	while(1)
	{
		_ttype = NextToken(szBuf, sizeof(szBuf));
		if(_ttype == TOKENEOF)
			return;
		if(_ttype == ttype)
		{
			if(IsToken(pszToken, szBuf))
			{
				Stuff(ttype, pszToken);
				return;
			}
		}
	}
}
Esempio n. 17
0
// -----------------------------------------------------------------------------
// SdpUtil::IsTokenList
// Checks that token list is valid
// -----------------------------------------------------------------------------
//
TBool SdpUtil::IsTokenList(
    const TDesC8& aValue )
	{	
	TBool atError = ( aValue.Length() == 0 );
    
    // Check that we are starting with valid character, not e.g. with space
    if ( !atError && 
         KInvalidTokenCharacters().Locate( aValue[0] ) != KErrNotFound )
        {
        atError = ETrue;
        }
    
    TLex8 lexer( aValue );
    // Go through the tokens to see that they are valid
    while ( !atError && !lexer.Eos() )
        {
        if ( !IsToken( lexer.NextToken() ) )
            {
            atError = ETrue;
            }   
        }

	return !atError;
	}
Esempio n. 18
0
NOXREF int ParseDirective(const char *pText)
{
	NOXREFCHECK;
	if (pText && pText[0] == '$')
	{
		float tempFloat[8];
		if (IsToken(pText, "position"))
		{
			if (ParseFloats(pText, tempFloat, 2))
			{
				gMessageParms.x = tempFloat[0];
				gMessageParms.y = tempFloat[1];
			}
		}
		else if (IsToken(pText, "effect"))
		{
			if (ParseFloats(pText, tempFloat, 1))
			{
				gMessageParms.effect = (int)tempFloat[0];
			}
		}
		else if (IsToken(pText, "fxtime"))
		{
			if (ParseFloats(pText, tempFloat, 1))
			{
				gMessageParms.fxtime = tempFloat[0];
			}
		}
		else if (IsToken(pText, "color2"))
		{
			if (ParseFloats(pText, tempFloat, 3))
			{
				gMessageParms.r2 = (int)tempFloat[0];
				gMessageParms.g2 = (int)tempFloat[1];
				gMessageParms.b2 = (int)tempFloat[2];
			}
		}
		else if (IsToken(pText, "color"))
		{
			if (ParseFloats(pText, tempFloat, 3))
			{
				gMessageParms.r1 = (int)tempFloat[0];
				gMessageParms.g1 = (int)tempFloat[1];
				gMessageParms.b1 = (int)tempFloat[2];
			}
		}
		else if (IsToken(pText, "fadein"))
		{
			if (ParseFloats(pText, tempFloat, 1))
			{
				gMessageParms.fadein = tempFloat[0];
			}
		}
		else if (IsToken(pText, "fadeout"))
		{
			if (ParseFloats(pText, tempFloat, 3))
			{
				gMessageParms.fadeout = tempFloat[0];
			}
		}
		else if (IsToken(pText, "holdtime"))
		{
			if (ParseFloats(pText, tempFloat, 3))
			{
				gMessageParms.holdtime = tempFloat[0];
			}
		}
		else
		{
			Con_DPrintf("Unknown token: %s\n", pText);
		}
		return 1;
	}
	return 0;
}
Esempio n. 19
0
int m_alias(aClient *cptr, aClient *sptr, int parc, char *parv[], char *cmd)
{
ConfigItem_alias *alias;
aClient *acptr;
int ret;

	if (!(alias = Find_alias(cmd))) 
	{
		sendto_one(sptr, ":%s %d %s %s :Unknown command",
			me.name, ERR_UNKNOWNCOMMAND, parv[0], cmd);
		return 0;
	}
	
	/* If it isn't an ALIAS_COMMAND, we require a paramter ... We check ALIAS_COMMAND LATER */
	if (alias->type != ALIAS_COMMAND && (parc < 2 || *parv[1] == '\0'))
	{
		sendto_one(sptr, err_str(ERR_NOTEXTTOSEND), me.name, parv[0]);
		return -1;
	}

	if (alias->type == ALIAS_SERVICES) 
	{
		if (SERVICES_NAME && (acptr = find_person(alias->nick, NULL)))
		{
			if (alias->spamfilter && (ret = dospamfilter(sptr, parv[1], SPAMF_USERMSG, alias->nick, 0, NULL)) < 0)
				return ret;
			sendto_one(acptr, ":%s %s %s@%s :%s", parv[0],
				IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
				alias->nick, SERVICES_NAME, parv[1]);
		}
		else
			sendto_one(sptr, err_str(ERR_SERVICESDOWN), me.name,
				parv[0], alias->nick);
	}
	else if (alias->type == ALIAS_STATS) 
	{
		if (STATS_SERVER && (acptr = find_person(alias->nick, NULL)))
		{
			if (alias->spamfilter && (ret = dospamfilter(sptr, parv[1], SPAMF_USERMSG, alias->nick, 0, NULL)) < 0)
				return ret;
			sendto_one(acptr, ":%s %s %s@%s :%s", parv[0],
				IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
				alias->nick, STATS_SERVER, parv[1]);
		}
		else
			sendto_one(sptr, err_str(ERR_SERVICESDOWN), me.name,
				parv[0], alias->nick);
	}
	else if (alias->type == ALIAS_NORMAL) 
	{
		if ((acptr = find_person(alias->nick, NULL))) 
		{
			if (alias->spamfilter && (ret = dospamfilter(sptr, parv[1], SPAMF_USERMSG, alias->nick, 0, NULL)) < 0)
				return ret;
			if (MyClient(acptr))
				sendto_one(acptr, ":%s!%s@%s PRIVMSG %s :%s", parv[0], 
					sptr->user->username, GetHost(sptr),
					alias->nick, parv[1]);
			else
				sendto_one(acptr, ":%s %s %s :%s", parv[0],
					IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
					alias->nick, parv[1]);
		}
		else
			sendto_one(sptr, err_str(ERR_NOSUCHNICK), me.name,
				parv[0], alias->nick);
	}
	else if (alias->type == ALIAS_CHANNEL)
	{
		aChannel *chptr;
		if ((chptr = find_channel(alias->nick, NULL)))
		{
			if (!can_send(sptr, chptr, parv[1], 0))
			{
				if (alias->spamfilter && (ret = dospamfilter(sptr, parv[1], SPAMF_CHANMSG, chptr->chname, 0, NULL)) < 0)
					return ret;
				sendto_channelprefix_butone_tok(sptr,
				    sptr, chptr,
				    PREFIX_ALL,
				    MSG_PRIVATE,
				    TOK_PRIVATE,
				    chptr->chname, parv[1], 0);
				return 0;
			}
		}
		sendto_one(sptr, err_str(ERR_CANNOTDOCOMMAND), me.name, parv[0],
				cmd, "You may not use this command at this time");
	}
	else if (alias->type == ALIAS_COMMAND) 
	{
		ConfigItem_alias_format *format;
		char *ptr = "";
		if (!(parc < 2 || *parv[1] == '\0'))
			ptr = parv[1]; 
		for (format = alias->format; format; format = (ConfigItem_alias_format *)format->next) 
		{
			if (regexec(&format->expr, ptr, 0, NULL, 0) == 0) 
			{
				/* Parse the parameters */
				int i = 0, j = 0, k = 1;
				char output[1024], current[1024];
				char nums[4];

				bzero(current, sizeof current);
				bzero(output, sizeof output);

				while(format->parameters[i] && j < 500) 
				{
					k = 0;
					if (format->parameters[i] == '%') 
					{
						i++;
						if (format->parameters[i] == '%') 
							output[j++] = '%';
						else if (isdigit(format->parameters[i])) 
						{
							for(; isdigit(format->parameters[i]) && k < 2; i++, k++) {
								nums[k] = format->parameters[i];
							}
							nums[k] = 0;
							i--;
							if (format->parameters[i+1] == '-') {
								strrangetok(ptr, current, ' ', atoi(nums),0);
								i++;
							}
							else 
								strrangetok(ptr, current, ' ', atoi(nums), atoi(nums));
							if (!*current)
								continue;
							if (j + strlen(current)+1 >= 500)
								break;
							strlcat(output, current, sizeof output);
							j += strlen(current);
							
						}
						else if (format->parameters[i] == 'n' ||
							 format->parameters[i] == 'N')
						{
							strlcat(output, parv[0], sizeof output);
							j += strlen(parv[0]);
						}
						else 
						{
							output[j++] = '%';
							output[j++] = format->parameters[i];
						}
						i++;
						continue;
					}
					output[j++] = format->parameters[i++];
				}
				output[j] = 0;
				/* Now check to make sure we have something to send */
				if (strlen(output) == 0)
				{
					sendto_one(sptr, err_str(ERR_NEEDMOREPARAMS), me.name, sptr->name, cmd);
					return -1;
				}
				
				if (format->type == ALIAS_SERVICES) 
				{
					if (SERVICES_NAME && (acptr = find_person(format->nick, NULL)))
					{
						if (alias->spamfilter && (ret = dospamfilter(sptr, output, SPAMF_USERMSG, format->nick, 0, NULL)) < 0)
							return ret;
						sendto_one(acptr, ":%s %s %s@%s :%s", parv[0],
						IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
						format->nick, SERVICES_NAME, output);
					} else
						sendto_one(sptr, err_str(ERR_SERVICESDOWN), me.name,
							parv[0], format->nick);
				}
				else if (format->type == ALIAS_STATS) 
				{
					if (STATS_SERVER && (acptr = find_person(format->nick, NULL)))
					{
						if (alias->spamfilter && (ret = dospamfilter(sptr, output, SPAMF_USERMSG, format->nick, 0, NULL)) < 0)
							return ret;
						sendto_one(acptr, ":%s %s %s@%s :%s", parv[0],
							IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
							format->nick, STATS_SERVER, output);
					} else
						sendto_one(sptr, err_str(ERR_SERVICESDOWN), me.name,
							parv[0], format->nick);
				}
				else if (format->type == ALIAS_NORMAL) 
				{
					if ((acptr = find_person(format->nick, NULL))) 
					{
						if (alias->spamfilter && (ret = dospamfilter(sptr, output, SPAMF_USERMSG, format->nick, 0, NULL)) < 0)
							return ret;
						if (MyClient(acptr))
							sendto_one(acptr, ":%s!%s@%s PRIVMSG %s :%s", parv[0], 
							sptr->user->username, IsHidden(sptr) ? sptr->user->virthost : sptr->user->realhost,
							format->nick, output);
						else
							sendto_one(acptr, ":%s %s %s :%s", parv[0],
								IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
								format->nick, output);
					}
					else
						sendto_one(sptr, err_str(ERR_NOSUCHNICK), me.name,
							parv[0], format->nick);
				}
				else if (format->type == ALIAS_CHANNEL)
				{
					aChannel *chptr;
					if ((chptr = find_channel(format->nick, NULL)))
					{
						if (!can_send(sptr, chptr, output, 0))
						{
							if (alias->spamfilter && (ret = dospamfilter(sptr, output, SPAMF_CHANMSG, chptr->chname, 0, NULL)) < 0)
								return ret;
							sendto_channelprefix_butone_tok(sptr,
							    sptr, chptr,
							    PREFIX_ALL, MSG_PRIVATE,
							    TOK_PRIVATE, chptr->chname,
							    output, 0);
							return 0;
						}
					}
					sendto_one(sptr, err_str(ERR_CANNOTDOCOMMAND), me.name,
						 parv[0], cmd, 
						"You may not use this command at this time");
				}
				else if (format->type == ALIAS_REAL)
				{
					int ret;
					char mybuf[500];
					
					snprintf(mybuf, sizeof(mybuf), "%s %s", format->nick, output);

					if (recursive_alias)
					{
						sendto_one(sptr, err_str(ERR_CANNOTDOCOMMAND), me.name, parv[0], cmd, "You may not use this command at this time -- recursion");
						return -1;
					}

					recursive_alias = 1;
					ret = parse(sptr, mybuf, mybuf+strlen(mybuf));
					recursive_alias = 0;

					return ret;
				}
				break;
			}
		}
		return 0;
	}
	return 0;
}
Esempio n. 20
0
//--------------------------------------------------------------
/// Injects the application specified by the Inject command and
/// sends the results of the injection to the requester
/// \param requestID the ID of the incoming request
/// \param sCmd pointer to the string containing the request
/// \param pClientSocket the socket used to send the response
//--------------------------------------------------------------
void ProcessTracker::DoInjectCommand(CommunicationID requestID, char** sCmd, NetSocket* pClientSocket)
{
    // clear the previous data since it is about to get reset
    g_allowedWrappersMap.clear();
    m_injectedAppName = "";
    m_injectedAppArgs = "";

    // parse the command
    gtASCIIString strCmd(*sCmd);
    std::list< gtASCIIString > paramList;
    strCmd.Split("&", true, paramList);

    for (std::list< gtASCIIString >::const_iterator iter = paramList.begin();
         iter != paramList.end();
         ++iter)
    {
        char* pParam = (char*) iter->asCharArray();
        char** ppParam = &pParam;

        if (IsToken(ppParam, "plugins="))
        {
            // plugins= is followed by a list of comma separated short descriptions of wrappers
            gtASCIIString strPlugins(*ppParam);
            std::list< gtASCIIString > pluginList;
            strPlugins.Split(",", true, pluginList);

            for (std::list< gtASCIIString >::const_iterator iter1 = pluginList.begin();
                 iter1 != pluginList.end();
                 ++iter1)
            {
                if (*iter1 == "")
                {
                    Log(logERROR, "Failed to parse plugin name\n");
                    SendTextResponse(requestID, "Error: Failed to parse plugin name.", pClientSocket);
                    return;
                }

                WrapperMap::iterator iWrapper = GetWrapperMap().find(iter1->asCharArray());

                if (iWrapper == GetWrapperMap().end())
                {
                    Log(logERROR, "Invalid plugin requested, you requested plugin %s\n", (*iter1).asCharArray());
                    SendFormattedTextResponse(requestID, pClientSocket, "Error: Invalid plugin requested, you requested plugin %s\n", (*iter1).asCharArray());
                    return;
                }

                // we have a valid index
                g_allowedWrappersMap.insert(*iWrapper);
            }
        }
        else if (IsToken(ppParam, "app="))
        {
            m_injectedAppName = *ppParam;
        }
        else if (IsToken(ppParam, "args="))
        {
            m_injectedAppArgs = *ppParam;
        }
    }

    // make sure an app name was specified
    if (m_injectedAppName.empty() == true)
    {
        Log(logERROR, "Application name not specified\n");
        SendTextResponse(requestID, "Error: Application name not specified", pClientSocket);
        return;
    }

    // if no wrappers were specified, then use them all
    if (g_allowedWrappersMap.empty() == true)
    {
        g_allowedWrappersMap = GetWrapperMap();
    }

    // fix the path
    gtASCIIString appName = m_injectedAppName.c_str();
    appName.replace("%20", " ");
    appName.replace("%22", "\"");
    appName.replace("%5C", "\\");
    appName.replace("%E2%80%93", "-");
    appName.replace("%26", "&");
    appName.replace("%27", "'");
    appName.replace("%60", "`");
    appName.replace("%E2%80%98", "`");
    m_injectedAppName = appName.asCharArray();

    gtASCIIString appArgs = m_injectedAppArgs.c_str();
    appArgs.replace("%22", "\"");
    appArgs.replace("%20", " ");
    appArgs.replace("%5C", "\\");
    appArgs.replace("%E2%80%93", "-");
    appArgs.replace("%26", "&");
    appArgs.replace("%27", "'");
    appArgs.replace("%60", "`");
    appArgs.replace("%E2%80%98", "`");
    m_injectedAppArgs = appArgs.asCharArray();

    if (WritePluginsToSharedMemoryAndLaunchApp() == true)
    {
        // loop up to 500 times while checking to see if a
        // wrapper name has been written into the shared memory from MicroDLL
        unsigned int uTimeout = 500;

        while (smGet("ActivePlugins", NULL, 0) == 0 && uTimeout > 0)
        {
            uTimeout--;
            osSleep(10);
        }

        if (uTimeout > 0)
        {
            SendHTMLResponse(requestID, "<html>OK</html>", pClientSocket);
        }
        else
        {
            Log(logWARNING, "The server has timed out while trying to receive the current active plugins\n");
            gtASCIIString strErrorResponse;
            strErrorResponse = "<html>The server is taking a while to respond. <p/>Either the application does not use one of the selected APIs or it takes a while to load.<p/><br/>";
            strErrorResponse.appendFormattedString("Please <a href='/page/index.html'>try to reconnect</a> if you expect it to continue or<br/> <a href='/%d/Kill'>click here to kill the process</a></html>", m_injectedAppID);
            SendHTMLResponse(requestID, strErrorResponse.asCharArray(), pClientSocket);
        }
    }
    else
    {
        Log(logERROR, "The plugins could not be written to shared memory or the application could not be launched\n");
        SendTextResponse(requestID, "Error, see log file for more details", pClientSocket);
    }

    return;
}
Esempio n. 21
0
void CHPGLParser::PenMoveCommand(uint8_t cmdidx)
{
	Plotter.Resume();

	switch (cmdidx)
	{
		case PU:	Plotter.DelayPenUp();		_state.FeedRate = _state.FeedRateUp; break;
		case PD:	Plotter.PenDown();			_state.FeedRate = _state.FeedRateDown; break;
		case PA:	_state._HPGLIsAbsolut = true;	break;
		case PR:	_state._HPGLIsAbsolut = false;	break;
	}

	if (IsToken(F("PD"), false, false))											{ PenMoveCommand(PD);	return; }
	if (IsToken(F("PU"), false, false))											{ PenMoveCommand(PU);	return; }
	if (IsToken(F("PA"), false, false))											{ PenMoveCommand(PA);	return; }
	if (IsToken(F("PR"), false, false))											{ PenMoveCommand(PR);	return; }

	while (IsInt(_reader->GetChar()))
	{
		long xIn = GetInt32();

		//all blank or colon

		if (IsInt(_reader->SkipSpaces()))
		{
			// only blank as seperator
		}
		else if (_reader->GetChar() == ',' && IsInt(_reader->GetNextCharSkipScaces()))
		{
			// Colon
		}
		else
		{
		ERROR_MISSINGARGUMENT:
			Error(F("Missing or invalid parameter"));
			return;
		}

		long yIn = GetInt32();

		if (_reader->IsError())	goto ERROR_MISSINGARGUMENT;

		mm1000_t x = HPGLToMM1000X(xIn);
		mm1000_t y = HPGLToMM1000Y(yIn);

		if (_state._HPGLIsAbsolut)
		{
			if (x != CMotionControlBase::GetInstance()->GetPosition(X_AXIS) || y != CMotionControlBase::GetInstance()->GetPosition(Y_AXIS))
			{
				Plotter.DelayPenNow();
				CMotionControlBase::GetInstance()->MoveAbsEx(_state.FeedRate , X_AXIS, x, Y_AXIS, y, -1);
			}
		}
		else
		{
			if (x != 0 || y != 0)
			{
				Plotter.DelayPenNow();
				CMotionControlBase::GetInstance()->MoveRelEx(_state.FeedRate,X_AXIS,x, Y_AXIS, y, -1);
			}
		}
		if (_reader->SkipSpaces() != ',')
			break;

		_reader->GetNextCharSkipScaces();
	}
}
Esempio n. 22
0
Token	ScannerSub::PeekToken2(void){
	int		nCommentNest = 0;

	if(bPeeked) return token;

	bPeeked = true;

	while(true){
		unsigned char c = *lpPos;
		if(c == ' ' || c == '\t'){ lpPos++; continue; }	// スペース or TAB
		if(c == '\0'){									// 行末
			if(ReadLine()) return TK_EOF;				// EOF
			continue;
		}
		if(IsToken(lpPos,"/*")){						// コメント行
			nCommentNest++;
			continue;	
		}
		if(IsToken(lpPos,"*/")){						// コメント行
			nCommentNest--;
			continue;	
		}
		if(nCommentNest != 0){
			if(IS_KANJI1(c)) lpPos++;
			lpPos++;
			continue;
		}
		if(IsToken(lpPos,"//")){						// コメント行
			if(ReadLine()) return TK_EOF;				// EOF
			continue;	
		}
		
		// 字句解析部の命令
		if(IsToken(lpPos,"include"))return TK_INCLUDE;
		if(IsToken(lpPos,"#include"))return TK_INCLUDE;
		if(IsToken(lpPos,"define"))return TK_DEFINE;
		if(IsToken(lpPos,"#define"))return TK_DEFINE;


		// 命令
		if(IsToken(lpPos,"if"))		return TK_IF;
		if(IsToken(lpPos,"else"))	return TK_ELSE;
		if(IsToken(lpPos,"loop"))	return TK_LOOP;
		if(IsToken(lpPos,"break"))	return TK_BREAK;
		if(IsToken(lpPos,"alt"))	return TK_ALT;
		if(IsToken(lpPos,"case"))	return TK_CASE;
		if(IsToken(lpPos,"default"))return TK_DEFAULT;
		if(IsToken(lpPos,"goto"))	return TK_GOTO;
		if(IsToken(lpPos,"return"))	return TK_RETURN;
		if(IsToken(lpPos,"struct"))	return TK_STRUCT;
		if(IsToken(lpPos,"asmout"))	return TK_ASMOUT;
		if(IsToken(lpPos,"for"))	return TK_FOR;
		if(IsToken(lpPos,"while"))	return TK_WHILE;
		if(IsToken(lpPos,"do"))		return TK_DO;
		if(IsToken(lpPos,"continue"))return TK_CONTINUE;

		// 型宣言
		if(IsToken(lpPos,"int"))	return TK_INT;
		if(IsToken(lpPos,"long"))	return TK_LONG;
		if(IsToken(lpPos,"short"))	return TK_SHORT;
		if(IsToken(lpPos,"char"))	return TK_CHAR;
		if(IsToken(lpPos,"dword"))	return TK_DWORD;
		if(IsToken(lpPos,"word"))	return TK_WORD;
		if(IsToken(lpPos,"byte"))	return TK_BYTE;
		if(IsToken(lpPos,"void"))	return TK_VOID;
		if(IsToken(lpPos,"near"))	return TK_NEAR;
		if(IsToken(lpPos,"far"))	return TK_FAR;
		if(IsToken(lpPos,"static"))	return TK_STATIC;
		if(IsToken(lpPos,"signed"))	return TK_SIGNED;
		if(IsToken(lpPos,"unsigned"))return TK_UNSIGNED;
		if(IsToken(lpPos,"offset"))	return TK_OFFSET;
		if(IsToken(lpPos,"segment"))return TK_SEGMENT;
		if(IsToken(lpPos,"rep"))	return TK_REP;
		if(IsToken(lpPos,"true"))	return TK_TRUE;
		if(IsToken(lpPos,"false"))	return TK_FALSE;
		if(IsToken(lpPos,"sizeof"))	return TK_SIZEOF;
//		if(IsToken(lpPos,"code"))	return TK_CODE;
//		if(IsToken(lpPos,"data"))	return TK_DATA;
//		if(IsToken(lpPos,"local"))	return TK_LOCAL;
		
		// フラグなどの宣言
		if(IsToken(lpPos,"CF"))		return TK_CF;
		if(IsToken(lpPos,"ZF"))		return TK_ZF;

		// segment命令のための宣言
		if(IsToken(lpPos,"DWORD"))	return TK_DWORD;
		if(IsToken(lpPos,"WORD"))	return TK_WORD;
		if(IsToken(lpPos,"BYTE"))	return TK_BYTE;
		if(IsToken(lpPos,"PARA"))	return TK_PARA;
		if(IsToken(lpPos,"PAGE"))	return TK_PAGE;
		if(IsToken(lpPos,"PAGE4K"))	return TK_PAGE4K;
		if(IsToken(lpPos,"PRIVATE"))return TK_PRIVATE;
		if(IsToken(lpPos,"PUBLIC"))	return TK_PUBLIC;
		if(IsToken(lpPos,"STACK"))	return TK_STACK;
		if(IsToken(lpPos,"COMMON"))	return TK_COMMON;
		if(IsToken(lpPos,"USE16"))	return TK_USE16;
		if(IsToken(lpPos,"USE32"))	return TK_USE32;
		if(IsToken(lpPos,"RO"))		return TK_RO;
		if(IsToken(lpPos,"EO"))		return TK_EO;
		if(IsToken(lpPos,"ER"))		return TK_ER;
		if(IsToken(lpPos,"RW"))		return TK_RW;

		if(IsToken(lpPos,"<="))		return TK_LE;
		if(IsToken(lpPos,">="))		return TK_GE;
		if(IsToken(lpPos,"=="))		return TK_EQ;
		if(IsToken(lpPos,"!="))		return TK_NE;

		if(IsToken(lpPos,"+="))		return TK_ADD;
		if(IsToken(lpPos,"-="))		return TK_SUB;
		if(IsToken(lpPos,"*="))		return TK_MULA;
		if(IsToken(lpPos,"/="))		return TK_DIVA;
		if(IsToken(lpPos,"&="))		return TK_ANDA;
		if(IsToken(lpPos,"|="))		return TK_ORA;
		if(IsToken(lpPos,"^="))		return TK_XORA;
		if(IsToken(lpPos,">>="))	return TK_SHRA;
		if(IsToken(lpPos,"<<="))	return TK_SHLA;
		if(IsToken(lpPos,"=-"))		return TK_NEG;
		if(IsToken(lpPos,"=~"))		return TK_CPLA;
		
		if(IsToken(lpPos,">>"))		return TK_SHR;
		if(IsToken(lpPos,"<<"))		return TK_SHL;
		if(IsToken(lpPos,"->"))		return TK_MEMBER;
		if(IsToken(lpPos,"++"))		return TK_INC;
		if(IsToken(lpPos,"--"))		return TK_DEC;
		if(IsToken(lpPos,"::"))		return TK_DCOLON;
		if(IsToken(lpPos,"&&"))		return TK_DAND;

		// 一文字トークン
		if(c=='<'){ lpPos++; return TK_BE; }
		if(c=='>'){ lpPos++; return TK_AB; }

		if(c=='.'){ lpPos++; return TK_DOT; }
		if(c==','){ lpPos++; return TK_COMMA; }

		if(c==';'){ lpPos++; return TK_DLM; }
		if(c==':'){ lpPos++; return TK_COLON; }

		if(c=='+'){ lpPos++; return TK_PLUS; }
		if(c=='-'){ lpPos++; return TK_MINUS; }
		if(c=='*'){ lpPos++; return TK_MUL; }
		if(c=='/'){ lpPos++; return TK_DIV; }
		if(c=='%'){ lpPos++; return TK_REM; }

		if(c=='|'){ lpPos++; return TK_OR; }
		if(c=='&'){ lpPos++; return TK_AND; }
		if(c=='^'){ lpPos++; return TK_XOR; }
		if(c=='~'){ lpPos++; return TK_CPL; }
		if(c=='!'){ lpPos++; return TK_NOT; }
		if(c=='.'){ lpPos++; return TK_DOT; }

		if(c=='{'){ lpPos++; return TK_LBR; }
		if(c=='}'){ lpPos++; return TK_RBR; }
		if(c=='('){ lpPos++; return TK_LPR; }
		if(c==')'){ lpPos++; return TK_RPR; }
		if(c=='['){ lpPos++; return TK_LSQ; }
		if(c==']'){ lpPos++; return TK_RSQ; }
		if(c=='='){ lpPos++; return TK_BECOME; }
//		if(c=='#'){ lpPos++; return TK_SHARP; }
//		if(c=='@'){ lpPos++; return TK_AT; }

		// '〜' もしくは "〜"
		if(c=='\''){ GetQuotedLabel(lpPos); return TK_QUOTE; }
		if(c=='\"'){ GetQuotedLabel(lpPos); return TK_WQUOTE; }

		if(!NumCheck(lpPos)){	// 数値
			return TK_NUM;
		}

		CopyLabel(lpPos);			// lpPosから次のトークンまでコピー
		return TK_LABEL;			// ラベル
	}
}
Esempio n. 23
0
bool ProcessTracker::HandleRequest(HTTPRequestHeader* pRequestHeader,
                                   CommunicationID requestID,
                                   NetSocket* pClientSocket,
                                   bool renderLoopStalled)
{
    char* ptr = pRequestHeader->GetUrl();
    char* sCmd = &ptr[1];

#ifdef CODEXL_GRAPHICS
#ifdef USE_GRAPHICS_SERVER_STATUS_RETURN_CODES

    // Handle process not running condition
    if (pRequestHeader->CheckProcessStillRunning() == false)
    {
        Log(logMESSAGE, "Rejecting the command above due to process no longer running: %s\n", pRequestHeader->GetUrl());
        // Need to return the correct error data for process not running
        HandleServerStatusResponse(GRAPHICS_SERVER_STATE_PROCESS_NOT_RUNNING, pRequestHeader, pClientSocket);
        // This request never gets passed to the graphics server.
        return true;
    }

    // Check if renering has stalled.
    if (renderLoopStalled == true)
    {
        Log(logMESSAGE, "Rejecting the command above due to render stall: %s\n", pRequestHeader->GetUrl());
        // Need to return the correct error data for process not running
        HandleServerStatusResponse(GRAPHICS_SERVER_STATE_STALLED, pRequestHeader, pClientSocket);
        // This request never gets passed to the graphics server.
        return true;
    }

#else
    UNREFERENCED_PARAMETER(renderLoopStalled);
#endif
#else
    PS_UNREFERENCED_PARAMETER(renderLoopStalled);
#endif


#ifdef _WIN32

    // if using AppInit_Dll, clear the registry as soon as a process.xml request is sent.
    // TODO: move this to where a connection has definately been made
    if (SG_GET_BOOL(OptionAppInitDll) == true)
    {
        if (registryCleared == false)
        {
            RestoreAppInit();
            registryCleared = true;
        }
    }

#endif

    if (IsToken(&sCmd, "inject?"))
    {
        DoInjectCommand(requestID, &sCmd, pClientSocket);
    }
    else
    {
        // do commands that depend on PID

        for (WrapperMap::iterator wrapperIter = g_activeWrappersMap.begin();
             wrapperIter != g_activeWrappersMap.end();
             ++wrapperIter)
        {
            // parse out the process ID
            unsigned long pid = 0;
            sscanf_s(wrapperIter->first.c_str(), "%lu/", &pid);

            // make PID string for easier parsing of the command
            gtASCIIString strPID;
            strPID.appendFormattedString("%lu", pid);

            gtASCIIString strPidSlashPlugin = wrapperIter->first.c_str();

            // the key in the activeWrappersMap is formatted as pid/plugin (ie: "435/DX11")
            // and this conveniently matches the format of the commands coming into the server, so parse for matching commands
            gtASCIIString tmpString = strPidSlashPlugin;
            tmpString += "/";

            if (IsToken(&sCmd, tmpString.asCharArray()))
            {
                // we know this command is targetting the current plugin
                pRequestHeader->SetUrl(sCmd);

                // pass the request to the plugin
#ifdef _WIN32
                const char* memoryName = strPidSlashPlugin.asCharArray();
#else
                // the '/' character can't be used as a filename in Linux, so just use the plugin name as the shared memory name
                // (ignore the process ID)
                char memoryName[PS_MAX_PATH];
                char pluginShortDesc[ PS_MAX_PATH ];
                sscanf_s(strPidSlashPlugin.asCharArray(), "%lu/%s", &pid, pluginShortDesc, sizeof(pluginShortDesc));
                sprintf_s(memoryName, PS_MAX_PATH, "%lu %s", pid, pluginShortDesc);
#endif

                if (PassRequestToPlugin(memoryName, pRequestHeader, pid, pClientSocket))
                {
                    return true;
                }
                else
                {
                    Log(logERROR, "Request '%s' is not targeted to an active plugin.\n", GetRequestText(requestID));
                    SendHTMLResponse(requestID, "<html>Error: Targeted plugin is not currently active.</html>", pClientSocket);
                }
            }
            else
            {
                tmpString = strPID;
                tmpString += "/Kill";

                if (IsToken(&sCmd, tmpString.asCharArray()))
                {
                    if (KillProcess(pid))
                    {
                        SendTextResponse(requestID, "Ok", pClientSocket);

                        // if the app was launched from the command line or drag and drop
                        // then killing the app should cause the server to shutdown also
                        if (g_bAppSpecifiedAtCmdLine)
                        {
                            g_shutdownEvent.Signal();
                            CloseStreamThread();
                            CloseStreamSockets();
                            SendTextResponse(requestID, "OK", pClientSocket);
                            return true;
                        }
                    }
                    else
                    {
                        Log(logERROR, "Failed to Kill the process\n");
                        SendTextResponse(requestID, "Error: Failed to Kill the process.", pClientSocket);
                    }
                }
            }
        }
    }

    return false;
}
Esempio n. 24
0
//-----------------------------------------------------------------------------
// Purpose: 
// Input  : tr - 
// Output : Returns TRUE on success, FALSE on failure.
//-----------------------------------------------------------------------------
BOOL GDinputvariable::InitFromTokens(TokenReader& tr)
{
	char szToken[128];

	if (!GDGetToken(tr, m_szName, sizeof(m_szName), IDENT))
	{
		return FALSE;
	}

	if (!GDSkipToken(tr, OPERATOR, "("))
	{
		return FALSE;
	}

	// check for "reportable" marker
	trtoken_t ttype = tr.NextToken(szToken, sizeof(szToken));
	if (ttype == OPERATOR)
	{
		if (!strcmp(szToken, "*"))
		{
			m_bReportable = true;
		}
	}
	else
	{
		tr.Stuff(ttype, szToken);
	}

	// get type
	if (!GDGetToken(tr, szToken, sizeof(szToken), IDENT))
	{
		return FALSE;
	}

	if (!GDSkipToken(tr, OPERATOR, ")"))
	{
		return FALSE;
	}

	//
	// Check for known variable types.
	//
	m_eType = GetTypeFromToken(szToken);
	if (m_eType == ivBadType)
	{
		GDError(tr, "'%s' is not a valid variable type", szToken);
		return FALSE;
	}

	//
	// Look ahead at the next token.
	//
	ttype = tr.PeekTokenType(szToken,sizeof(szToken));

	//
	// Check for the "readonly" specifier.
	//
	if ((ttype == IDENT) && IsToken(szToken, "readonly"))
	{
		tr.NextToken(szToken, sizeof(szToken));
		m_bReadOnly = true;

		//
		// Look ahead at the next token.
		//
		ttype = tr.PeekTokenType(szToken,sizeof(szToken));
	}

	//
	// Check for the ':' indicating a long name.
	//
	if (ttype == OPERATOR && IsToken(szToken, ":"))
	{
		//
		// Eat the ':'.
		//
		tr.NextToken(szToken, sizeof(szToken));

		if (m_eType == ivFlags)
		{
			GDError(tr, "flag sets do not have long names");
			return FALSE;
		}

		//
		// Get the long name.
		//
		if (!GDGetToken(tr, m_szLongName, sizeof(m_szLongName), STRING))
		{
			return(FALSE);
		}

		//
		// Look ahead at the next token.
		//
		ttype = tr.PeekTokenType(szToken,sizeof(szToken));

		//
		// Check for the ':' indicating a default value.
		//
		if (ttype == OPERATOR && IsToken(szToken, ":"))
		{
			//
			// Eat the ':'.
			//
			tr.NextToken(szToken, sizeof(szToken));

			//
			// Look ahead at the next token.
			//
			ttype = tr.PeekTokenType(szToken,sizeof(szToken));
			if (ttype == OPERATOR && IsToken(szToken, ":"))
			{
				//
				// No default value provided, skip to the description.
				//
			}
			else
			{
				//
				// Determine how to parse the default value. If this is a choices field, the
				// default could either be a string or an integer, so we must look ahead and
				// use whichever is there.
				//
				trtoken_t eStoreAs = GetStoreAsFromType(m_eType);

				if (eStoreAs == STRING)
				{
					if (!GDGetToken(tr, m_szDefault, sizeof(m_szDefault), STRING))
					{
						return(FALSE);
					}
				}
				else if (eStoreAs == INTEGER)
				{
					if (!GDGetToken(tr, szToken, sizeof(szToken), INTEGER))
					{
						return(FALSE);
					}

					m_nDefault = atoi(szToken);
				}

				//
				// Look ahead at the next token.
				//
				ttype = tr.PeekTokenType(szToken,sizeof(szToken));
			}
		}

		//
		// Check for the ':' indicating a description.
		//
		if (ttype == OPERATOR && IsToken(szToken, ":"))
		{
			//
			// Eat the ':'.
			//
			tr.NextToken(szToken, sizeof(szToken));

			//
			// Read the description.
			//

			// If we've already read a description then free it to avoid memory leaks.
			if ( m_pszDescription )
			{
				delete [] m_pszDescription;
				m_pszDescription = NULL;
			}
			if (!GDGetTokenDynamic(tr, &m_pszDescription, STRING))
			{
				return(FALSE);
			}

			//
			// Look ahead at the next token.
			//
			ttype = tr.PeekTokenType(szToken,sizeof(szToken));
		}
	}
	else
	{
		//
		// Default long name is short name.
		//
		strcpy(m_szLongName, m_szName);
	}

	//
	// Check for the ']' indicating the end of the class definition.
	//
	if ((ttype == OPERATOR && IsToken(szToken, "]")) ||	ttype != OPERATOR)
	{
		if (m_eType == ivFlags || m_eType == ivChoices)
		{
			//
			// Can't define a flags or choices variable without providing any flags or choices.
			//
			GDError(tr, "no %s specified", m_eType == ivFlags ? "flags" : "choices");
			return(FALSE);
		}
		return(TRUE);
	}

	if (!GDSkipToken(tr, OPERATOR, "="))
	{
		return(FALSE);
	}

	if (m_eType != ivFlags && m_eType != ivChoices)
	{
		GDError(tr, "didn't expect '=' here");
		return(FALSE);
	}

	// should be '[' to start flags/choices
	if (!GDSkipToken(tr, OPERATOR, "["))
	{
		return(FALSE);
	}

	// get flags?
	if (m_eType == ivFlags)
	{
		GDIVITEM ivi;

		while (1)
		{
			ttype = tr.PeekTokenType();
			if (ttype != INTEGER)
			{
				break;
			}

			// store bitflag value
			GDGetToken(tr, szToken, sizeof(szToken), INTEGER);
			sscanf( szToken, "%lu", &ivi.iValue );

			// colon..
			if (!GDSkipToken(tr, OPERATOR, ":"))
			{
				return FALSE;
			}

			// get description
			if (!GDGetToken(tr, szToken, sizeof(szToken), STRING))
			{
				return FALSE;
			}
			strcpy(ivi.szCaption, szToken);

			// colon..
			if (!GDSkipToken(tr, OPERATOR, ":"))
			{
				return FALSE;
			}

			// get default setting
			if (!GDGetToken(tr, szToken, sizeof(szToken), INTEGER))
			{
				return FALSE;
			}
			ivi.bDefault = atoi(szToken) ? TRUE : FALSE;

			// add item to array of items
			m_Items.AddToTail(ivi);
		}
		
		// Set the default value.
		unsigned long nDefault = 0;
		for (int i = 0; i < m_Items.Count(); i++)
		{
			if (m_Items[i].bDefault)
				nDefault |= m_Items[i].iValue;
		}
		m_nDefault = (int)nDefault;
		Q_snprintf( m_szDefault, sizeof( m_szDefault ), "%d", m_nDefault );
	}
	else if (m_eType == ivChoices)
	{
		GDIVITEM ivi;

		while (1)
		{
			ttype = tr.PeekTokenType();
			if ((ttype != INTEGER) && (ttype != STRING))
			{
				break;
			}

			// store choice value
			GDGetToken(tr, szToken, sizeof(szToken), ttype);
			ivi.iValue = 0;
			strcpy(ivi.szValue, szToken);

			// colon
			if (!GDSkipToken(tr, OPERATOR, ":"))
			{
				return FALSE;
			}

			// get description
			if (!GDGetToken(tr, szToken, sizeof(szToken), STRING))
			{
				return FALSE;
			}

			strcpy(ivi.szCaption, szToken);

			m_Items.AddToTail(ivi);
		}
	}

	if (!GDSkipToken(tr, OPERATOR, "]"))
	{
		return FALSE;
	}

	return TRUE;
}
//
// Check the given name to see if it is a valid macro name.
// If realMacro is TRUE, then don't allow the name to be 'main'.
// If it is return TRUE, othewise return FALSE and issue an error
// message.
//
boolean SetMacroNameDialog::verifyMacroName(const char *name, boolean realMacro)
{
    int i = 0;
    if (realMacro && IsToken(name,"main",i) &&
               (!name[i] || IsWhiteSpace(name,i))) 
    {
	ModalErrorMessage(this->getRootWidget(),
		"Macro name cannot be \"main\".");
	return FALSE;
    }
    i = 0;
    if (!IsRestrictedIdentifier(name, i) )
    {
	ModalErrorMessage(this->getRootWidget(),
		"Macro name `%s' must start with a letter and consist "
		     "of only letters and numbers", name);
	return FALSE;
    }
    SkipWhiteSpace(name, i);
    if (name[i] != '\0')
    {
	ModalErrorMessage(this->getRootWidget(),
		"Macro name `%s' must start with a letter and consist "
		     "of only letters and numbers", name);
	return FALSE;
    }

    if (IsReservedScriptingWord(name)) {
        ErrorMessage("Macro name \"%s\" is a reserved word", name);
        return FALSE;
    }


    NodeDefinition *nd;
    DictionaryIterator di(*theNodeDefinitionDictionary);
    Symbol nameSym = theSymbolManager->registerSymbol(name);
    while ( (nd = (NodeDefinition*)di.getNextDefinition()) )
    {
	if (nd->getNameSymbol() == nameSym)
	{ 
            if (!nd->isDerivedFromMacro())
            {
                ModalErrorMessage(this->getRootWidget(),
                    "Macro name `%s' is the name of a Data Explorer module.\n"
                    "Macro names must not be the same as a module name.",
                         name);
                return FALSE;
            } 
	    else if (this->network->getDefinition() != 
				(MacroDefinition*)nd) // && is Macro 
	    {
                ModalErrorMessage(this->getRootWidget(),
                    "Macro name `%s' is the name of an already loaded macro.",
                         name);
                return FALSE;
            }
	}
    }

    return TRUE;
}
Esempio n. 26
0
//-----------------------------------------------------------------------------
// Purpose: Fetches the next token from the file.
// Input  : tr - 
//			ppszStore - Destination buffer, one of the following:
//				pointer to NULL - token will be placed in an allocated buffer
//				pointer to non-NULL buffer - token will be placed in buffer
//			ttexpecting - 
//			pszExpecting - 
// Output : 
//-----------------------------------------------------------------------------
static bool DoGetToken(TokenReader &tr, char **ppszStore, int nSize, trtoken_t ttexpecting, const char *pszExpecting)
{
	trtoken_t ttype;

	if (*ppszStore != NULL)
	{
		// Reads the token into the given buffer.
		ttype = tr.NextToken(*ppszStore, nSize);
	}
	else
	{
		// Allocates a buffer to hold the token.
		ttype = tr.NextTokenDynamic(ppszStore);
	}

	if (ttype == TOKENSTRINGTOOLONG)
	{
		GDError(tr, "unterminated string or string too long");
		return false;
	}

	//
	// Check for a bad token type.
	//
	char *pszStore = *ppszStore;
	bool bBadTokenType = false;
	if ((ttype != ttexpecting) && (ttexpecting != TOKENNONE))
	{
		//
		// If we were expecting a string and got an integer, don't worry about it.
		// We can translate from integer to string.
		//
		if (!((ttexpecting == STRING) && (ttype == INTEGER)))
		{
			bBadTokenType = true;
		}
	}

	if (bBadTokenType && (pszExpecting == NULL))
	{
		//
		// We didn't get the expected token type but no expected
		// string was specified.
		//
		char *pszTokenName;
		switch (ttexpecting)
		{
			case IDENT:
			{
				pszTokenName = "identifier";
				break;
			}

			case INTEGER:
			{
				pszTokenName = "integer";
				break;
			}

			case STRING:
			{
				pszTokenName = "string";
				break;
			}

			case OPERATOR:
			default:
			{
				pszTokenName = "symbol";
				break;
			}
		}
		
		GDError(tr, "expecting %s", pszTokenName);
		return false;
	}
	else if (bBadTokenType || ((pszExpecting != NULL) && !IsToken(pszStore, pszExpecting)))
	{
		//
		// An expected string was specified, and we got either the wrong type or
		// the right type but the wrong string,
		//
		GDError(tr, "expecting '%s', but found '%s'", pszExpecting, pszStore);
		return false;
	}

	return true;
}
Esempio n. 27
0
//-----------------------------------------------------------------------------
// Purpose: Loads a gamedata (FGD) file into this object.
// Input  : pszFilename - 
// Output : Returns TRUE on success, FALSE on failure.
//-----------------------------------------------------------------------------
BOOL GameData::Load(const char *pszFilename)
{
	TokenReader tr;

	if(GetFileAttributes(pszFilename) == 0xffffffff)
		return FALSE;

	if(!tr.Open(pszFilename))
		return FALSE;

	trtoken_t ttype;
	char szToken[128];

	while (1)
	{
		if (tr.GetErrorCount() >= MAX_ERRORS)
		{
			break;
		}

		ttype = tr.NextToken(szToken, sizeof(szToken));

		if(ttype == TOKENEOF)
			break;

		if(ttype != OPERATOR || !IsToken(szToken, "@"))
		{
			if(!GDError(tr, "expected @"))
				return FALSE;
		}

		// check what kind it is, and parse a new object
		if (tr.NextToken(szToken, sizeof(szToken)) != IDENT)
		{
			if(!GDError(tr, "expected identifier after @"))
				return FALSE;
		}

		if (IsToken(szToken, "baseclass") || IsToken(szToken, "pointclass") || IsToken(szToken, "solidclass") || IsToken(szToken, "keyframeclass") ||
			IsToken(szToken, "moveclass") || IsToken(szToken, "npcclass") || IsToken(szToken, "filterclass"))
		{
			//
			// New class.
			//
			GDclass *pNewClass = new GDclass;
			if (!pNewClass->InitFromTokens(tr, this))
			{
				tr.IgnoreTill(OPERATOR, "@");	// go to next section
				delete pNewClass;
			}
			else
			{
				if (IsToken(szToken, "baseclass"))			// Not directly available to user.
				{
					pNewClass->SetBaseClass(true);
				}
				else if (IsToken(szToken, "pointclass"))	// Generic point class.
				{
					pNewClass->SetPointClass(true);
				}
				else if (IsToken(szToken, "solidclass"))	// Tied to solids.
				{
					pNewClass->SetSolidClass(true);
				}
				else if (IsToken(szToken, "npcclass"))		// NPC class - can be spawned by npc_maker.
				{
					pNewClass->SetPointClass(true);
					pNewClass->SetNPCClass(true);
				}
				else if (IsToken(szToken, "filterclass"))	// Filter class - can be used as a filter
				{
					pNewClass->SetPointClass(true);
					pNewClass->SetFilterClass(true);
				}
				else if (IsToken(szToken, "moveclass"))		// Animating
				{
					pNewClass->SetMoveClass(true);
					pNewClass->SetPointClass(true);
				}
				else if (IsToken(szToken, "keyframeclass"))	// Animation keyframes
				{
					pNewClass->SetKeyFrameClass(true);
					pNewClass->SetPointClass(true);
				}

				// Check and see if this new class matches an existing one. If so we will override the previous definition.
				int nExistingClassIndex = 0;
				GDclass *pExistingClass = ClassForName(pNewClass->GetName(), &nExistingClassIndex);
				if (NULL != pExistingClass)
				{
					m_Classes.InsertAfter(nExistingClassIndex, pNewClass);
					m_Classes.Remove(nExistingClassIndex);
				}
				else
				{
					m_Classes.AddToTail(pNewClass);
				}
			}
		}
		else if (IsToken(szToken, "include"))
		{
			if (GDGetToken(tr, szToken, sizeof(szToken), STRING))
			{
				// Let's assume it's in the same directory.
				char justPath[MAX_PATH], loadFilename[MAX_PATH];
				if ( Q_ExtractFilePath( pszFilename, justPath, sizeof( justPath ) ) )
				{
					Q_snprintf( loadFilename, sizeof( loadFilename ), "%s%s", justPath, szToken );
				}
				else
				{
					Q_strncpy( loadFilename, szToken, sizeof( loadFilename ) );
				}

				// First try our fully specified directory
				if (!Load(loadFilename))
				{
					// Failing that, try our start directory
					if (!Load(szToken))
					{
						GDError(tr, "error including file: %s", szToken);
					}
				}
			}
		}
		else if (IsToken(szToken, "mapsize"))
		{
			if (!ParseMapSize(tr))
			{
				// Error in map size specifier, skip to next @ sign. 
				tr.IgnoreTill(OPERATOR, "@");
			}
		}
		else if ( IsToken( szToken, "materialexclusion" ) )
		{
			if ( !LoadFGDMaterialExclusions( tr ) )
			{
				// FGD exclusions not defined; skip to next @ sign. 
				tr.IgnoreTill(OPERATOR, "@");
			}
		}
		else if ( IsToken( szToken, "autovisgroup" ) )
		{
			if ( !LoadFGDAutoVisGroups( tr ) )
			{
				// FGD AutoVisGroups not defined; skip to next @ sign. 
				tr.IgnoreTill(OPERATOR, "@");
			}
		}
		else
		{
			GDError(tr, "unrecognized section name %s", szToken);
			tr.IgnoreTill(OPERATOR, "@");
		}
	}

	if (tr.GetErrorCount() > 0)
	{
		return FALSE;
	}

	tr.Close();

	return TRUE;
}
Esempio n. 28
0
bool SimpleParser::Read()
{
  int c;
  int mode=0;  //0 whitespace/idle, 1 comment, 2 token, 3 punct
  string str;
  while((c=in.peek()) != EOF) {
    if(!in) {
      cerr<<"Error while reading characters!"<<endl;
      return false;
    }
    switch(mode) {
    case 0:
      if(IsSpace(c)) {  //continue
      }
      else if(IsComment(c)) mode=1;
      else if(IsToken(c)) { str+=c; mode=2;  }
      else if(IsPunct(c)) { str+=c; mode=3; }
      else {
	cerr<<"Illegal character "<<(char)c<<endl;
	return false;
      }
      break;
    case 1:   //comment
      if(c=='\n') 
	mode=0;
      break;
    case 2:    //reading tokens
      if(IsToken(c)) {str+=c;}
      else {
	Result res=InputToken(str);
	if(res == Stop) return true;
	else if(res == Error) {
	  cerr<<"Error on token "<<str.c_str()<<endl;
	  return false;
	}
	str.erase();
	if(c == '\n') {
	  Result res=InputEndLine();
	  if(res==Stop) return true;
	  else if(res == Error) {
	    cerr<<"Error on endline at line "<<lineno<<endl;
	    return false;
	  }
	  lineno++;
	  mode=0;
	}
	else if(IsSpace(c)) mode=0;
	else if(IsComment(c)) mode=1;
	else if(IsPunct(c)) { str+=c; mode=3;	}
	else {
	  cerr<<"Illegal character "<<(char)c<<endl;
	  return false;
	}
      }
      break;
    case 3:
      if(IsPunct(c)) {str+=c;}
      else {
	Result res=InputPunct(str);
	if(res == Stop) return true;
	else if(res == Error) {
	  cerr<<"Error on token "<<str.c_str()<<endl;
	  return false;
	}
	str.erase();
	if(IsSpace(c)) mode=0;
	else if(IsComment(c)) mode=1;
	else if(IsToken(c)) { str+=c; mode=2; }
	else {
	  cerr<<"Illegal character "<<(char)c<<endl;
	  return false;
	}
      }
      break;
    }
    if(c == '\n') {
      Result res=InputEndLine();
      if(res==Stop) return true;
      else if(res == Error) {
	cerr<<"Error on endline at line "<<lineno<<endl;
	return false;
      }
      lineno++;
    }
    c = in.get();
  }
  if(!str.empty()) {
    Result res=InputToken(str);
    if(res == Stop) return true;
    else if(res == Error) {
      cerr<<"Error on token "<<str.c_str()<<endl;
      return false;
    }
    else {
      cerr<<"Incomplete read at EOF, string "<<str.c_str()<<endl;
      return false;
    }
  }
  in.get();
  assert(!in);
  return true;
}