Exemplo n.º 1
0
ICCItem *CLImageArea::SetData (ICCItem *pData)

//	SetData
//
//	Sets the data being displayed

	{
	ALERROR error;
	CCodeChain *pCC = GetCC();
	ICCItem *pItem;
	CCVector *pBits;
	HBITMAP hBitmap;
	BOOL bOk;
	RECT rcImage;

	//	Get the size

	pItem = GetTF()->ObjMethod(pData, METHOD_IGetImageRect, NULL, NULL, NULL);
	if (pItem->IsError())
		return pItem;

	bOk = CLSizeOptions::ConvertItemToRect(pItem, &rcImage);
	pItem->Discard(pCC);
	if (!bOk)
		return pCC->CreateError(LITERAL("Invalid image size"), NULL);

	//	Get the actual bits

	pItem = GetTF()->ObjMethod(pData, METHOD_IGetRawImage, NULL, NULL, NULL);
	if (pItem->IsError())
		return pItem;

	//	Convert to a vector

	pBits = dynamic_cast<CCVector *>(pItem);
	if (pBits == NULL)
		{
		pItem->Discard(pCC);
		return pCC->CreateError(LITERAL("Invalid raw image"), NULL);
		}

	//	Convert to a DDB

	if (error = rawConvertToDDB(RectWidth(&rcImage),
			RectHeight(&rcImage),
			(RAWPIXEL *)pBits->GetArray(),
			0,
			NULL,
			&hBitmap))
		{
		pBits->Discard(pCC);
		return pCC->CreateSystemError(error);
		}

	//	Free any old bitmaps

	if (m_hImage)
		DeleteObject(m_hImage);

	//	Remember the new data

	m_hImage = hBitmap;
	m_rcImage = rcImage;

	//	Repaint

	m_pWindow->UpdateRect(&m_rcRect);

	//	Done
	
	return pCC->CreateTrue();
	}
Exemplo n.º 2
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	static char const * optv [] =
	{
		"ei:qv",
		"[sta|cid|rsvd|vic|bw|bwc] [limit] [device] [...]",
		"CoQos Stream Utility",
		"e\tredirect stderr to stdout",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"q\tquiet mode",
		"v\tverbose mode",
		(char const *) (0)
	};

#include "../plc/plc.c"

	uint16_t cid = 0;
	uint16_t limit = 0;
	uint8_t type;
	signed code;
	signed c;
	if (getenv (PLCDEVICE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'e':
			dup2 (STDOUT_FILENO, STDERR_FILENO);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			_setbits (plc.flags, PLC_SILENCE);
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			_setbits (plc.flags, PLC_VERBOSE);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if ((code = lookup (* argv++, types, SIZEOF (types))) == -1)
	{
		assist (*--argv, CONTROL, types, SIZEOF (types));
	}
	type = (uint8_t)(code);
	argc--;
	if (type == CONTROL_CID)
	{
		if (!argc)
		{
			error (1, errno, "Expected Connection Identifier");
		}
		if (!hexencode ((uint8_t *)(&cid), sizeof (cid), * argv++))
		{
			error (1, errno, "Invalid CID");
		}
		cid = htons (cid);
		argc--;
	}
	else if (type == CONTROL_BW)
	{
		if (!argc)
		{
			error (1, errno, "Expected Bandwidth Limit");
		}
		limit = atoi (* argv++);
		argc--;
	}
	openchannel (&channel);
	if (!(plc.message = malloc (sizeof (* plc.message))))
	{
		error (1, errno, PLC_NOMEMORY);
	}
	if (!argc)
	{
		con_info (&plc, type, cid, limit);
	}
	while ((argc) && (* argv))
	{
		if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices))))
		{
			error (1, errno, PLC_BAD_MAC, * argv);
		}
		con_info (&plc, type, cid, limit);
		argc--;
		argv++;
	}
	free (plc.message);
	closechannel (&channel);
	exit (0);
}
Exemplo n.º 3
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	static char const * optv [] =
	{
		"ei:qrst:T:vV:",
		"action operand condition [...] control volatility [device] [...]\n\n          where a condition is: field operator value",
		"Qualcomm Atheros Stream MakeRules Utility",
		"e\tredirect stderr to stdout",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"q\tquiet mode",
		"r\tread rules from device",
		"s\tdisplay symbol tables",
		"t n\tread timeout is (n) milliseconds [" LITERAL (CHANNEL_TIMEOUT) "]",
		"T x\tinserted vlan tag is x [" LITERAL (PLCRULE_VLAN_TAG) "]",
		"v\tverbose mode",
		"V n\tcspec version is n [" LITERAL (PLCRULE_CSPEC_VERSION) "]",
		(char const *) (0)
	};

#include "../plc/plc.c"

	struct cspec cspec;
	struct MMERule rule;
	signed c;
	memset (& rule, 0, sizeof (rule));
	memset (& cspec, 0, sizeof (cspec));
	cspec.VLAN_TAG = PLCRULE_VLAN_TAG;
	cspec.CSPEC_VERSION = PLCRULE_CSPEC_VERSION;
	if (getenv (PLCDEVICE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	while (~ (c = getoptv (argc, argv, optv)))
	{
		switch (c)
		{
		case 'e':
			dup2 (STDOUT_FILENO, STDERR_FILENO);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			_setbits (plc.flags, PLC_SILENCE);
			break;
		case 'r':
			_setbits (plc.flags, PLC_ANALYSE);
			break;
		case 's':
			printf ("\n");
			printf (" Controls are ");
			codelist (controls, SIZEOF (controls), COMMA, QUOTE, stdout);
			printf (".\n");
			printf (" Volatilities are ");
			codelist (volatilities, SIZEOF (volatilities), COMMA, QUOTE, stdout);
			printf (".\n");
			printf (" Actions are ");
			codelist (actions, SIZEOF (actions), COMMA, QUOTE, stdout);
			printf (".\n");
			printf (" Operands are ");
			codelist (operands, SIZEOF (operands), COMMA, QUOTE, stdout);
			printf (".\n");
			printf (" Fields are ");
			codelist (fields, SIZEOF (fields), COMMA, QUOTE, stdout);
			printf (".\n");
			printf (" Operators are ");
			codelist (operators, SIZEOF (operators), COMMA, QUOTE, stdout);
			printf (".\n");
			printf (" States are ");
			codelist (states, SIZEOF (states), COMMA, QUOTE, stdout);
			printf (".\n");
			printf ("\n");
			return (0);
		case 't':
			channel.timeout = (signed) (uintspec (optarg, 0, UINT_MAX));
			break;
		case 'T':
			cspec.VLAN_TAG = (uint32_t) (basespec (optarg, 16, sizeof (cspec.VLAN_TAG)));
			cspec.VLAN_TAG = htonl (cspec.VLAN_TAG);
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			_setbits (plc.flags, PLC_VERBOSE);
			break;
		case 'V':
			cspec.CSPEC_VERSION = (uint16_t) (basespec (optarg, 10, sizeof (cspec.CSPEC_VERSION)));
			cspec.CSPEC_VERSION = HTOLE16 (cspec.CSPEC_VERSION);
			break;
		default: 
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (_allclr (plc.flags, PLC_ANALYSE))
	{
		if (ParseRule (& argc, & argv, & rule, & cspec) == -1)
		{
			error (1, 0, "invalid rule");
		}
	}
	openchannel (& channel);
	if (! (plc.message = malloc (sizeof (* plc.message))))
	{
		error (1, errno, PLC_NOMEMORY);
	}
	if (! argc)
	{
		if (_anyset (plc.flags, PLC_ANALYSE))
		{
			ReadRules (& plc);
		}
		else 
		{
			MakeRule (& plc, & rule);
		}
	}
	while ((argc) && (* argv))
	{
		if (! hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices))))
		{
			error (1, errno, PLC_BAD_MAC, * argv);
		}
		if (_anyset (plc.flags, PLC_ANALYSE))
		{
			ReadRules (& plc);
		}
		else 
		{
			MakeRule (& plc, & rule);
		}
		argc--;
		argv++;
	}
	free (plc.message);
	closechannel (& channel);
	exit (0);
}
Exemplo n.º 4
0
int main (int argc, char const * argv []) 

{ 
	extern unsigned margin; 
	extern unsigned column; 
	static char const * optv [] = 
	{ 
		"bc:ehl:prstxz", 
		PUTOPTV_S_FUNNEL, 
		"print offset table", 
		"b\tprint docbook format", 
		"c n\talign descriptions to column (n) [" LITERAL (COLUMN) "]", 
		"e\tprint efsu format", 
		"h\tprint HTML table on stdout", 
		"l n\tindent level is (n) [" LITERAL (MARGIN) "]", 
		"p\tprint HTML page on stdout", 
		"r\treset at headings", 
		"s\tprint CSS2 stylesheet on stdout", 
		"t\tprint text with TAB seperated columns", 
		"x\thide unmarked objects", 
		"z\tremove leading zeros", 
		(char const *)(0)
	}; 
	char const * colors [] = 
	{ 
		"#FFFFFF", 
		"#FFFF00", 
		"#00FFFF", 
		"#00FF00", 
		"#FF00FF"
	}; 
	flag_t flags = (flag_t)(0); 
	signed c; 
	while (~ (c = getoptv (argc, argv, optv))) 
	{ 
		switch (c) 
		{ 
		case 'b': 
			_setbits (flags, OFFSET_BOOK); 
			break; 
		case 'c': 
			column = uintspec (optarg, 0, UCHAR_MAX); 
			break; 
		case 'e': 
			_setbits (flags, OFFSET_EFSU); 
			break; 
		case 'h': 
			_setbits (flags, OFFSET_HTML); 
			break; 
		case 'p': 
			_setbits (flags, OFFSET_PAGE); 
			break; 
		case 'l': 
			margin = (unsigned) (uintspec (optarg, 0, 16)); 
			break; 
		case 'r': 
			_setbits (flags, OFFSET_HOLE); 
			break; 
		case 's': 
			stylesheet (margin); 
			return (0); 
		case 't': 
			_setbits (flags, OFFSET_TEXT); 
			break; 
		case 'x': 
			_setbits (flags, OFFSET_FOLD); 
			break; 
		case 'z': 
			_setbits (flags, OFFSET_ZERO); 
			break; 
		default: 
			break; 
		} 
	} 
	argc -= optind; 
	argv += optind; 
	symbol = emalloc (SYMBOLSIZE); 
	string = emalloc (STRINGSIZE); 
	if (!argc) 
	{ 
		function (colors, sizeof (colors) / sizeof (const char *), flags); 
	} 
	while ((argc) && (* argv)) 
	{ 
		if (efreopen (* argv, "rb", stdin)) 
		{ 
			function (colors, SIZEOF (colors), flags); 
		} 
		argc--; 
		argv++; 
	} 
	return (0); 
} 
Exemplo n.º 5
0
ALERROR CNPUniverse::CreateRandomWorld (CreateCtx &Ctx, CNPNullPoint *pNP, CNPSovereign *pSovereign)

//	CreateRandomWorld
//
//	Creates a random world at the given null point

	{
	ALERROR error;
	CNPWorld *pWorld;
	int i, iRoll;

	//	Create the world

	if (error = CNPWorld::Create(m_Worlds.RegisterEntry(),
			pNP->GetUNID(),
			pSovereign,
			&pWorld))
		{
		Ctx.sError = LITERAL("Out of memory");
		return error;
		}

	m_Worlds.SetEntry(pWorld->GetUNID(), pWorld);

	//	Add to the null point

	if (error = pNP->AddWorld(pWorld))
		{
		delete pWorld;
		Ctx.sError = LITERAL("Out of memory");
		return error;
		}

	//	Add some traits to the world

	CXMLElement *pTraitTable = Ctx.pTemplate->GetContentElementByTag(CONSTLIT("DefineWorldTraitTable"));

	if (mathRandom(1, 100) <= 20)
		AddRandomTrait(Ctx, pWorld, ttMajorDisadvantage, 1, pTraitTable);

	if (mathRandom(1, 100) <= 35)
		AddRandomTrait(Ctx, pWorld, ttMinorDisadvantage, 1, pTraitTable);

	if (mathRandom(1, 100) <= 20)
		AddRandomTrait(Ctx, pWorld, ttMinorDisadvantage, 1, pTraitTable);


	if (mathRandom(1, 100) <= 20)
		AddRandomTrait(Ctx, pWorld, ttMajorAdvantage, 1, pTraitTable);

	if (mathRandom(1, 100) <= 35)
		AddRandomTrait(Ctx, pWorld, ttMinorAdvantage, 1, pTraitTable);

	if (mathRandom(1, 100) <= 20)
		AddRandomTrait(Ctx, pWorld, ttMinorAdvantage, 1, pTraitTable);

	//	Pick a tech level for the world

	CXMLElement *pTechTable = Ctx.pTemplate->GetContentElementByTag(CONSTLIT("DefineWorldTechLevelTable"));
	iRoll = mathRandom(1, 100);
	NPTechLevels iMinTech = pWorld->GetMinTech();
	for (i = 0; i < pTechTable->GetContentElementCount(); i++)
		{
		CXMLElement *pEntry = pTechTable->GetContentElement(i);
		int iProb = pEntry->GetAttributeInteger(CONSTLIT("Prob"));
		if (iRoll <= iProb)
			{
			NPTechLevels iTechLevel = (NPTechLevels)GetSymbolicAttribute(*Ctx.pSymbols, pEntry, CONSTLIT("Tech"));

			//	Make sure this tech level is appropriate for the world

			while (iTechLevel < iMinTech)
				iTechLevel = (NPTechLevels)(iTechLevel + 1);

			pWorld->SetTechLevel(iTechLevel);
			break;
			}

		iRoll -= iProb;
		}

	//	Set the initial population

	int iPopulation = 0;
	switch (pWorld->GetTechLevel())
		{
		case techAgricultural:
			iPopulation = mathRandom(250, 750);
			break;

		case techSteam:
		case techCyber:
			{
			for (i = 0; i < 12; i++)
				iPopulation += mathRandom(0, 500);
			break;
			}

		case techBio:
			{
			for (i = 0; i < 10; i++)
				iPopulation += mathRandom(0, 1000);
			break;
			}

		case techFusion:
		case techAI:
			{
			for (i = 0; i < 8; i++)
				iPopulation += mathRandom(0, 1600);
			break;
			}

		default:
			{
			for (i = 0; i < 10; i++)
				iPopulation += mathRandom(0, 2000);
			break;
			}
		}

	pWorld->SetPopulation((1000 * iPopulation) + mathRandom(-500, 500));

	//	Set the efficiency

	pWorld->SetEfficiency(25 + mathRandom(0, 25) 
			+ mathRandom(0, 25) 
			+ mathRandom(0, 25));

	//	Figure out if this world is a suitable candidate for a capital

	if (IsWorldSuitableAsCapital(this, pWorld))
		pWorld->SetTrait(traitReservedCapital);

	return NOERROR;
	}
Exemplo n.º 6
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	static char const * optv [] =
	{
		"cCef:ri:qvz:",
		"device [device] [...] [> stdout]",
		"Qualcomm Atheros INT6x00 Log Retrieval Utility",
		"c\tclear watchdog and checkpoint reports",
		"C\tcustom watchdog report",
		"e\tredirect stderr to stdout",
		"f s\tprint Watchdog Report in format (s) [xml]",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"q\tquiet mode",
		"r\tread ",
		"v\tverbose mode",
		(char const *) (0)
	};

#include "../plc/plc.c"

	signed c;
	if (getenv (PLCDEVICE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	plc.readaction = 0;
	plc.action = INT6KLOG_FMT_XML;
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'C':
			_setbits (plc.readaction, WD_ACTION_CUSTOM);
			break;
		case 'c':
			_setbits (plc.readaction, WD_ACTION_CLEAR);
			break;
		case 'e':
			dup2 (STDOUT_FILENO, STDERR_FILENO);
			break;
		case 'f':
			if ((c = lookup (optarg, formats, SIZEOF (formats))) == -1)
			{
				assist (optarg, "format", formats, SIZEOF (formats));
			}
			plc.action = (uint8_t)(c);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			_setbits (plc.flags, PLC_SILENCE);
			break;
		case 'r':
			_setbits (plc.readaction, WD_ACTION_READ);
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			_setbits (plc.flags, PLC_VERBOSE);
			break;
		case 'z':
			plc.readaction = (uint8_t)(uintspec (optarg, 0, 255));
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 1)
	{
		if (plc.rpt.file != -1)
		{
			error (1, ECANCELED, PLC_NODEVICE);
		}
	}
	openchannel (&channel);
	if (!(plc.message = malloc (sizeof (* plc.message))))
	{
		error (1, errno, PLC_NOMEMORY);
	}

#ifdef WIN32

	if (plc.action == INT6KLOG_FMT_RAW)
	{
		setmode (STDOUT_FILENO, O_BINARY);
	}

#endif

	if (!argc)
	{
		Diagnostics (&plc);
	}
	while ((argc) && (* argv))
	{
		if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices))))
		{
			error (1, errno, PLC_BAD_MAC, * argv);
		}
		Diagnostics (&plc);
		argc--;
		argv++;
	}
	free (plc.message);
	closechannel (&channel);
	exit (0);
}
Exemplo n.º 7
0
CString CNPServer::OnDataReceived (DWORD dwClientID, const CString &sData, LPVOID pCtx)

//	OnDataReceived

	{
	ALERROR error;
	CString sReply;
	ClientCtx *pClient = (ClientCtx *)pCtx;

	//	Parse data

	CBufferReadBlock Block(sData);
	CDataPackStruct *pData;
	if (error = CDataPackStruct::CreateFromBuffer(&Block, &pData))
		{
		Log("[%d] ERROR: Error creating CDataPackStruct from buffer", dwClientID);

		CDataPackStruct Msg;
		Msg.AppendInteger(RES_CMD_ERROR);
		return Msg.SerializeToString();
		}

	//	The first integer is the command code

	int iCmdCode = pData->GetIntegerItem(0);

	//	Most commands do not work if the universe has not been created yet

	switch (iCmdCode)
		{
		case CMD_CREATE_UNIVERSE:
		case CMD_REQUEST_CONNECT:
			break;

		default:
			{
			if (m_pUniv == NULL)
				{
				sReply = ComposeCmdFail(pClient, iCmdCode,
						LITERAL("The Universe has not yet been created."));
				delete pData;
				return sReply;
				}
			}
		}

	//	Dispatch

	switch (iCmdCode)
		{
		case CMD_CREATE_UNIVERSE:
			sReply = CmdCreateUniverse(pClient, *pData);
			break;

		case CMD_FLEET_DEST:
			sReply = CmdFleetDest(pClient, *pData);
			break;

		case CMD_LOGIN:
			sReply = CmdLogin(pClient, *pData);
			break;

		case CMD_NEW_PLAYER:
			sReply = CmdNewPlayer(pClient, *pData);
			break;

		case CMD_REQUEST_CONNECT:
			sReply = CmdRequestConnect(pClient, *pData);
			break;

		case CMD_VIEW:
			sReply = CmdView(pClient, *pData);
			break;

		default:
			{
			Log("[%d] ERROR: Invalid command from client (%d)", dwClientID, pData->GetIntegerItem(0));

			CDataPackStruct Msg;
			Msg.AppendInteger(RES_CMD_ERROR);
			sReply = Msg.SerializeToString();
			}
		}

	//	Done

	delete pData;

	return sReply;
	}
Exemplo n.º 8
0
ICCItem *CCodeChain::EvaluateArgs (CEvalContext *pCtx, ICCItem *pArgs, const CString &sArgValidation)

//	EvaluateArgs
//
//	Evaluate arguments and validate their types

	{
	ICCItem *pArg;
	ICCItem *pNew;
	ICCItem *pError;
	CCLinkedList *pEvalList;
	char *pValidation;
	int i;
	BOOL bNoEval;

	//	If the argument list if quoted, then it means that the arguments
	//	have already been evaluated. This happens if we've been called by
	//	(apply).

	bNoEval = pArgs->IsQuoted();

	//	Create a list to hold the results

	pNew = CreateLinkedList();
	if (pNew->IsError())
		return pNew;

	pEvalList = dynamic_cast<CCLinkedList *>(pNew);

	//	Start parsing at the beginning

	pValidation = sArgValidation.GetPointer();

	//	If there is a '*' in the validation, figure out
	//	how many arguments it represents

	int iVarArgs = Max(0, pArgs->GetCount() - (sArgValidation.GetLength() - 1));

	//	Loop over each argument

	for (i = 0; i < pArgs->GetCount(); i++)
		{
		ICCItem *pResult;

		pArg = pArgs->GetElement(i);

		//	If we're processing variable args, see if we're done

		if (*pValidation == '*')
			{
			if (iVarArgs == 0)
				pValidation++;
			else
				iVarArgs--;
			}

		//	Evaluate the item. If the arg is 'q' or 'u' then we 
		//	don't evaluate it.

		if (bNoEval || *pValidation == 'q' || *pValidation == 'u')
			pResult = pArg->Reference();

		//	If the arg is 'c' then we don't evaluate unless it is
		//	a lambda expression (or an identifier)

		else if (*pValidation == 'c' && !pArg->IsLambdaExpression() && !pArg->IsIdentifier())
			pResult = pArg->Reference();

		//	Evaluate

		else
			{
			pResult = Eval(pCtx, pArg);

			//	We don't want to return on error because some functions
			//	might want to pass errors around

			if (*pValidation != 'v' && *pValidation != '*')
				{
				if (pResult->IsError())
					{
					pEvalList->Discard(this);
					return pResult;
					}
				}
			}

		//	Check to see if the item is valid

		switch (*pValidation)
			{
			//	We expect a function...

			case 'f':
				{
				if (!pResult->IsFunction())
					{
					pError = CreateError(LITERAL("Function expected"), pResult);
					pResult->Discard(this);
					pEvalList->Discard(this);
					return pError;
					}
				break;
				}

			//  We expect a numeral...
			//
			//	NOTE: We treat integer the same a numeral because it's not always
			//	clear to the user when they've created a double or an integer.
			//	It is up to the actual function to use the integer or double 
			//	value appropriately.

			case 'i':
			case 'n':
				{
				if (!pResult->IsDouble() && !pResult->IsInteger())
					{
					pError = CreateError(LITERAL("Numeral expected"), pResult);
					pResult->Discard(this);
					pEvalList->Discard(this);
					return pError;
					}
				break;
				}

			//  We expect a double...

			case 'd':
				{
				if (!pResult->IsDouble())
					{
					pError = CreateError(LITERAL("Double expected"), pResult);
					pResult->Discard(this);
					pEvalList->Discard(this);
					return pError;
					}
				break;
				}

			//  We expect a vEctor...

			case 'e':
				{
				if (!(pResult->GetValueType() == ICCItem::Vector))
					{
					pError = CreateError(LITERAL("Vector expected"), pResult);
					pResult->Discard(this);
					pEvalList->Discard(this);
					return pError;
					}
				break;
				}

			//	We expect a linked list

			case 'k':
				{
				if (pResult->GetClass()->GetObjID() != OBJID_CCLINKEDLIST)
					{
					pError = CreateError(LITERAL("Linked-list expected"), pResult);
					pResult->Discard(this);
					pEvalList->Discard(this);
					return pError;
					}
				break;
				}

			//	We expect a list

			case 'l':
				{
				if (!pResult->IsList())
					{
					pError = CreateError(LITERAL("List expected"), pResult);
					pResult->Discard(this);
					pEvalList->Discard(this);
					return pError;
					}
				break;
				}

			//	We expect an identifier

			case 's':
			case 'q':
				{
				if (!pResult->IsIdentifier())
					{
					pError = CreateError(LITERAL("Identifier expected"), pResult);
					pResult->Discard(this);
					pEvalList->Discard(this);
					return pError;
					}
				break;
				}

			//	We expect an atom table

			case 'x':
				{
				if (!pResult->IsAtomTable())
					{
					pError = CreateError(LITERAL("Atom table expected"), pResult);
					pResult->Discard(this);
					pEvalList->Discard(this);
					return pError;
					}
				break;
				}

			//	We expect a symbol table

			case 'y':
				{
				if (!pResult->IsSymbolTable())
					{
					pError = CreateError(LITERAL("Symbol table expected"), pResult);
					pResult->Discard(this);
					pEvalList->Discard(this);
					return pError;
					}
				break;
				}

			//	We expect anything

			case 'c':
			case 'u':
			case 'v':
				break;

			//	We expect any number of anythings...

			case '*':
				break;

			//	Too many arguments

			case '\0':
				{
				pError = CreateError(LITERAL("Too many arguments"), NULL);
				pResult->Discard(this);
				pEvalList->Discard(this);
				return pError;
				}

			default:
				ASSERT(FALSE);
			}

		//	Add the result to the list

		pEvalList->Append(*this, pResult);
		pResult->Discard(this);

		//	Next validation sequence (note that *pValidation can never
		//	be '\0' because we return above if we find it)

		if (*pValidation != '*')
			pValidation++;
		}

	//	Make sure we have enough arguments

	if (*pValidation != '\0' && *pValidation != '*')
		{
		pError = CreateError(LITERAL("Insufficient arguments"), NULL);
		pEvalList->Discard(this);
		return pError;
		}

	//	Return the evaluation list

	return pEvalList;
	}
Exemplo n.º 9
0
int main (int argc, char const * argv [])

{
	static char const * optv [] =
	{
		"B:c:D:F:m:p:P:q:S:uvw",
		"",
		"Atheros Serial Line Device Settings",
		"B n\tbaud rate is (n) [" LITERAL (UART_BAUDRATE) "]",
		"c s\tsend custom serial line command (s)",
		"D n\tuse (n) data bits [" LITERAL (UART_DATABITS) "]",
		"F n\tflow control is (n) ["LITERAL (UART_FLOWCTRL) "]",
		"m n\tcommand mode is (n)",
		"p f\tserial port is (f) [" DEVICE "]",
		"P n\tuse (n) parity bits [" LITERAL (UART_PARITY) "]",
		"q\tquiet mode",
		"S n\tuse (n) stop bits [" LITERAL (UART_STOPBITS) "]",
		"u\tforce default host port settings [115200 8N1]",
		"v\tverbose mode",
		"w\twake device [+++]",
		(char const *) (0)
	};
	struct uart uart =
	{
		{
			0,
			DEVICE
		},
		(char *)(0),
		UART_MODE,
		UART_BAUDRATE,
		UART_DATABITS,
		UART_PARITY,
		UART_STOPBITS,
		UART_FLOWCTRL,
		0
	};
	signed c;
	if (getenv (UART_PORT))
	{
		uart.port.name = strdup (getenv (UART_PORT));
	}
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'B':
			_setbits (uart.flags, UART_ATBR);
			uart.baudrate = (uint64_t)(uintspec (optarg, 1, ULONG_MAX));
			break;
		case 'c':
			_setbits (uart.flags, UART_COMMAND);
			uart.string = optarg;
			break;
		case 'D':
			_setbits (uart.flags, UART_ATBR);
			uart.databits = (byte)(uintspec (optarg, 7, 8));
			break;
		case 'F':
			_setbits (uart.flags, UART_ATBR);
			uart.flowctrl = (byte)(uintspec (synonym (optarg, flowctrls, FLOWCTRLS), 0, UCHAR_MAX));
			break;
		case 'm':
			_setbits (uart.flags, UART_ATBR);
			uart.mode = (byte)(uintspec (synonym (optarg, modes, MODES), 0, UCHAR_MAX));
		case 'P':
			_setbits (uart.flags, UART_ATBR);
			uart.parity = (byte)(uintspec (synonym (optarg, paritybits, PARITYBITS), 0, UCHAR_MAX));
			break;
		case 'q':
			_setbits (uart.flags, UART_SILENCE);
			break;
		case 'p':
			uart.port.name = optarg;
			break;
		case 'S':
			_setbits (uart.flags, UART_ATBR);
			uart.stopbits = (unsigned)(uintspec (optarg, 1, 2));
			break;
		case 'u':
			_setbits (uart.flags, UART_DEFAULT);
			break;
		case 'v':
			_setbits (uart.flags, UART_VERBOSE);
			break;
		case 'w':
			_setbits (uart.flags, UART_WAKE);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (argc)
	{
		error (1, ENOTSUP, ERROR_TOOMANY);
	}
	openport (&uart.port, uart.flags);
	manager (&uart);
	closeport (&uart.port);
	return (0);
}
Exemplo n.º 10
0
ICCItem *CCodeChain::UnstreamItem (IReadStream *pStream)

//	UnstreamItem
//
//	Load the item from an open stream

	{
	ALERROR error;
	DWORD dwClass;
	ICCItem *pItem;
	ICCItem *pError;

	//	Read the object class

	if (error = pStream->Read((char *)&dwClass, sizeof(dwClass), NULL))
		return CreateSystemError(error);

	//	Instantiation an object of the right class

	if (dwClass == OBJID_CCINTEGER)
		pItem = m_IntegerPool.CreateItem(this);
	else if (dwClass == OBJID_CCDOUBLE)
		pItem = m_DoublePool.CreateItem(this);
	else if (dwClass == OBJID_CCSTRING)
		pItem = m_StringPool.CreateItem(this);
	else if (dwClass == OBJID_CCLINKEDLIST)
		pItem = m_ListPool.CreateItem(this);
	else if (dwClass == OBJID_CCPRIMITIVE)
		pItem = m_PrimitivePool.CreateItem(this);
	else if (dwClass == OBJID_CCNIL)
		pItem = m_pNil;
	else if (dwClass == OBJID_CCTRUE)
		pItem = m_pTrue;
	else if (dwClass == OBJID_CCSYMBOLTABLE)
		pItem = m_SymbolTablePool.CreateItem(this);
	else if (dwClass == OBJID_CCLAMBDA)
		pItem = m_LambdaPool.CreateItem(this);
	else if (dwClass == OBJID_CCATOMTABLE)
		pItem = m_AtomTablePool.CreateItem(this);
	else if (dwClass == OBJID_CCVECTOROLD)
		{
		pItem = new CCVectorOld(this);
		if (pItem == NULL)
			pItem = CreateMemoryError();
		}
	else if (dwClass == OBJID_CCVECTOR)
		pItem = m_VectorPool.CreateItem(this);
	else
		return CreateError(LITERAL("Unknown item type"), NULL);

	//	Check for error

	if (pItem->IsError())
		return pItem;

	//	We need to increment the reference here because the native
	//	create does not.

	pItem->Reset();
	pItem->Reference();

	//	Let the item load the rest

	pError = pItem->Unstream(this, pStream);
	if (pError->IsError())
		{
		pItem->Discard(this);
		return pError;
		}

	pError->Discard(this);

	//	Done

	return pItem;
	}
Exemplo n.º 11
0
ICCItem *CCodeChain::Eval (CEvalContext *pEvalCtx, ICCItem *pItem)

//	Eval
//
//	Evaluates the given item and returns a result

	{
	//	Errors always evaluate to themselves

	if (pItem->IsError())
		return pItem->Reference();

	//	If this item is quoted, then return an unquoted item

	if (pItem->IsQuoted())
		{
		//	If this is a literal symbol table then we need to evaluate its 
		//	values.

		if (pItem->IsSymbolTable())
			return EvalLiteralStruct(pEvalCtx, pItem);

		//	HACK: We clone the item so that when we try to modify a literal list we
		//	mody a copy instead of the original.

		else
			{
			ICCItem *pResult = pItem->Clone(this);
			pResult->ClearQuoted();
			return pResult;
			}
		}

	//	Evaluate differently depending on whether or not
	//	this is an atom or a list. If it is an atom, either return
	//	the value or look up the atom in a symbol table. If the item
	//	is a list, try to evaluate as a function

	else if (pItem->IsIdentifier())
		return Lookup(pEvalCtx, pItem);

	//	If this is an expression (a list with multiple terms) then we
	//	try to evaluate it.

	else if (pItem->IsExpression())
		{
		ICCItem *pFunctionName;
		ICCItem *pFunction;
		ICCItem *pArgs;
		ICCItem *pResult;

		//	The first element of the list is the function

		pFunctionName = pItem->Head(this);

		//	We must have a first element since this is a list (but not Nil)

		ASSERT(pFunctionName);

		//	If this is an identifier, then look up the function
		//	in the global symbols

		if (pFunctionName->IsIdentifier())
			pFunction = LookupFunction(pEvalCtx, pFunctionName);

		//	Otherwise, evaluate it

		else
			pFunction = Eval(pEvalCtx, pFunctionName);

		//	If we get an error, return it

		if (pFunction->IsError())
			return pFunction;

		//	Make sure this is a function

		if (!pFunction->IsFunction())
			{
			pFunction->Discard(this);
			return CreateError(LITERAL("Function name expected"), pFunctionName);
			}

		//	Get the arguments

		pArgs = pItem->Tail(this);

		//	Do it

		pResult = pFunction->Execute(pEvalCtx, pArgs);

		//	Handle error by appending the function call that failed

		if (pResult->IsError())
			{
			CCString *pError = dynamic_cast<CCString *>(pResult);
			if (pError)
				{
				CString sError = pError->GetValue();
				if (!sError.IsBlank())
					{
					char *pPos = sError.GetASCIIZPointer() + sError.GetLength() - 1;
					if (*pPos != '#')
						{
						sError.Append(strPatternSubst(CONSTLIT(" ### %s ###"), pItem->Print(this)));
						pError->SetValue(sError);
						}
					}
				}
			}

		//	Done

		pFunction->Discard(this);
		pArgs->Discard(this);
		return pResult;
		}
	
	//	Anything else is a literal so we return it.

	else
		return pItem->Reference();
	}
Exemplo n.º 12
0
ICCItem *CCodeChain::Lookup (CEvalContext *pCtx, ICCItem *pItem)

//	Lookup
//
//	Returns the binding for this item

	{
	ICCItem *pBinding = NULL;
	BOOL bFound;
	ICCItem *pStart;
	int iFrame, iOffset;

	//	Start somewhere

	if (pCtx->pLocalSymbols)
		pStart = pCtx->pLocalSymbols;
	else
		pStart = pCtx->pLexicalSymbols;

	//	If this item already has been resolved, do a quick lookup

	if (pItem->GetBinding(&iFrame, &iOffset))
		{
		while (iFrame > 0)
			{
			pStart = pStart->GetParent();
			iFrame--;
			}

		pBinding = pStart->LookupByOffset(this, iOffset);
		bFound = TRUE;
		}

	//	Otherwise, do a lookup

	else
		{
		bFound = FALSE;
		iFrame = 0;

		while (!bFound && pStart)
			{
			pBinding = pStart->SimpleLookup(this, pItem, &bFound, &iOffset);
			if (!bFound)
				{
				pBinding->Discard(this);
				pBinding = NULL;
				pStart = pStart->GetParent();
				iFrame++;
				}
			}

		//	If we found it and this is a local frame,
		//	set the resolution info

		if (bFound && pStart->IsLocalFrame())
			pItem->SetBinding(iFrame, iOffset);
		}

	//	If there is no binding, return an error

	if (!bFound)
		{
		ASSERT(pBinding == NULL);
		//pBinding->Discard(this);
		pBinding = CreateError(LITERAL("No binding for symbol"), pItem);
		}

	return pBinding;
	}
Exemplo n.º 13
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	static char const * optv [] =
	{
		"a:d:ef:i:n:p:qrs:tvw",
		"device [device] [...] [> stdout]",
		"Qualcomm Atheros Ethernet PHY Settings",
		"a s\tadvertise capabilities as (s) ['1000Full'|'100Full'|'100Half'|10Full'|'10Half']",
		"d s\tduplex setting is (s) ['half'|'full']",
		"e\tredirect stderr to stdout",
		"f s\tflow control is (s) ['on'|'tx'|'rx'|'off']",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"n s\tauto-negotiate mode is (s) ['on'|'off']",
		"p n\tport number is (n) [" LITERAL (ETH_PORT) "]",
		"q\tquiet mode",
		"r\tread settings instead of write settings",
		"s s\ttransmission speed in mbps is (s) ['10'|'100'|'1000']",
		"v\tverbose mode",
		"w\twrite settings instead of read settings",
		(char const *) (0)
	};
	struct phy_settings settings =
	{
		0,
		1,
		0,
		0,
		0,
		0
	};
	flag_t flags = (flag_t)(0);
	signed c;
	if (getenv (PLCDEVICE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'a':
			if ((c = lookup (optarg, advcap, ADVCAP)) == -1)
			{
				assist (optarg, "capability", advcap, ADVCAP);
			}
			settings.ADVCAPS |= (uint8_t)(c);
			break;
		case 'd':
			if ((c = lookup (optarg, duplex, DUPLEX)) == -1)
			{
				assist (optarg, "duplex", duplex, DUPLEX);
			}
			settings.EDUPLEX = (uint8_t)(c);
			break;
		case 'e':
			dup2 (STDOUT_FILENO, STDERR_FILENO);
			break;
		case 'f':
			if ((c = lookup (optarg, control, CONTROL)) == -1)
			{
				assist (optarg, "control", control, CONTROL);
			}
			settings.EFLOWCONTROL = (uint8_t)(c);
			break;
		case 'n':
			if ((c = lookup (optarg, negotiate, NEGOTIATE)) == -1)
			{
				assist (optarg, "auto-negotiate", negotiate, NEGOTIATE);
			}
			settings.AUTONEGOTIATE = (uint8_t)(c);
			break;
		case 's':
			if ((c = lookup (optarg, speeds, SPEEDS)) == -1)
			{
				assist (optarg, "speed", speeds, SPEEDS);
			}
			settings.ESPEED = (uint8_t)(c);
			break;
		case 't':
			_setbits (flags, PLC_ANALYSE);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'p':
			settings.MCONTROL &= 0x0F;
			settings.MCONTROL |= (unsigned)(uintspec (optarg, 0, 7)) << 4;
			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			break;
		case 'r':
			settings.MCONTROL &= 0xF0;
			settings.MCONTROL |= 0x00;
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			break;
		case 'w':
			settings.MCONTROL &= 0xF0;
			settings.MCONTROL |= 0x01;
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	openchannel (&channel);
	if (!argc)
	{
		PHYSettings (&channel, &settings, flags);
	}
	while ((argc) && (* argv))
	{
		if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices))))
		{
			error (1, errno, PLC_BAD_MAC, * argv);
		}
		PHYSettings (&channel, &settings, flags);
		argc--;
		argv++;
	}
	closechannel (&channel);
	exit (0);
}
Exemplo n.º 14
0
int main (int argc, char const * argv []) 

{
	extern struct channel channel;
	static char const * optv [] = 
	{
		"ei:qv",
		"action priority destination rate ttl operand condition [...] [device] [...]\n\n          where condition is field operator value",
		"CoQos Stream Utility",
		"e\tredirect stderr to stdout",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"q\tquiet mode",
		"v\tverbose mode",
		(char const *) (0)
	};

#include "../plc/plc.c"

	struct connection connection;
	struct MMEClassifier * rule = (struct MMEClassifier *)(&connection.rule.CLASSIFIERS);
	uint16_t * word;
	uint8_t * byte;
	signed code;
	signed c;
	if (getenv (PLCDEVICE)) 
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	while ((c = getoptv (argc, argv, optv)) != -1) 
	{
		switch (c) 
		{
		case 'e':
			dup2 (STDOUT_FILENO, STDERR_FILENO);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			_setbits (plc.flags, PLC_SILENCE);
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			_setbits (plc.flags, PLC_VERBOSE);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	memset (&connection, 0, sizeof (connection));
	if ((code = lookup (* argv++, actions, SIZEOF (actions))) == -1) 
	{
		assist (*--argv, CLASSIFIER_ACTION_NAME, actions, SIZEOF (actions));
	}
	connection.cspec.CONN_CAP = (uint8_t)(code);
	argc--;
	if (!argc) 
	{
		error (1, ECANCELED, "Expected Priority: 0-15");
	}
	connection.cspec.CONN_COQOS_PRIO = (uint8_t)(uintspec (* argv++, 0, 15));
	argc--;
	if (!argc) 
	{
		error (1, ECANCELED, "Expected Destination MAC Address");
	}
	if (!hexencode (connection.APP_DA, sizeof (connection.APP_DA), synonym (* argv++, devices, SIZEOF (devices)))) 
	{
		error (1, errno, "Invalid MAC=[%s]", *--argv);
	}
	argc--;
	if (!argc) 
	{
		error (1, ECANCELED, "Expected Data Rate: 10-9000 (kbps)");
	}
	connection.cspec.CONN_RATE = (uint16_t)(uintspec (* argv++, 1, 9000));
	argc--;
	if (!argc) 
	{
		error (1, ECANCELED, "Expected TTL: 10000-2000000 (microseconds)");
	}
	connection.cspec.CONN_TTL = (uint32_t)(uintspec (* argv++, 10000, 2000000));
	argc--;
	if ((code = lookup (* argv++, operands, SIZEOF (operands))) == -1) 
	{
		assist (*--argv, CLASSIFIER_OPERAND_NAME, operands, SIZEOF (operands));
	}
	connection.rule.MOPERAND = (uint8_t)(code);
	argc--;
	while ((* argv) && (lookup (* argv, controls, SIZEOF (controls)) == -1)) 
	{
		if ((code = lookup (* argv++, fields, SIZEOF (fields))) == -1) 
		{
			assist (*--argv, CLASSIFIER_FIELD_NAME, fields, SIZEOF (fields));
		}
		rule->CR_PID = (uint8_t)(code);
		argc--;
		if ((code = lookup (* argv++, operators, SIZEOF (operators))) == -1) 
		{
			assist (*--argv, CLASSIFIER_OPERATOR_NAME, operators, SIZEOF (operators));
		}
		rule->CR_OPERAND = (uint8_t)(code);
		argc--;
		if (!argc || !* argv) 
		{
			error (1, ENOTSUP, "Have %s '%s' without any value", CLASSIFIER_OPERATOR_NAME, *--argv);
		}
		switch (rule->CR_PID) 
		{
		case FIELD_ETH_SA:
		case FIELD_ETH_DA:
			bytespec (* argv++, rule->CR_VALUE, ETHER_ADDR_LEN);
			break;
		case FIELD_IPV4_SA:
		case FIELD_IPV4_DA:
			ipv4spec (* argv++, rule->CR_VALUE);
			break;
		case FIELD_IPV6_SA:
		case FIELD_IPV6_DA:
			ipv6spec (* argv++, rule->CR_VALUE);
			break;
		case FIELD_VLAN_UP:
		case FIELD_IPV4_TOS:
		case FIELD_IPV4_PROT:
			byte = (uint8_t *)(rule->CR_VALUE);
			*byte = (uint8_t)(basespec (* argv++, 0, sizeof (* byte)));
			break;
		case FIELD_VLAN_ID:
		case FIELD_TCP_SP:
		case FIELD_TCP_DP:
		case FIELD_UDP_SP:
		case FIELD_UDP_DP:
		case FIELD_IP_SP:
		case FIELD_IP_DP:
			word = (uint16_t *)(rule->CR_VALUE);
			*word = (uint16_t)(basespec (* argv++, 0, sizeof (* word)));
			*word = htons (*word);
			break;
		case FIELD_ETH_TYPE:
			word = (uint16_t *)(rule->CR_VALUE);
			*word = (uint16_t)(basespec (* argv++, 0, sizeof (* word)));
			*word = htons (*word);
			break;
		case FIELD_HPAV_MME:
			bytespec (* argv++, rule->CR_VALUE, sizeof (uint8_t) + sizeof (uint16_t));
			byte = (uint8_t *)(rule->CR_VALUE);
			HTOBE16 ((uint16_t)(* ++byte));
			break;
		case FIELD_IPV6_TC:
		case FIELD_IPV6_FL:
		case FIELD_TCP_ACK:
		default:
			error (1, ENOTSUP, "Field '%s' (0x%02X)", argv [-2], rule->CR_PID);
			break;
		}
		connection.rule.NUM_CLASSIFIERS++;
		if (connection.rule.NUM_CLASSIFIERS > RULE_MAX_CLASSIFIERS) 
		{
			error (1, ENOTSUP, "More than %d classifiers in rule", RULE_MAX_CLASSIFIERS);
		}
		rule++;
		argc--;
	}
	connection.cspec.CSPEC_VERSION = 0x0001;
	openchannel (&channel);
	if (!(plc.message = malloc (sizeof (* plc.message)))) 
	{
		error (1, errno, PLC_NOMEMORY);
	}
	if (!argc) 
	{
		add_conn (&plc, &connection);
	}
	while ((argc) && (* argv)) 
	{
		if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices)))) 
		{
			error (1, errno, PLC_BAD_MAC, * argv);
		}
		add_conn (&plc, &connection);
		argc--;
		argv++;
	}
	free (plc.message);
	closechannel (&channel);
	exit (0);
}
Exemplo n.º 15
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	extern struct key const keys [];
	static char const * optv [] =
	{
		"aB:C:d:D:efFHi:IJ:K:l:mMn:N:p:P:QqrRS:st:Tvw:x",
		"device [device] [...]",
		"Qualcomm Atheros INT6x00 Powerline Device Manager",
		"a\tread device attributes using VS_OP_ATTRIBUTES",
		"B n\tperform pushbutton action (n) using MS_PB_ENC [1|2|3|'join'|'leave'|'status']",
		"C n\tflash NVRAM with module (n) using VS_MOD_NVM [1|2|3|'nvm'|'pib'|'both']",
		"d f\tdump and clear watchdog report to file (f) using VS_WD_RPT",
		"D x\tset DAK to (x) for option -J [" DAK1 "]",
		"e\tredirect stderr to stdout",
		"f\tread NVRAM Configuration using VS_GET_NVM",
		"F[F]\tflash [force] NVRAM with PIB and firmware using VS_MOD_NVM",
		"H\tstop host action requests using VS_HOST_ACTION.IND",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"I\tread device identity using VS_RD_MOD",
		"J x\tset NMK on remote device (x) via local device using VS_SET_KEY (see -K)",
		"K x\tset NMK to (x) for options -J and -M [" NMK1 "]",
		"l n\tloop (n) times [" LITERAL (INT6K_LOOP) "]",
		"m\tread network membership information using VS_NW_INFO",
		"M\tset NMK on local device using VS_SET_KEY (see -K)",
		"n f\tread NVM from SDRAM to file (f) using VS_RD_MOD",
		"N f\twrite NVM file (f) to SDRAM using VS_WR_MOD",
		"p f\tread PIB from SDRAM to file (f) using VS_RD_MOD",
		"P f\twrite PIB file (f) to SDRAM using VS_WR_MOD",
		"q\tquiet mode",
		"Q\tquick flash (return immediately)",
		"r\tread hardware and firmware revision using VS_SW_VER",
		"R\treset device using VS_RS_DEV",
		"s\tread SDRAM Configuration using VS_RD_CBLOCK",
		"S f\twrite an SDRAM Configuration file (f) using VS_SET_SDRAM",
		"t n\tread timeout is (n) milliseconds [" LITERAL (CHANNEL_TIMEOUT) "]",
		"T\trestore factory defaults using VS_FAC_DEFAULTS",
		"v\tverbose mode",
		"w n\tpause (n) seconds [" LITERAL (INT6K_WAIT) "]",
		"x\texit on error",
		(char const *) (0)
	};

#include "../plc/plc.c"

	signed loop = INT6K_LOOP;
	signed wait = INT6K_WAIT;
	signed c;
	if (getenv (PLCDEVICE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'a':
			_setbits (plc.flags, PLC_ATTRIBUTES);
			break;
		case 'B':
			_setbits (plc.flags, PLC_PUSH_BUTTON);
			plc.pushbutton = (unsigned)(uintspec (synonym (optarg, buttons, SIZEOF (buttons)), 0, UCHAR_MAX));
			break;
		case 'C':
			_setbits (plc.flags, PLC_FLASH_DEVICE);
			plc.module = (unsigned)(uintspec (synonym (optarg, modules, SIZEOF (modules)), 0, UCHAR_MAX));
			break;
		case 'd':
			_setbits (plc.flags, PLC_WATCHDOG_REPORT);
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.rpt.file = open (plc.rpt.name = optarg, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
			{
				error (1, errno, "%s", plc.rpt.name);
			}

#ifndef WIN32

			chown (optarg, getuid (), getgid ());

#endif

			plc.readaction = 3;
			break;
		case 'D':
			if (!strcmp (optarg, "none"))
			{
				memcpy (plc.DAK, keys [0].DAK, sizeof (plc.DAK));
				break;
			}
			if (!strcmp (optarg, "key1"))
			{
				memcpy (plc.DAK, keys [1].DAK, sizeof (plc.DAK));
				break;
			}
			if (!strcmp (optarg, "key2"))
			{
				memcpy (plc.DAK, keys [2].DAK, sizeof (plc.DAK));
				break;
			}
			if (!hexencode (plc.DAK, sizeof (plc.DAK), (char const *)(optarg)))
			{
				error (1, errno, PLC_BAD_DAK, optarg);
			}
			break;
		case 'e':
			dup2 (STDOUT_FILENO, STDERR_FILENO);
			break;
		case 'f':
			_setbits (plc.flags, PLC_NVRAM_INFO);
			break;
		case 'F':
			_setbits (plc.module, (VS_MODULE_MAC | VS_MODULE_PIB));
			if (_anyset (plc.flags, PLC_FLASH_DEVICE))
			{
				_setbits (plc.module, VS_MODULE_FORCE);
			}
			_setbits (plc.flags, PLC_FLASH_DEVICE);
			break;
		case 'H':
			_setbits (plc.flags, PLC_HOST_ACTION);
			break;
		case 'I':
			_setbits (plc.flags, PLC_READ_IDENTITY);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'J':
			if (!hexencode (plc.RDA, sizeof (plc.RDA), (char const *)(optarg)))
			{
				error (1, errno, PLC_BAD_MAC, optarg);
			}
			_setbits (plc.flags, PLC_SETREMOTEKEY);
			break;
		case 'K':
			if (!strcmp (optarg, "none"))
			{
				memcpy (plc.NMK, keys [0].NMK, sizeof (plc.NMK));
				break;
			}
			if (!strcmp (optarg, "key1"))
			{
				memcpy (plc.NMK, keys [1].NMK, sizeof (plc.NMK));
				break;
			}
			if (!strcmp (optarg, "key2"))
			{
				memcpy (plc.NMK, keys [2].NMK, sizeof (plc.NMK));
				break;
			}
			if (!hexencode (plc.NMK, sizeof (plc.NMK), (char const *)(optarg)))
			{
				error (1, errno, PLC_BAD_NMK, optarg);
			}
			break;
		case 'M':
			_setbits (plc.flags, PLC_SETLOCALKEY);
			break;
		case 'l':
			loop = (unsigned)(uintspec (optarg, 0, UINT_MAX));
			break;
		case 'm':
			_setbits (plc.flags, PLC_NETWORK);
			break;
		case 'N':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.NVM.file = open (plc.NVM.name = optarg, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc.NVM.name);
			}
			if (nvmfile1 (&plc.NVM))
			{
				error (1, errno, "Bad firmware file: %s", plc.NVM.name);
			}
			_setbits (plc.flags, PLC_WRITE_MAC);
			break;
		case 'n':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.nvm.file = open (plc.nvm.name = optarg, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
			{
				error (1, errno, "%s", plc.nvm.name);
			}

#ifndef WIN32

			chown (optarg, getuid (), getgid ());

#endif

			_setbits (plc.flags, PLC_READ_MAC);
			break;
		case 'P':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.PIB.file = open (plc.PIB.name = optarg, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc.PIB.name);
			}
			if (pibfile1 (&plc.PIB))
			{
				error (1, errno, "Bad parameter file: %s", plc.PIB.name);
			}
			_setbits (plc.flags, PLC_WRITE_PIB);
			break;
		case 'p':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.pib.file = open (plc.pib.name = optarg, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
			{
				error (1, errno, "%s", plc.pib.name);
			}

#ifndef WIN32

			chown (optarg, getuid (), getgid ());

#endif

			_setbits (plc.flags, PLC_READ_PIB);
			break;
		case 'Q':
			_setbits (plc.flags, PLC_QUICK_FLASH);
			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			_setbits (plc.flags, PLC_SILENCE);
			break;
		case 'R':
			_setbits (plc.flags, PLC_RESET_DEVICE);
			break;
		case 'r':
			_setbits (plc.flags, PLC_VERSION);
			break;
		case 'S':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.CFG.file = open (plc.CFG.name = optarg, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc.CFG.name);
			}
			if (sdramfile (plc.CFG.file, optarg, plc.flags))
			{
				error (1, ECANCELED, "SDRAM config file %s is corrupt", optarg);
			}
			_setbits (plc.flags, PLC_SDRAM_CONFIG);
			break;
		case 's':
			_setbits (plc.flags, PLC_SDRAM_INFO);
			break;
		case 't':
			channel.timeout = (signed)(uintspec (optarg, 0, UINT_MAX));
			break;
		case 'T':
			_setbits (plc.flags, PLC_FACTORY_DEFAULTS);
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			_setbits (plc.flags, PLC_VERBOSE);
			break;
		case 'V':
			_setbits (plc.flags, PLC_SNIFFER);
			plc.action = (uint8_t)(uintspec (optarg, 0, UCHAR_MAX));
			break;
		case 'w':
			wait = (unsigned)(uintspec (optarg, 0, 3600));
			break;
		case 'x':
			_setbits (plc.flags, PLC_BAILOUT);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 1)
	{
		if (plc.nvm.file != -1)
		{
			error (1, ECANCELED, PLC_NODEVICE);
		}
		if (plc.pib.file != -1)
		{
			error (1, ECANCELED, PLC_NODEVICE);
		}
		if (plc.rpt.file != -1)
		{
			error (1, ECANCELED, PLC_NODEVICE);
		}
	}
	openchannel (&channel);
	if (!(plc.message = malloc (sizeof (* plc.message))))
	{
		error (1, errno, PLC_NOMEMORY);
	}
	if (!argc)
	{
		manager (&plc, loop, wait);
	}
	while ((argc) && (* argv))
	{
		if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices))))
		{
			error (1, errno, PLC_BAD_MAC, * argv);
		}
		manager (&plc, loop, wait);
		argc--;
		argv++;
	}
	free (plc.message);
	closechannel (&channel);
	exit (0);
}
Exemplo n.º 16
0
int main (int argc, char const * argv []) 

{ 
	extern struct channel channel; 
	static char const * optv [] = 
	{ 
		"cCdi:p:qs:t:vx", 
		"", 
		"Qualcomm Atheros Electric Vehicle Supply Equipment Emulator", 
		"c\tprint template configuration file on stdout", 
		"C\tstop on count mismatch", 
		"d\tdisplay debug information", 

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]", 

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]", 

#endif

		"p s\tconfiguration profile is (s) [" LITERAL (PROFILE) "]", 
		"s s\tconfiguration section is (s) [" LITERAL (SECTION) "]", 
		"q\tquiet mode", 
		"t n\tread timeout is (n) milliseconds [" LITERAL (SLAC_TIMEOUT) "]", 
		"v\tverbose mode", 
		"x\texit on error", 
		(char const *) (0)
	}; 
	struct session session; 
	struct message message; 
	char const * profile = PROFILE; 
	char const * section = SECTION; 
	signed c; 
	memset (& session, 0, sizeof (session)); 
	memset (& message, 0, sizeof (message)); 
	channel.timeout = SLAC_TIMEOUT; 
	if (getenv (PLCDEVICE)) 
	{ 

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE)); 

#else

		channel.ifname = strdup (getenv (PLCDEVICE)); 

#endif

	} 
	optind = 1; 
	while (~ (c = getoptv (argc, argv, optv))) 
	{ 
		switch (c) 
		{ 
		case 'c': 
			configure (); 
			return (0); 
		case 'C': 
			_setbits (session.flags, SLAC_COMPARE); 
			break; 
		case 'd': 
			_setbits (session.flags, (SLAC_VERBOSE | SLAC_SESSION)); 
			break; 
		case 'i': 

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg); 

#else

			channel.ifname = optarg; 

#endif

			break; 
		case 'p': 
			profile = optarg; 
			break; 
		case 's': 
			section = optarg; 
			break; 
		case 'q': 
			_setbits (channel.flags, CHANNEL_SILENCE);
			_setbits (session.flags, SLAC_SILENCE); 
			break; 
		case 't': 
			channel.timeout = (signed) (uintspec (optarg, 0, UINT_MAX)); 
			break; 
		case 'v': 
			_setbits (channel.flags, CHANNEL_VERBOSE); 
			break; 
		case 'x': 
			session.exit = session.exit? 0: 1; 
			break; 
		default: 
			break; 
		} 
	} 
	argc -= optind; 
	argv += optind; 
	openchannel (&channel);
	desuid ();
	if (argc) 
	{ 
		slac_debug (& session, 1, __func__, ERROR_TOOMANY); 
	} 
	initialize (& session, profile, section); 
	identifier (& session, & channel); 
	if (evse_cm_set_key (& session, & channel, & message)) 
	{ 
		slac_debug (& session, 1, __func__, "Can't set key."); 
	} 
	sleep (session.settletime); 
	while (session.state) 
	{ 
		if (session.state == EVSE_STATE_UNOCCUPIED) 
		{ 
			UnoccupiedState (& session, & channel, & message); 
			continue; 
		} 
		if (session.state == EVSE_STATE_UNMATCHED) 
		{ 
			UnmatchedState (& session, & channel, & message); 
			continue; 
		} 
		if (session.state == EVSE_STATE_MATCHED) 
		{ 
			MatchedState (& session, & channel, & message); 
			continue; 
		} 
		slac_debug (& session, 1, __func__, "Illegal state!"); 
	} 
	closechannel (& channel); 
	exit (0); 
} 
Exemplo n.º 17
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	struct message message;
	static char const * optv [] =
	{
		"e:i:qt:v",
		PUTOPTV_S_DIVINE,
		"Qualcomm Atheros Ethernet Frame Read Utility",
		"e x\tethertype is (x) [" LITERAL (EFRU_ETHERTYPE) "]",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (s) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (n) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"q\tsuppress normal output",
		"t n\tread timeout is (n) milliseconds [" LITERAL (CHANNEL_FOREVER) "]",
		"v\tverbose messages on stdout",
		(char const *) (0)
	};
	flag_t flags = (flag_t)(0);
	signed length;
	signed c;
	if (getenv (EFRU_INTERFACE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (EFRU_INTERFACE));

#else

		channel.ifname = strdup (getenv (EFRU_INTERFACE));

#endif

	}
	optind = 1;
	channel.type = EFRU_ETHERTYPE;
	channel.timeout = CHANNEL_FOREVER;
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'e':
			channel.type = (uint16_t)(basespec (optarg, 16, sizeof (channel.type)));
			break;
		case 'i':

#if defined (WIN32)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'q':
			_setbits (flags, EFRU_SILENCE);
			break;
		case 't':
			channel.timeout = (signed)(uintspec (optarg, 0, UINT_MAX));
			break;
		case 'v':
			_setbits (flags, EFRU_VERBOSE);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (argc)
	{
		error (1, ECANCELED, ERROR_TOOMANY);
	}
	openchannel (&channel);
	while ((length = readpacket (&channel, &message, sizeof (message))) >= 0)
	{
		hexdump (&message, 0, length, stdout);
	}
	closechannel (&channel);
	return (0);
}
Exemplo n.º 18
0
CString CNPServer::CmdLogin (ClientCtx *pClient, const CDataPackStruct &Data)
	{
	//	If we're already logged in, then fail (for now)

	if (pClient->ACL != aclNoLogin)
		return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("You are already logged in."));

	//	Get the data

	CString sName = Data.GetStringItem(1);
	CString sPassword = Data.GetStringItem(2);

	Lock();

	//	Check for overlord

	if (strCompare(sName, LITERAL("overlord")) == 0)
		{
		//	Check the password

		if (strCompare(sPassword, m_sOverlordPassword) != 0)
			{
			Unlock();
			return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Invalid name or password."));
			}

		//	Complete login

		pClient->sName = LITERAL("Overlord");
		pClient->ACL = aclOverlord;
		pClient->pSovereign = m_pUniv->GetSovereign(m_pUniv->GetOverlordUNID());

		Log("[%d] Login as Overlord", pClient->dwClientID);
		}

	//	Check for guest

	else if (strCompare(sName, LITERAL("guest")) == 0)
		{
		//	Not allowed, for now

		Unlock();
		return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Guest access not allowed in this universe."));
		}

	//	A player

	else
		{
		//	Look-up the player

		CNPHumanPlayer *pPlayer;
		if (m_Players.Lookup(sName, (CObject **)&pPlayer) != NOERROR)
			{
			Unlock();
			return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Invalid name or password."));
			}

		//	Check the password

		if (strCompare(sPassword, pPlayer->GetPassword()) != 0)
			{
			Unlock();
			return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Invalid name or password."));
			}

		//	Complete login

		pClient->sName = sName;
		pClient->ACL = aclPlayer;
		pClient->pSovereign = m_pUniv->GetSovereign(pPlayer->GetSovereignID());

		Log("[%d] Login as %s", pClient->dwClientID, sName.GetASCIIZPointer());
		}

	//	Compose reply

	CDataPackStruct Reply;
	Reply.AppendInteger(RES_LOGIN);
	Reply.AppendInteger(pClient->pSovereign->GetUNID());
	Reply.AppendInteger(m_pUniv->GetTurn());
	Reply.AppendString(pClient->pSovereign->GetName());

	Unlock();

	return Reply.SerializeToString();
	}
Exemplo n.º 19
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	static char const * optv [] =
	{
		"ei:qv",
		"cid",
		"CoQos Stream Utility",
		"e\tredirect stderr to stdout",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"q\tquiet mode",
		"v\tverbose mode",
		(char const *) (0)
	};

#include "../plc/plc.c"

	uint16_t cid;
	signed c;
	if (getenv (PLCDEVICE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'e':
			dup2 (STDOUT_FILENO, STDERR_FILENO);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			_setbits (plc.flags, PLC_SILENCE);
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			_setbits (plc.flags, PLC_VERBOSE);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (!argc)
	{
		error (1, ECANCELED, "Missing CID");
	}
	if (!hexencode ((uint8_t *)(&cid), sizeof (cid), * argv++))
	{
		error (1, EINVAL, "CID=[%s]", *--argv);
	}
	cid = htons (cid);
	argc--;
	openchannel (&channel);
	if (!(plc.message = malloc (sizeof (* plc.message))))
	{
		error (1, errno, PLC_NOMEMORY);
	}
	if (!argc)
	{
		rel_conn (&plc, cid);
	}
	while ((argc) && (* argv))
	{
		if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices))))
		{
			error (1, errno, PLC_BAD_MAC, * argv);
		}
		rel_conn (&plc, cid);
		argc--;
		argv++;
	}
	free (plc.message);
	closechannel (&channel);
	exit (0);
}
Exemplo n.º 20
0
CString CNPServer::CmdNewPlayer (ClientCtx *pClient, const CDataPackStruct &Data)
	{
	ALERROR error;

	//	Unless we're overlord or the universe has open access
	//	we cannot create a new player

	if (pClient->ACL != aclOverlord	&& !m_bOpenAccess)
		return ComposeCmdFail(pClient, CMD_NEW_PLAYER, LITERAL("You are not authorized to create new player accounts."));

	//	Create the new player

	CString sEmperorName = Data.GetStringItem(1);
	CString sPassword = Data.GetStringItem(2);
	CString sEmpireName = Data.GetStringItem(3);

	Lock();

	//	Make sure there isn't a player with that name already

	if (m_Players.Lookup(sEmperorName, NULL) == NOERROR)
		{
		Unlock();
		return ComposeCmdFail(pClient, CMD_NEW_PLAYER, LITERAL("A player with that name already exists."));
		}

	//	Pick a capital for this player

	int i;
	CNPWorld *pCapital = NULL;
	for (i = 0; i < m_pUniv->GetNullPointCount(); i++)
		{
		CNPNullPoint *pNP = m_pUniv->GetNullPointByIndex(i);

		int j;
		for (j = 0; j < pNP->GetWorldCount(); j++)
			{
			CNPWorld *pWorld = pNP->GetWorld(j);

			if (pWorld->HasTrait(traitReservedCapital)
					&& pWorld->GetSovereign()->GetUNID() == m_pUniv->GetIndependentUNID())
				{
				pCapital = pWorld;
				break;
				}
			}

		if (pCapital)
			break;
		}

	//	If we could not find a capital then we cannot create a new empire

	if (pCapital == NULL)
		{
		Unlock();
		return ComposeCmdFail(pClient, CMD_NEW_PLAYER, LITERAL("A world suitable for an empire's capital could not be found."));
		}

	//	Create the player

	CNPHumanPlayer *pPlayer;
	if (error = CNPHumanPlayer::Create(m_pUniv, sEmperorName, sPassword, sEmpireName, pCapital, &pPlayer))
		{
		Unlock();
		return ComposeCmdError(pClient, CMD_NEW_PLAYER, error);
		}

	//	Add it to our list

	if (error = m_Players.AddEntry(sEmperorName, pPlayer))
		{
#ifdef LATER
		//	delete the sovereign and the player
#endif
		Unlock();
		return ComposeCmdError(pClient, CMD_NEW_PLAYER, error);
		}

	Unlock();

	Log("[%d] New account created for %s", pClient->dwClientID, sEmperorName.GetASCIIZPointer());
	return ComposeCmdSuccess(pClient, CMD_NEW_PLAYER);
	}
Exemplo n.º 21
0
int main (int argc, char const * argv []) 

{
	static char const * optv [] = 
	{
		"e:m:o:p:iqrvw:",
		"",
		"Weeder Solid State Relay Module Controller",
		"e n\techo is (n) [" LITERAL (WEEDER_ECHO) "]",
		"m n\tmode is (n) [" LITERAL (WEEDER_MODE) "]",
		"o s\tunit order is (s) [" WEEDER_UNITS "]",
		"p f\tport is (f) [" WEEDER_PORT "]",
		"q\tquiet mode",
		"r\tread attenuator value",
		"v\tverbose mode",
		"w n\twait (n) millseconds [" LITERAL (WEEDER_WAIT) "]",
		(char const *) (0)
	};
	struct _file_ port = 
	{
		-1,
		WEEDER_PORT
	};

#if defined (WIN32)

	HANDLE hSerial;
	DCB dcbSerial = 
	{
		0
	};

#else

	struct termios termios;

#endif

	char const * units = WEEDER_UNITS;
	unsigned wait = WEEDER_WAIT;
	unsigned echo = WEEDER_ECHO;
	unsigned mode = WEEDER_MODE;
	unsigned data = 0;
	flag_t flags = (flag_t)(0);
	signed c;
	optind = 1;
	if (getenv ("WEEDER")) 
	{
		port.name = strdup (getenv ("WEEDER"));
	}
	while ((c = getoptv (argc, argv, optv)) != -1) 
	{
		switch (c) 
		{
		case 'e':
			echo = (unsigned)(uintspec (synonym (optarg, modes, SIZEOF (modes)), 0, 1));
			break;
		case 'm':
			mode = (unsigned)(uintspec (synonym (optarg, modes, SIZEOF (modes)), 0, 1));
			break;
		case 'n':
			_setbits (flags, WEEDER_NEWLINE);
			break;
		case 'o':
			units = optarg;
			break;
		case 'p':
			port.name = optarg;
			break;
		case 'w':
			wait = (unsigned)(uintspec (optarg, 5, 100));
			break;
		case 'q':
			_setbits (flags, WEEDER_SILENCE);
			break;
		case 'r':
			_setbits (flags, WEEDER_DISPLAY);
			break;
		case 'v':
			_setbits (flags, WEEDER_VERBOSE);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if ((argc) && (* argv)) 
	{
		data = (unsigned)(uintspec (* argv, 0, 0x7F));
	}

#if defined (WIN32)

	hSerial = CreateFile (port.name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
	if (hSerial == INVALID_HANDLE_VALUE) 
	{
		error (1, errno, FILE_CANTOPEN, port.name);
	}
	dcbSerial.DCBlength = sizeof (dcbSerial);
	if (!GetCommState (hSerial, &dcbSerial)) 
	{
		error (1, 0, FILE_CANTREAD " state", port.name);
	}
	dcbSerial.BaudRate = CBR_9600;
	dcbSerial.ByteSize = 8;
	dcbSerial.StopBits = ONESTOPBIT;
	dcbSerial.Parity = NOPARITY;
	if (!SetCommState (hSerial, &dcbSerial)) 
	{
		error (1, 0, FILE_CANTSAVE, port.name);
	}
	CloseHandle (hSerial);
	if ((port.file = open (port.name, O_BINARY | O_RDWR)) == -1) 
	{
		error (1, errno, FILE_CANTOPEN " state", port.name);
	}

#else

	if ((port.file = open (port.name, O_RDWR|O_NOCTTY|O_NDELAY)) == -1) 
	{
		error (1, 0, FILE_CANTOPEN, port.name);
	}
	tcgetattr (port.file, &termios);
	termios.c_cflag = CS8;
	cfsetospeed (&termios, B9600);
	tcsetattr (port.file, TCSANOW, &termios);

#endif

	function1 (&port, units, wait, echo);
	if ((argc) && (* argv)) 
	{
		function2 (&port, units, wait, mode, data);
	}
	if (_anyset (flags, WEEDER_DISPLAY)) 
	{
		function3 (&port, units, wait);
	}
	close (port.file);
	exit (0);
}
Exemplo n.º 22
0
CString CNPServer::CmdView (ClientCtx *pClient, const CDataPackStruct &Data)
	{
	CDataPackStruct Reply;
	CString sError;

	//	Get parameters

	DWORD dwUNID = Data.GetIntegerItem(1);

	Lock();

	//	If we don't know about this object then we can't view it

	if (!ValidAccess(pClient, dwUNID))
		{
		Unlock();
		return ComposeCmdFail(pClient, CMD_VIEW, LITERAL("Unknown object."));
		}

	//	Return data

	switch (GetUNIDType(dwUNID))
		{
		case unidFleet:
			{
			CNPFleet *pFleet;
			if (!ValidFleetAccess(pClient, dwUNID, false, &pFleet, &sError))
				{
				Unlock();
				return sError;
				}

			Reply.AppendInteger(RES_VIEW_FLEET);
			Reply.AppendInteger(dwUNID);
			Reply.AppendInteger(pFleet->GetSovereign()->GetUNID());
			Reply.AppendInteger(pFleet->GetLocation());
			Reply.AppendInteger(pFleet->GetDest());
			Reply.AppendInteger(pFleet->GetInTransit());

			CDataPackStruct *pAssets;
			Reply.AppendNewStruct(&pAssets);
			pFleet->GetAssetList().Save(pAssets);
			break;
			}

		case unidNullPoint:
			{
			int i;

			CNPNullPoint *pNP;
			if (!ValidNullPointAccess(pClient, dwUNID, false, &pNP, &sError))
				{
				Unlock();
				return sError;
				}

			Reply.AppendInteger(RES_VIEW_NULLPOINT);
			Reply.AppendInteger(dwUNID);
			Reply.AppendInteger(pNP->GetX());
			Reply.AppendInteger(pNP->GetY());
			Reply.AppendInteger(pNP->GetWorld(0)->GetUNID());

			//	Links
			CDataPackStruct *pLinks;
			Reply.AppendNewStruct(&pLinks);
			for (i = 0; i < pNP->GetLinkCount(); i++)
				{
				CNPNullPoint *pDest = pNP->GetLinkDest(i);
				pLinks->AppendInteger(pDest->GetUNID());
				}

			//	Fleets
			CDataPackStruct *pFleets;
			Reply.AppendNewStruct(&pFleets);
			CNPFleet *pNextFleet = pNP->GetFirstFleet();
			while (pNextFleet)
				{
				if (ValidAccess(pClient, pNextFleet->GetUNID()))
					pFleets->AppendInteger(pNextFleet->GetUNID());

				pNextFleet = pNextFleet->GetNextFleet();
				}
			break;
			}

		case unidSovereign:
			{
			CNPSovereign *pSovereign = m_pUniv->GetSovereign(dwUNID);
			if (pSovereign == NULL)
				{
				Unlock();
				return ComposeCmdFail(pClient, CMD_VIEW, LITERAL("Unexpected error: object not found."));
				}

			Reply.AppendInteger(RES_VIEW_SOVEREIGN);
			Reply.AppendInteger(dwUNID);
			Reply.AppendString(pSovereign->GetName());
			Reply.AppendInteger(pSovereign->GetCapital());
			break;
			}

		case unidWorld:
			{
			CNPWorld *pWorld = m_pUniv->GetWorld(dwUNID);
			if (pWorld == NULL)
				{
				Unlock();
				return ComposeCmdFail(pClient, CMD_VIEW, LITERAL("Unexpected error: object not found."));
				}

			Reply.AppendInteger(RES_VIEW_WORLD);
			Reply.AppendInteger(dwUNID);
			Reply.AppendInteger(pWorld->GetSovereign()->GetUNID());
			Reply.AppendInteger(pWorld->GetLocation());
			Reply.AppendInteger(pWorld->GetPopulation());
			Reply.AppendInteger(pWorld->GetTechLevel());
			Reply.AppendInteger(pWorld->GetEfficiency());

			CIntArray Traits;
			pWorld->EnumTraits(&Traits);
			Reply.AppendIntArray(Traits);
			break;
			}

		default:
			Unlock();
			return ComposeCmdFail(pClient, CMD_VIEW, LITERAL("Unknown object."));
		}

	Unlock();

	return Reply.SerializeToString();
	}
Exemplo n.º 23
0
ALERROR CNPUniverse::AddRandomTrait (CreateCtx &Ctx,
									 CNPWorld *pWorld, 
									 TraitType iSection, 
									 int iCount, 
									 CXMLElement *pTraitTable)

//	AddRandomTrait
//
//	Adds traits from the given table

	{
	int iSectionStart;

	//	Find the beginning of the section

	iSectionStart = 0;
	while (iSectionStart < pTraitTable->GetContentElementCount()
			&& pTraitTable->GetContentElement(iSectionStart)->GetAttributeInteger(CONSTLIT("Table")) != iSection)
		iSectionStart++;

	//	If not found, we fail

	if (iSectionStart == pTraitTable->GetContentElementCount())
		{
		Ctx.sError = LITERAL("Unable to find appropriate trait table section");
		return ERR_FAIL;
		}

	//	Keep looping for each trait to add

	for (int i = 0; i < iCount; i++)
		{
		//	Keep trying until we successfully add some trait or
		//	until we get sick of trying.

		for (int j = 0; j < 10; j++)
			{
			int iRoll = mathRandom(1, 100);
			int iEntry = iSectionStart;
			CXMLElement *pEntry;

			while (iEntry < pTraitTable->GetContentElementCount()
					&& (pEntry = pTraitTable->GetContentElement(iEntry))
					&& (pEntry->GetAttributeInteger(CONSTLIT("Table")) == iSection)
					&& (iRoll = iRoll - pEntry->GetAttributeInteger(CONSTLIT("Prob"))) > 0)
				iEntry++;

			//	If not found, we fail

			if (iRoll > 0)
				{
				Ctx.sError = LITERAL("Trait table probabilities do not add up to 100%");
				return ERR_FAIL;
				}

			//	Add the trait. If we add it successfully then we stop
			//	the inner loop.

			if (AddTrait(pWorld, pTraitTable, pEntry, *Ctx.pSymbols))
				break;
			}
		}

	return NOERROR;
	}
Exemplo n.º 24
0
/* static */ nsresult
GeckoPrintService::TranslateSettings (GtkPrintSettings *aGtkSettings,
				      GtkPageSetup *aPageSetup,
				      GtkPrinter *aPrinter,
				      const nsACString &aSourceFile,
				      PRInt16 aPrintFrames,
				      PRBool aIsForPrinting,
				      nsIPrintSettings *aSettings)
{
  NS_ENSURE_ARG (aGtkSettings);
  NS_ENSURE_ARG (aPageSetup);

  GtkPrintCapabilities capabilities = GtkPrintCapabilities (0);
  if (aIsForPrinting) {
    NS_ENSURE_TRUE (aPrinter, NS_ERROR_FAILURE);

    capabilities = gtk_printer_get_capabilities (aPrinter);
  }

  /* Initialisation */
  aSettings->SetIsInitializedFromPrinter (PR_FALSE); /* FIXME: PR_TRUE? */
  aSettings->SetIsInitializedFromPrefs (PR_FALSE); /* FIXME: PR_TRUE? */
  aSettings->SetPrintSilent (PR_FALSE);
  aSettings->SetShowPrintProgress (PR_TRUE);

  /* We always print PS to a file and then hand that off to gtk-print */
  aSettings->SetPrinterName (LITERAL ("PostScript/default"));

  if (aIsForPrinting) {
    aSettings->SetPrintToFile (PR_TRUE);

    nsString sourceFile;
    NS_CStringToUTF16 (aSourceFile,
		       NS_CSTRING_ENCODING_NATIVE_FILESYSTEM,
		       sourceFile);

    aSettings->SetToFileName (sourceFile.get ());
  } else {
    /* Otherwise mozilla will create the file nevertheless and 
     * fail since we haven't set a name!
     */
    aSettings->SetPrintToFile (PR_FALSE);
  }

  /* This is the time between printing each page, in ms.
   * It 'gives the user more time to press cancel' !
   * We don't want any of this nonsense, so set this to a low value,
   * just enough to update the print dialogue.
   */
  aSettings->SetPrintPageDelay (50);

  if (aIsForPrinting) {
#ifdef HAVE_NSIPRINTSETTINGS_SETOUTPUTFORMAT
    NS_ENSURE_TRUE (aPrinter, NS_ERROR_FAILURE);

    const char *format = gtk_print_settings_get (aGtkSettings, GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT);
    if (!format)
      format = "ps";

    if (strcmp (format, "pdf") == 0 &&
	gtk_printer_accepts_pdf (aPrinter)) {
      aSettings->SetOutputFormat (nsIPrintSettings::kOutputFormatPDF);
    } else if (strcmp (format, "ps") == 0 &&
	       gtk_printer_accepts_ps (aPrinter)) {
      aSettings->SetOutputFormat (nsIPrintSettings::kOutputFormatPS);
    } else {
      g_warning ("Output format '%s' specified, but printer '%s' does not support it!",
		 format, gtk_printer_get_name (aPrinter));
      return NS_ERROR_FAILURE;
    }
#endif
	  
    int n_copies = gtk_print_settings_get_n_copies (aGtkSettings);
    if (n_copies <= 0)
      return NS_ERROR_FAILURE;
    if (capabilities & GTK_PRINT_CAPABILITY_COPIES) {
      aSettings->SetNumCopies (1);
    } else {
      /* We have to copy them ourself */
      aSettings->SetNumCopies (n_copies);
      gtk_print_settings_set_n_copies (aGtkSettings, 1);
    }

    gboolean reverse = gtk_print_settings_get_reverse (aGtkSettings);
    if (capabilities & GTK_PRINT_CAPABILITY_REVERSE) {
      aSettings->SetPrintReversed (PR_FALSE);
    } else {
      aSettings->SetPrintReversed (reverse);
      gtk_print_settings_set_reverse (aGtkSettings, FALSE);
    }

    GtkPageSet pageSet = gtk_print_settings_get_page_set (aGtkSettings);
    aSettings->SetPrintOptions (nsIPrintSettings::kPrintEvenPages,
			        pageSet != GTK_PAGE_SET_ODD);
    aSettings->SetPrintOptions (nsIPrintSettings::kPrintEvenPages,
			        pageSet != GTK_PAGE_SET_EVEN);

    GtkPrintPages printPages = gtk_print_settings_get_print_pages (aGtkSettings);
    switch (printPages) {
      case GTK_PRINT_PAGES_RANGES: {
        int numRanges = 0;
        GtkPageRange *pageRanges = gtk_print_settings_get_page_ranges (aGtkSettings, &numRanges);
        if (numRanges > 0) {
          /* FIXME: We can only support one range, ignore more ranges or raise error? */
          aSettings->SetPrintRange (nsIPrintSettings::kRangeSpecifiedPageRange);
	  /* Gecko page numbers start at 1, while gtk page numbers start at 0 */
          aSettings->SetStartPageRange (pageRanges[0].start + 1);
	  aSettings->SetEndPageRange (pageRanges[0].end + 1);

	  g_free (pageRanges);
          break;
        }
	/* Fall-through to PAGES_ALL */
      }
      case GTK_PRINT_PAGES_CURRENT:
        /* not supported, fall through */
      case GTK_PRINT_PAGES_ALL:
        aSettings->SetPrintRange (nsIPrintSettings::kRangeAllPages);
        break;
        /* FIXME: we need some custom ranges here, "Selection" and "Focused Frame" */
    }
  } else {
    aSettings->SetPrintOptions (nsIPrintSettings::kPrintEvenPages, PR_TRUE);
    aSettings->SetPrintOptions (nsIPrintSettings::kPrintEvenPages, PR_TRUE);
    aSettings->SetPrintReversed (PR_FALSE);
    aSettings->SetPrintRange (nsIPrintSettings::kRangeAllPages);
  }

  /* And clear those in the settings, so the printer doesn't try to apply them too */
  gtk_print_settings_set_print_pages (aGtkSettings, GTK_PRINT_PAGES_ALL);
  gtk_print_settings_set_page_ranges (aGtkSettings, NULL, 0);
  gtk_print_settings_set_page_set (aGtkSettings, GTK_PAGE_SET_ALL);

  /* We must use the page setup here instead of the print settings, see gtk bug #485685 */
  switch (gtk_page_setup_get_orientation (aPageSetup)) {
    case GTK_PAGE_ORIENTATION_PORTRAIT:
    case GTK_PAGE_ORIENTATION_REVERSE_PORTRAIT: /* not supported */
      aSettings->SetOrientation (nsIPrintSettings::kPortraitOrientation);
      break;
    case GTK_PAGE_ORIENTATION_LANDSCAPE:
    case GTK_PAGE_ORIENTATION_REVERSE_LANDSCAPE: /* not supported */
      aSettings->SetOrientation (nsIPrintSettings::kLandscapeOrientation);
      break;
  }

  aSettings->SetPrintInColor (gtk_print_settings_get_use_color (aGtkSettings));

  aSettings->SetPaperSizeUnit(nsIPrintSettings::kPaperSizeMillimeters);

#ifdef HAVE_NSIPRINTSETTINGS_SETPAPERSIZE
  aSettings->SetPaperSize (nsIPrintSettings::kPaperSizeDefined);
#endif

  GtkPaperSize *paperSize = gtk_page_setup_get_paper_size (aPageSetup);
  if (!paperSize) {
    return NS_ERROR_FAILURE;
  }

  aSettings->SetPaperSizeType (nsIPrintSettings::kPaperSizeDefined);
  aSettings->SetPaperWidth (gtk_paper_size_get_width (paperSize, GTK_UNIT_MM));
  aSettings->SetPaperHeight (gtk_paper_size_get_height (paperSize, GTK_UNIT_MM));

#ifdef HAVE_NSIPRINTSETTINGS_SETPAPERNAME
  aSettings->SetPaperName (NS_ConvertUTF8toUTF16 (gtk_paper_size_get_name (paperSize)).get ());
#else
{
  /* Mozilla bug https://bugzilla.mozilla.org/show_bug.cgi?id=307404
   * means that we cannot actually use any paper sizes except mozilla's
   * builtin list, and we must refer to them *by name*!
  */
  static const struct {
    const char gtkPaperName[13];
    const char mozPaperName[10];
  } paperTable [] = {
    { GTK_PAPER_NAME_A5, "A5" },
    { GTK_PAPER_NAME_A4, "A4" },
    { GTK_PAPER_NAME_A3, "A3" },
    { GTK_PAPER_NAME_LETTER, "Letter" },
    { GTK_PAPER_NAME_LEGAL, "Legal" },
    { GTK_PAPER_NAME_EXECUTIVE, "Executive" },
  };

  const char *paperName = gtk_paper_size_get_name (paperSize);
	
  PRUint32 i;
  for (i = 0; i < G_N_ELEMENTS (paperTable); i++) {
    if (g_ascii_strcasecmp (paperTable[i].gtkPaperName, paperName) == 0) {
      paperName = paperTable[i].mozPaperName;
      break;
    }
  }
  if (i == G_N_ELEMENTS (paperTable)) {
    /* Not in table, fall back to A4 */
    g_warning ("Unknown paper name '%s', falling back to A4", gtk_paper_size_get_name (paperSize));
    paperName = paperTable[1].mozPaperName;
  }

  aSettings->SetPaperName (NS_ConvertUTF8toUTF16 (paperName).get ());
}
#endif /* !HAVE_NSIPRINTSETTINGS_SETPAPERNAME */

  /* Sucky mozilla wants margins in inch! */
  aSettings->SetMarginTop (gtk_page_setup_get_top_margin (aPageSetup, GTK_UNIT_INCH));
  aSettings->SetMarginBottom (gtk_page_setup_get_bottom_margin (aPageSetup, GTK_UNIT_INCH));
  aSettings->SetMarginLeft (gtk_page_setup_get_left_margin (aPageSetup, GTK_UNIT_INCH));
  aSettings->SetMarginRight (gtk_page_setup_get_right_margin (aPageSetup, GTK_UNIT_INCH));

  aSettings->SetHeaderStrLeft (eel_gconf_get_boolean (CONF_PRINT_PAGE_TITLE) ? LITERAL ("&T") : LITERAL (""));
  aSettings->SetHeaderStrCenter (LITERAL (""));
  aSettings->SetHeaderStrRight (eel_gconf_get_boolean (CONF_PRINT_PAGE_URL) ? LITERAL ("&U") : LITERAL (""));
  aSettings->SetFooterStrLeft (eel_gconf_get_boolean (CONF_PRINT_PAGE_NUMBERS) ? LITERAL ("&PT") : LITERAL (""));
  aSettings->SetFooterStrCenter (LITERAL (""));
  aSettings->SetFooterStrRight (eel_gconf_get_boolean (CONF_PRINT_DATE) ? LITERAL ("&D") : LITERAL (""));

  aSettings->SetPrintFrameType (aPrintFrames);
  aSettings->SetPrintFrameTypeUsage (nsIPrintSettings::kUseSettingWhenPossible);

  /* FIXME: only if GTK_PRINT_CAPABILITY_SCALE is not set? */
  aSettings->SetScaling (gtk_print_settings_get_scale (aGtkSettings) / 100.0);
  gtk_print_settings_set_scale (aGtkSettings, 1.0);

  aSettings->SetShrinkToFit (PR_FALSE); /* FIXME setting */
  
  aSettings->SetPrintBGColors (eel_gconf_get_boolean (CONF_PRINT_BG_COLORS) != FALSE);
  aSettings->SetPrintBGImages (eel_gconf_get_boolean (CONF_PRINT_BG_IMAGES) != FALSE);

  /* aSettings->SetPlexName (LITERAL ("default")); */
  /* aSettings->SetColorspace (LITERAL ("default")); */
  /* aSettings->SetResolutionName (LITERAL ("default")); */
  /* aSettings->SetDownloadFonts (PR_TRUE); */

  /* Unset those setting that we can handle, so they don't get applied
   * again for the print job.
   */
  /* gtk_print_settings_set_collate (aGtkSettings, FALSE); not yet */
  /* FIXME: Unset the orientation for the print job? */
  /* gtk_page_setup_set_orientation (aPageSetup, GTK_PAGE_ORIENTATION_PORTRAIT); */
  /* FIXME: unset output format -> "ps" ? */

  return NS_OK;
}
Exemplo n.º 25
0
ALERROR CNPUniverse::InitFromXML (CXMLElement *pTemplate, CSymbolTable &Symbols, CString *retsError)

//	InitFromXML
//
//	Initializes from an XML template

	{
	ALERROR error;
	int iNullPoints;
	CreateCtx Ctx;

	//	Initialize context

	Ctx.pTemplate = pTemplate;
	Ctx.pSymbols = &Symbols;

	//	Get some elements

	CXMLElement *pOptions = pTemplate->GetContentElementByTag(CONSTLIT("DefineOptions"));

	//	Initialize

	iNullPoints = pOptions->GetAttributeInteger(CONSTLIT("NullPointCount"));
	m_iMaxPlayers = pOptions->GetAttributeInteger(CONSTLIT("MaxPlayers"));
	m_iBaseAnno = pOptions->GetAttributeInteger(CONSTLIT("BaseAnno"));
	m_iTurn = 0;

	//	Create the Overlord sovereign

	CNPSovereign *pOverlord;
	if (error = CreateSovereign(LITERAL("The Universe"), NULL, NULL, &pOverlord))
		{
		*retsError = LITERAL("Unable to create Overlord sovereign");
		return error;
		}

	m_dwOverlord = pOverlord->GetUNID();

	//	Create the default, independent sovereign

	CNPSovereign *pIndep;
	if (error = CreateSovereign(LITERAL("Independent"), NULL, NULL, &pIndep))
		{
		*retsError = LITERAL("Unable to create independent sovereign");
		return error;
		}

	m_dwIndependent = pIndep->GetUNID();

	//	Create the null point network.

	if (error = CreateNullPointNetwork(iNullPoints))
		{
		*retsError = LITERAL("Unable to create null point network");
		return error;
		}

	//	Create worlds

	if (error = CreateRandomWorlds(Ctx))
		{
		*retsError = LITERAL("Unable to create worlds");
		return error;
		}

	//	Next turn

	m_dwNextTurn = ::GetTickCount() + (DWORD)(SecondsPerOro * 1000);

	return NOERROR;
	}
Exemplo n.º 26
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	extern void terminate (signo_t);
	static char const * optv [] =
	{
		"dFi:n:N:p:P:qS:t:vw:x",
		"-N file -P file [-S file]",
		"Qualcomm Atheros Panther/Lynx PLC Host Daemon",
		"d\texecute in background as daemon",
		"F [F]\tflash [force] non-volatile memory",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"n f\tread firmware from device into file (f)",
		"N f\tfirmware file is (f)",
		"p f\tread parameters from device into file (f)",
		"P f\tparameter file is (f)",
		"q\tquiet mode",
		"S f\tsoftloader file is (f)",
		"t n\tread timeout is (n) milliseconds [" LITERAL (CHANNEL_TIMEOUT) "]",
		"v\tverbose mode",
		"w n\twakeup every (n) seconds [" LITERAL (PLC_LONGTIME) "]",
		"x\texit on error",
		(char const *) (0)
	};

#include "../plc/plc.c"

	struct sigaction sa;
	char const * socketname = SOCKETNAME;
	signed c;
	if (getenv (PLCDEVICE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	plc.timer = PLC_LONGTIME;
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'd':
			_setbits (plc.flags, PLC_DAEMON);
			break;
		case 'F':
			_setbits (plc.module, (VS_MODULE_MAC | VS_MODULE_PIB));
			if (_anyset (plc.flags, PLC_FLASH_DEVICE))
			{
				_setbits (plc.module, VS_MODULE_FORCE);
			}
			_setbits (plc.flags, PLC_FLASH_DEVICE);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'N':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.NVM.file = open (plc.NVM.name = optarg, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc.NVM.name);
			}
			if (nvmfile2 (&plc.NVM))
			{
				error (1, errno, "Bad firmware file: %s", plc.NVM.name);
			}
			_setbits (plc.flags, PLC_WRITE_MAC);
			break;
		case 'n':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.nvm.file = open (plc.nvm.name = optarg, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
			{
				error (1, errno, "%s", plc.nvm.name);
			}
			break;
		case 'P':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.PIB.file = open (plc.PIB.name = optarg, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc.PIB.name);
			}
			if (pibfile2 (&plc.PIB))
			{
				error (1, errno, "Bad parameter file: %s", plc.PIB.name);
			}
			_setbits (plc.flags, PLC_WRITE_PIB);
			break;
		case 'p':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.pib.file = open (plc.pib.name = optarg, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
			{
				error (1, errno, "%s", plc.pib.name);
			}
			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			_setbits (plc.flags, PLC_SILENCE);
			break;
		case 'S':
			if (!checkfilename (optarg))
			{
				error (1, EINVAL, "%s", optarg);
			}
			if ((plc.CFG.file = open (plc.CFG.name = optarg, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc.CFG.name);
			}
			if (nvmfile2 (&plc.CFG))
			{
				error (1, errno, "Bad firmware file: %s", plc.CFG.name);
			}
			break;
		case 't':
			channel.timeout = (signed)(uintspec (optarg, 0, UINT_MAX));
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			_setbits (plc.flags, PLC_VERBOSE);
			break;
		case 'w':
			plc.timer = (unsigned)(uintspec (optarg, 1, 3600));
			break;
		case 'x':
			_setbits (plc.flags, PLC_BAILOUT);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (argc)
	{
		error (1, ENOTSUP, ERROR_TOOMANY);
	}
	if (plc.NVM.file == -1)
	{
		error (1, ECANCELED, "No host NVM file named");
	}
	if (plc.PIB.file == -1)
	{
		error (1, ECANCELED, "No host PIB file named");
	}
	if (plc.CFG.file == -1)
	{
		if (_anyset (plc.flags, PLC_FLASH_DEVICE))
		{
			error (1, ECANCELED, "No Softloader file named");
		}
	}
	if (plc.nvm.file == -1)
	{
		if ((plc.nvm.file = open (plc.nvm.name = NEWNVM, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
		{
			error (1, errno, "%s", plc.nvm.name);
		}
	}
	if (plc.pib.file == -1)
	{
		if ((plc.pib.file = open (plc.pib.name = NEWPIB, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1)
		{
			error (1, errno, "%s", plc.pib.name);
		}
	}

#ifndef WIN32

	if (_anyset (plc.flags, PLC_DAEMON))
	{
		pid_t pid = fork ();
		if (pid < 0)
		{
			error (1, errno, "Can't start daemon");
		}
		if (pid > 0)
		{
			exit (0);
		}
	}
	memset (&sa, 0, sizeof (struct sigaction));
	sa.sa_handler = terminate;
	sigaction (SIGTERM, &sa, (struct sigaction *)(0));
	sigaction (SIGQUIT, &sa, (struct sigaction *)(0));
	sigaction (SIGTSTP, &sa, (struct sigaction *)(0));
	sigaction (SIGINT, &sa, (struct sigaction *)(0));
	sigaction (SIGHUP, &sa, (struct sigaction *)(0));

#endif

	openchannel (&channel);
	if (!(plc.message = malloc (sizeof (* plc.message))))
	{
		error (1, errno, PLC_NOMEMORY);
	}
	function (&plc, socketname);
	free (plc.message);
	closechannel (&channel);
	exit (0);
}
Exemplo n.º 27
0
int main (int argc, char const * argv [])

{
	extern const unsigned char ct_unescape [];
	static char const * optv [] =
	{
		"print user/group names in alphabetcial order in columns",
		PUTOPTV_S_DIVINE,
		"c:e:gHnw:uRT",
		"c n\tcolumn count is (n) [" LITERAL (COUNT) "]",
		"w n\tscreen width is (n) [" LITERAL (WIDTH) "]",
		"e s\texpression is s [.+]",
		"g\tlist groupnames",
		"H\tregular expression help",
		"u\tlist usernames",
		"n\tnumber list items",
		"R\tregular expression help",
		"T\tescape sequence rules",
		(char *) (0)
	};
	LIST list;
	regexp * regex = (regexp *) (0);
	char const * expression = ".+";
	flag_t flags = (flag_t) (0);
	size_t count = COUNT;
	size_t width = WIDTH;
	bool index = false;
	int c;
	while (~ (c = getoptv (argc, argv, optv)))
	{
		switch (c)
		{
		case 'w':
			width = uintspec (optarg, 1, 132);
			break;
		case 'c':
			count = uintspec (optarg, 1, 16);
			break;
		case 'g':
			_setbits (flags, WHOM_B_GRP);
			break;
		case 'e':
			expression = optarg;
			break;
		case 'n':
			index = true;
			break;
		case 'u':
			_setbits (flags, WHOM_B_USR);
			break;
		case 'H':
			_setbits (flags, WHOM_B_SHW);
			break;
		case 'R':
			regexhelp ();
			exit (0);
		case 'T':
			chruescmap (ct_unescape, REGEX_C_ESC);
			exit (0);
		default: 
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (_anyset (flags, (WHOM_B_SHW)))
	{
		regex = regexmake (expression);
		regexshow (regex);
		return (0);
	}
	if (_allclr (flags, (WHOM_B_USR | WHOM_B_GRP)))
	{
		_setbits (flags, (WHOM_B_USR | WHOM_B_GRP));
	}
	setpwent ();
	listcreate (& list, _LISTSIZE);
	regex = regexmake (expression);
	function (& list, regex, flags);
	regex = regexfree (regex);
	listcolumn (& list, stdout, width, count, index);
	listdelete (& list);
	endpwent ();
	exit (0);
}
static int32 GetFormattingInfo(const WIDECHAR* Format, FFormatInfo& OutInfo)
{
	const WIDECHAR* FormatStart = Format++;

	// Skip flags
	while (*Format == LITERAL(WIDECHAR, '#') || *Format == LITERAL(WIDECHAR, '0') || *Format == LITERAL(WIDECHAR, '-')
		   || *Format == LITERAL(WIDECHAR, ' ') || *Format == LITERAL(WIDECHAR, '+') || *Format == LITERAL(WIDECHAR, '\''))
	{
		Format++;
	}

	OutInfo.HasDynamicWidth = false;

	// Skip width
	while ((*Format >= LITERAL(WIDECHAR, '0') && *Format <= LITERAL(WIDECHAR, '9')) || *Format == LITERAL(WIDECHAR, '*'))
	{
		if (*Format == LITERAL(WIDECHAR, '*'))
		{
			OutInfo.HasDynamicWidth = true;
		}
		Format++;
	}

	// Skip precision
	if (*Format == LITERAL(WIDECHAR, '.'))
	{
		Format++;
		while ((*Format >= LITERAL(WIDECHAR, '0') && *Format <= LITERAL(WIDECHAR, '9')) || *Format == LITERAL(WIDECHAR, '*'))
		{
			if (*Format == LITERAL(WIDECHAR, '*'))
			{
				OutInfo.HasDynamicWidth = true;
			}
			Format++;
		}
	}

	OutInfo.LengthModifier = 0;
	if (*Format == LITERAL(WIDECHAR, 'h') || *Format == LITERAL(WIDECHAR, 'l') || *Format == LITERAL(WIDECHAR, 'j') || *Format == LITERAL(WIDECHAR, 't')
		|| *Format == LITERAL(WIDECHAR, 'z') || *Format == LITERAL(WIDECHAR, 'q') || *Format == LITERAL(WIDECHAR, 'L'))
	{
		OutInfo.LengthModifier = *Format++;
		if (*Format == LITERAL(WIDECHAR, 'h'))
		{
			OutInfo.LengthModifier = 'H';
			Format++;
		}
		else if (*Format == LITERAL(WIDECHAR, 'l'))
		{
			OutInfo.LengthModifier = 'L';
			Format++;
		}
	}

	OutInfo.Type = *Format++;

	const int32 FormatLength = Format - FormatStart;

	FMemory::Memcpy(OutInfo.Format, FormatStart, FormatLength * sizeof(WIDECHAR));
	OutInfo.Format[FormatLength] = 0;

	return FormatLength;
}
Exemplo n.º 29
0
Arquivo: vm.c Projeto: txus/terrorvm
VALUE VM_run(STATE)
{
  Debugger_load_current_file(state);

  int *ip = CURR_FRAME->fn->code;

  while(1) {
    switch(*ip) {
      case NOOP:
        break;
      case SETLINE: { // debugging
        ip++;
        Debugger_setline(state, *ip);
        break;
      }
      case PUSH: {
        Debugger_evaluate(state);
        ip++;
        debugi("PUSH %i", *ip);
        VALUE value = LITERAL(*ip);
        Stack_push(STACK, value);
        break;
      }
      case PUSHTRUE: {
        Debugger_evaluate(state);
        debugi("PUSHTRUE");
        Stack_push(STACK, TrueObject);
        break;
      }
      case PUSHFALSE: {
        Debugger_evaluate(state);
        debugi("PUSHFALSE");
        Stack_push(STACK, FalseObject);
        break;
      }
      case PUSHNIL: {
        Debugger_evaluate(state);
        debugi("PUSHNIL");
        Stack_push(STACK, NilObject);
        break;
      }
      case JMP: {
        Debugger_evaluate(state);
        ip++;
        int jump = *ip;
        debugi("JMP %i", jump);
        while(jump--) ip++;
        break;
      }
      case JIF: {
        Debugger_evaluate(state);
        ip++;
        int jump = *ip;
        debugi("JIF %i", jump);

        VALUE value = Stack_pop(STACK);
        if (value == FalseObject || value == NilObject) {
          while(jump--) ip++;
        }

        break;
      }
      case JIT: {
        Debugger_evaluate(state);
        ip++;
        int jump = *ip;
        debugi("JIT %i", jump);

        VALUE value = Stack_pop(STACK);
        if (value != FalseObject && value != NilObject) {
          while(jump--) ip++;
        }

        break;
      }
      case GOTO: {
        Debugger_evaluate(state);
        ip++;
        int jump = *ip - 2;

        debugi("GOTO %i", jump);

        ip = CURR_FRAME->fn->code;
        while(jump--) ip++;

        break;
      }
      case GETSLOT: {
        Debugger_evaluate(state);
        ip++;
        debugi("GETSLOT %i", *ip);
        VALUE receiver = Stack_pop(STACK);
        VALUE slot     = LITERAL(*ip);

        check(receiver->type != NilType, "Tried to get a slot from nil.");
        check(slot->type == StringType, "Slot name must be a String.");

        VALUE value = Value_get(receiver, VAL2STR(slot));
        check(value, "Undefined slot %s on object type %i.", VAL2STR(slot), receiver->type);

        Stack_push(STACK, value);
        break;
      }
      case SETSLOT: {
        Debugger_evaluate(state);
        ip++;
        debugi("SETSLOT %i", *ip);
        VALUE value    = Stack_pop(STACK);
        VALUE receiver = Stack_pop(STACK);
        VALUE slot     = LITERAL(*ip);

        check(receiver->type != NilType, "Tried to set a slot on nil.");
        check(slot->type == StringType, "Slot name must be a String.");

        Value_set(state, receiver, VAL2STR(slot), value);
        Stack_push(STACK, value); // push the rhs back to the stack
        break;
      }
      case DEFN: {
        Debugger_evaluate(state);
        ip++;
        debugi("DEFN %i", *ip);
        VALUE fn_name = LITERAL(*ip);
        bstring state_fn = bfromcstr(VAL2STR(fn_name));
        VALUE closure = Closure_new(state, STATE_FN(state_fn), CURR_FRAME);
        bdestroy(state_fn);
        Stack_push(STACK, closure);
        break;
      }
      case MAKEVEC: {
        Debugger_evaluate(state);
        ip++;
        debugi("MAKEVEC %i", *ip);
        int count = *ip;
        DArray *array = DArray_create(sizeof(VALUE), count || 1);

        while(count--) {
          VALUE elem = Stack_pop(STACK);
          check(elem, "Stack underflow.");
          GC_protect(elem);
          DArray_push(array, elem);
        }

        VALUE vector = Vector_new(state, array);
        Stack_push(STACK, vector);
        Vector_each(vector, ^ void (VALUE element) {
          GC_unprotect(element);
        });
        break;
      }
      case SEND: {
        Debugger_evaluate(state);
        ip++;
        int op1 = *ip;
        ip++;
        int op2 = *ip;

        debugi("SEND %i %i", op1, op2);

        VALUE name = LITERAL(op1);
        int argcount = op2;

        DArray *locals = DArray_create(sizeof(VALUE), argcount+1);
        while(argcount--) {
          DArray_push(locals, Stack_pop(STACK));
        }
        VALUE receiver = Stack_pop(STACK);

        // Special chicken-egg case. We cannot define "apply" as a native method
        // on Closure, since that triggers the creation of a new closure ad
        // infinitum, so we have to handle this special function here.
        if(receiver->type == ClosureType &&
           strcmp(VAL2STR(name), "apply") == 0) {

          state->ret = ip; // save where we want to return
          ip = Function_call(state, VAL2FN(receiver), CURR_FRAME->self, locals, VAL2STR(name));
          break;
        }

        VALUE closure = Value_get(receiver, VAL2STR(name));
        check(closure, "Undefined slot %s on object type %i.", VAL2STR(name), receiver->type);

        if (closure->type != ClosureType && closure != NilObject) {
          // GETSLOT
          Stack_push(STACK, closure);
          DArray_destroy(locals);
          break;
        }

#ifdef OPTIMIZE_SEND
        if(op2 == 1 && strcmp(VAL2STR(name), "[]") == 0) { // getslot
          VALUE key = (VALUE)DArray_at(locals, 0);
          Stack_push(STACK, Value_get(receiver, VAL2STR(key)));
          DArray_destroy(locals);
          break;
        }

        if(op2 == 2 && strcmp(VAL2STR(name), "[]=") == 0) { // setslot
          VALUE key   = (VALUE)DArray_at(locals, 0);
          VALUE value = (VALUE)DArray_at(locals, 1);
          Value_set(receiver, VAL2STR(key), value);
          Stack_push(STACK, value);
          DArray_destroy(locals);
          break;
        }
#endif

        state->ret = ip; // save where we want to return
        ip = Function_call(state, VAL2FN(closure), receiver, locals, VAL2STR(name));
        break;
      }
      case PUSHLOBBY: {
        Debugger_evaluate(state);
        debugi("PUSHLOBBY");
        Stack_push(STACK, state->lobby);
        break;
      }
      case PUSHSELF: {
        Debugger_evaluate(state);
        debugi("PUSHSELF");
        Stack_push(STACK, CURR_FRAME->self);
        break;
      }
      case PUSHLOCAL: {
        Debugger_evaluate(state);
        ip++;
        Stack_push(STACK, LOCAL(*ip));
        debugi("PUSHLOCAL %i", *ip);
        break;
      }
      case PUSHLOCALDEPTH: {
        Debugger_evaluate(state);
        ip++;
        int depth = *ip;
        ip++;
        Stack_push(STACK, DEEPLOCAL(depth, *ip));
        debugi("PUSHLOCALDEPTH %i %i", depth, *ip);
        break;
      }
      case SETLOCAL: {
        Debugger_evaluate(state);
        ip++;
        debugi("SETLOCAL %i", *ip);
        LOCALSET(*ip, Stack_peek(STACK));
        break;
      }
      case SETLOCALDEPTH: {
        Debugger_evaluate(state);
        ip++;
        int depth = *ip;
        ip++;
        debugi("SETLOCAL %i %i", depth, *ip);
        DEEPLOCALSET(depth, *ip, Stack_peek(STACK));
        break;
      }
      case POP: {
        Debugger_evaluate(state);
        ip++;
        int count = *ip;
        debugi("POP %i", count);
        check(Stack_count(STACK) >= count, "Stack underflow.");
        while(count--) Stack_pop(STACK);
        break;
      }
      case RET: {
        Debugger_evaluate(state);
        debugi("RET");
        CallFrame *old_frame = Stack_pop(FRAMES);

        ip = old_frame->ret;

        CallFrame_destroy(old_frame);

        check(Stack_count(STACK) > 0, "Stack underflow.");

        if (ip == NULL) return Stack_pop(STACK); // if there's nowhere to return, exit

        break;
      }
      case DUMP: {
        Debugger_evaluate(state);
        debugi("DUMP");
        Stack_print(state, STACK);
        DArray *literals = CURR_FRAME->fn->literals;
        printf("--LITERALS (%i)--\n", DArray_count(literals));
        Value_print_all(state, literals);

        DArray *locals = CURR_FRAME->locals;
        printf("--LOCALS (%i)--\n", DArray_count(locals));
        Value_print_all(state, locals);
        break;
      }
    }
Exemplo n.º 30
0
int main (int argc, char const * argv [])

{
	extern struct channel channel;
	static char const * optv [] =
	{
		"d:ei:p:qr:v",
		"[device] [...]",
		"Qualcomm Atheros 16-bit MDIO Register Editor",
		"d n\tdata value is (n) [0x0000]",
		"e\tredirect stderr to stdout",

#if defined (WINPCAP) || defined (LIBPCAP)

		"i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]",

#else

		"i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]",

#endif

		"p n\tPHY number (n) [0xFF]",
		"q\tquiet mode",
		"r n\tregister number (n) [0xFF]",
		"v\tverbose mode",
		(char const *) (0)
	};
	uint8_t mode = 0;
	uint8_t phy = 0;
	uint8_t reg = 0;
	uint16_t data = 0;
	signed c;
	if (getenv (PLCDEVICE))
	{

#if defined (WINPCAP) || defined (LIBPCAP)

		channel.ifindex = atoi (getenv (PLCDEVICE));

#else

		channel.ifname = strdup (getenv (PLCDEVICE));

#endif

	}
	optind = 1;
	while ((c = getoptv (argc, argv, optv)) != -1)
	{
		switch (c)
		{
		case 'd':
			mode = 1;
			data = (uint16_t)(uintspec (optarg, 0, 0xFFFF));
			break;
		case 'e':
			dup2 (STDOUT_FILENO, STDERR_FILENO);
			break;
		case 'i':

#if defined (WINPCAP) || defined (LIBPCAP)

			channel.ifindex = atoi (optarg);

#else

			channel.ifname = optarg;

#endif

			break;
		case 'p':
			phy = (uint8_t)(uintspec (optarg, 0, 0x1F));
			break;
		case 'q':
			_setbits (channel.flags, CHANNEL_SILENCE);
			break;
		case 'r':
			reg = (uint8_t)(uintspec (optarg, 0, 0x1F));
			break;
		case 'v':
			_setbits (channel.flags, CHANNEL_VERBOSE);
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	openchannel (&channel);
	desuid ();
	if (!argc)
	{
		function (&channel, mode, phy, reg, data);
	}
	while ((argc) && (* argv))
	{
		if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices))))
		{
			error (1, errno, PLC_BAD_MAC, * argv);
		}
		function (&channel, mode, phy, reg, data);
		argv++;
		argc--;
	}
	closechannel (&channel);
	return (0);
}