Example #1
0
oexINT CLog::Log( oexCSTR x_pFile, oexINT x_nLine, oexCSTR8 x_pFunction, oexINT x_uLevel, oexCSTR x_pErr, oexINT x_nErr, oexUINT x_uSkip )
{_STT();
	// Ensure valid reporting level
	if ( x_uLevel < m_uLevel )
		return x_nErr;

	// Log count
	if ( 1 == oexIncrement( &m_lInLog ) )
	{
		_oexTRY
		{
			// Create log file if needed
			if ( !m_file.IsOpen() )
				if ( !OpenLogFile() )
				{	oexDecrement( &m_lInLog );
					return x_nErr;
				} // end if

			if ( !oexCHECK_PTR( x_pFile ) )
				x_pFile = oexT( "???" );

			if ( !oexCHECK_PTR( x_pFunction ) )
				x_pFunction = "???";

			CStr sLevel;
			oexCSTR pLevel = oexT( "" );
			if ( eHalt == x_uLevel )
				pLevel = oexT( "Halt" );
			else if ( eError == x_uLevel )
				pLevel = oexT( "Error" );
			else if ( eWarning == x_uLevel )
				pLevel = oexT( "Warning" );
			else if ( eNotice == x_uLevel )
				pLevel = oexT( "Notice" );
			else
				pLevel = sLevel.Mks( (int)x_uLevel ).Ptr();

			CStr sLog;

			// Add file / line number
			oexUINT uThreadId = oexGetCurThreadId();
#if defined( oexFULL_FILENAME_IN_LOG )
			sLog << x_pFile << oexT( ":(" ) << x_nLine << oexT( ")" )
#else
			sLog << oexGetFileName( x_pFile ) << oexT( ":(" ) << x_nLine << oexT( ")" )
#endif
				 << oexFmt( oexT( " : Thread %u (0x%x)" ), uThreadId, uThreadId ) << oexNL;

			// Write out the time
#if defined( OEX_NANOSECONDS )
			sLog << oexLocalTimeStr( oexT( " -> Local: %Y/%c/%d - %g:%m:%s.%l.%u.%n" oexNL8 ) );
#else
			sLog << oexLocalTimeStr( oexT( " -> Local Time  : %Y/%c/%d - %g:%m:%s.%l.%u" oexNL8 ) );
#endif

#if defined( OEXLIB_STACK_TRACING )
			CStackTrace::CStack *p = oexSt().GetStack();
			if ( p )
			{
				sLog << oexT(         " -> Thread Name : " ) << p->GetName() << oexNL;
			
				// +++ This really doesn't make a lot of sense in the log file, more for stack tracing
//				sLog << oexT(         " -> Tag         : " ) << p->GetTag() << oexNL;
//				sLog << oexFmt( oexT( " -> CheckPoint  : %d (0x%x)" oexNL8 ), p->GetCheckpoint(), p->GetCheckpoint() );

			} // end if
#endif
			// Add function name if available
			if ( x_pFunction && *x_pFunction )
				sLog << oexT(         " -> Function    : " ) << oexMbToStrPtr( x_pFunction ) << oexT( "()" oexNL8 );

			// Add error level
			sLog << oexT(             " -> Level       : " ) << pLevel;

			// Add system error info
			if ( x_nErr )
				sLog << CStr().Print( oexT( " : 0x%X (%d) : " ), x_nErr, x_nErr )
					 << os::CTrace::GetErrorMsg( x_nErr ).RTrim( oexT( "\r\n" ) );

			sLog << oexNL;

			// Write out the user error string if available
			if ( oexCHECK_PTR( x_pErr ) )
				sLog << oexT( " -> " oexNL8 " -> " ) << CStr( x_pErr ).Replace( oexNL, oexT( "" oexNL8 " -> " ) ) << oexNL;

#if defined( oexBACKTRACE_IN_LOG )
			// Write out the backtrace
			sLog << oexT( " -> " )
				 << os::CTrace::GetBacktrace( x_uSkip ).Replace( oexNL, oexT( "" oexNL8 " -> " ) )
				 << oexNL;
#endif

			// Just to space things out
			sLog << oexNL;

			// Write out the string to the file
			m_file.Write( oexStrToMb( sLog ) );

#if defined( oexPRINT_LOGS )

		// Print if user wants to see this level
		if ( oexPRINT_LOGS <= x_uLevel )
			oexEcho( sLog.Ptr() );
#endif

		}
		_oexCATCH_ALL()
		{
		} // end catch

	} // end if
Example #2
0
void CGUIString::GenerateTextCall(const CGUI *pGUI,
								  SFeedback &Feedback,
								  CStrIntern DefaultFont,
								  const int &from, const int &to,
								  const bool FirstLine,
								  const IGUIObject *pObject) const
{
	// Reset width and height, because they will be determined with incrementation
	//  or comparisons.
	Feedback.Reset();

	// Check out which text chunk this is within.
	//bool match_found = false;
	std::vector<TextChunk>::const_iterator itTextChunk;
	for (itTextChunk=m_TextChunks.begin(); itTextChunk!=m_TextChunks.end(); ++itTextChunk)
	{
		// Get the area that is overlapped by both the TextChunk and
		//  by the from/to inputted.
		int _from, _to;
		_from = std::max(from, itTextChunk->m_From);
		_to = std::min(to, itTextChunk->m_To);

		// If from is larger than to, than they are not overlapping
		if (_to == _from && itTextChunk->m_From == itTextChunk->m_To)
		{
			// These should never be able to have more than one tag.
			ENSURE(itTextChunk->m_Tags.size()==1);

			// Now do second check
			//  because icons and images are placed on exactly one position
			//  in the words-list, it can be counted twice if placed on an
			//  edge. But there is always only one logical preference that
			//  we want. This check filters the unwanted.

			// it's in the end of one word, and the icon
			//  should really belong to the beginning of the next one
			if (_to == to && to >= 1)
			{
				if (GetRawString()[to-1] == ' ' ||
					GetRawString()[to-1] == '-' ||
					GetRawString()[to-1] == '\n')
					continue;
			}
			// This std::string is just a break
			if (_from == from && from >= 1)
			{
				if (GetRawString()[from] == '\n' &&
					GetRawString()[from-1] != '\n' &&
					GetRawString()[from-1] != ' ' &&
					GetRawString()[from-1] != '-')
					continue;
			}

			// Single tags
			if (itTextChunk->m_Tags[0].m_TagType == CGUIString::TextChunk::Tag::TAG_IMGLEFT)
			{
				// Only add the image if the icon exists.
				if (pGUI->IconExists(itTextChunk->m_Tags[0].m_TagValue))
				{
					Feedback.m_Images[SFeedback::Left].push_back(itTextChunk->m_Tags[0].m_TagValue);
				}
				else if (pObject)
				{
					LOGERROR(L"Trying to use an [imgleft]-tag with an undefined icon (\"%hs\").", itTextChunk->m_Tags[0].m_TagValue.c_str());
				}
			}
			else
			if (itTextChunk->m_Tags[0].m_TagType == CGUIString::TextChunk::Tag::TAG_IMGRIGHT)
			{
				// Only add the image if the icon exists.
				if (pGUI->IconExists(itTextChunk->m_Tags[0].m_TagValue))
				{
					Feedback.m_Images[SFeedback::Right].push_back(itTextChunk->m_Tags[0].m_TagValue);
				}
				else if (pObject)
				{
					LOGERROR(L"Trying to use an [imgright]-tag with an undefined icon (\"%hs\").", itTextChunk->m_Tags[0].m_TagValue.c_str());
				}
			}
			else
			if (itTextChunk->m_Tags[0].m_TagType == CGUIString::TextChunk::Tag::TAG_ICON)
			{
				// Only add the image if the icon exists.
				if (pGUI->IconExists(itTextChunk->m_Tags[0].m_TagValue))
				{
					// We'll need to setup a text-call that will point
					//  to the icon, this is to be able to iterate
					//  through the text-calls without having to
					//  complex the structure virtually for nothing more.
					SGUIText::STextCall TextCall;

					// Also add it to the sprites being rendered.
					SGUIText::SSpriteCall SpriteCall;

					// Get Icon from icon database in pGUI
					SGUIIcon icon = pGUI->GetIcon(itTextChunk->m_Tags[0].m_TagValue);

					CSize size = icon.m_Size;

					// append width, and make maximum height the height.
					Feedback.m_Size.cx += size.cx;
					Feedback.m_Size.cy = std::max(Feedback.m_Size.cy, size.cy);

					// These are also needed later
					TextCall.m_Size = size;
					SpriteCall.m_Area = size;

					// Handle additional attributes
					std::vector<TextChunk::Tag::TagAttribute>::const_iterator att_it;
					for(att_it = itTextChunk->m_Tags[0].m_TagAttributes.begin(); att_it != itTextChunk->m_Tags[0].m_TagAttributes.end(); ++att_it)
					{
						TextChunk::Tag::TagAttribute tagAttrib = (TextChunk::Tag::TagAttribute)(*att_it);

						if (tagAttrib.attrib == "displace" && !tagAttrib.value.empty())
						{	//Displace the sprite
							CSize displacement;
							// Parse the value
							if (!GUI<CSize>::ParseString(CStr(tagAttrib.value).FromUTF8(), displacement))
								LOGERROR(L"Error parsing 'displace' value for tag [ICON]");
							else
								SpriteCall.m_Area += displacement;

						}
						else if(tagAttrib.attrib == "tooltip")
						{
							SpriteCall.m_Tooltip = CStr(tagAttrib.value).FromUTF8();
						}
						else if(tagAttrib.attrib == "tooltip_style")
						{
							SpriteCall.m_TooltipStyle = CStr(tagAttrib.value).FromUTF8();
						}
					}

					SpriteCall.m_Sprite = icon.m_SpriteName;
					SpriteCall.m_CellID = icon.m_CellID;

					// Add sprite call
					Feedback.m_SpriteCalls.push_back(SpriteCall);

					// Finalize text call
					TextCall.m_pSpriteCall = &Feedback.m_SpriteCalls.back();

					// Add text call
					Feedback.m_TextCalls.push_back(TextCall);
				}
				else if (pObject)
				{
					LOGERROR(L"Trying to use an [icon]-tag with an undefined icon (\"%hs\").", itTextChunk->m_Tags[0].m_TagValue.c_str());
				}
			}
		}
		else
		if (_to > _from && !Feedback.m_NewLine)
		{
			SGUIText::STextCall TextCall;

			// Set defaults
			TextCall.m_Font = DefaultFont;
			TextCall.m_UseCustomColor = false;

			// Extract substd::string from RawString.
			TextCall.m_String = GetRawString().substr(_from, _to-_from);

			// Go through tags and apply changes.
			std::vector<CGUIString::TextChunk::Tag>::const_iterator it2;
			for (it2 = itTextChunk->m_Tags.begin(); it2 != itTextChunk->m_Tags.end(); ++it2)
			{
				if (it2->m_TagType == CGUIString::TextChunk::Tag::TAG_COLOR)
				{
					// Set custom color
					TextCall.m_UseCustomColor = true;

					// Try parsing the color std::string
					if (!GUI<CColor>::ParseString(CStr(it2->m_TagValue).FromUTF8(), TextCall.m_Color))
					{
						if (pObject)
							LOGERROR(L"Error parsing the value of a [color]-tag in GUI text when reading object \"%hs\".", pObject->GetPresentableName().c_str());
					}
				}
				else
				if (it2->m_TagType == CGUIString::TextChunk::Tag::TAG_FONT)
				{
					// TODO Gee: (2004-08-15) Check if Font exists?
					TextCall.m_Font = CStrIntern(it2->m_TagValue);
				}
			}

			// Calculate the size of the font
			CSize size;
			int cx, cy;
			CFontMetrics font (TextCall.m_Font);
			font.CalculateStringSize(TextCall.m_String.c_str(), cx, cy);
			// For anything other than the first line, the line spacing
			// needs to be considered rather than just the height of the text
			if (! FirstLine)
				cy = font.GetLineSpacing();

			size.cx = (float)cx;
			size.cy = (float)cy;

			// Append width, and make maximum height the height.
			Feedback.m_Size.cx += size.cx;
			Feedback.m_Size.cy = std::max(Feedback.m_Size.cy, size.cy);

			// These are also needed later
			TextCall.m_Size = size;

			if (! TextCall.m_String.empty())
			{
				if (TextCall.m_String[0] == '\n')
				{
					Feedback.m_NewLine = true;
				}
			}

			// Add text-chunk
			Feedback.m_TextCalls.push_back(TextCall);
		}
	}
}
Example #3
0
int fromRsh()
{	int hosti,porti,hosto,porto;

	if( 0 < _fromRsh ) return 1;
	if( 0 > _fromRsh ) return 0;

	_fromRsh = -1;

	if( getenv("HOME") == NULL ) return 0;
	if( getenv("SHELL") == NULL ) return 0;

	if( file_issock(0) < 0 ) return 0;
	if( file_issock(1) < 0 ) return 0;

	if( getenv("SSH_CONNECTION") != 0 ){
		if( sock_isAFUNIX(0)
		 || sockFromMyself(0)
		 || sock_isconnectedX(0,0)
		){
			_fromRsh = IS_SSH;
			return 0;
		}
	}

/*
	if( file_issock(2) < 0 ) return 0;
*/
{
	int hostl,portl;
	hostl = sockHostport(0,&portl);
	/*
	 * If this DeleGate is invoked from rshd, the port number must be
	 *   shell(cmd) == 514/tcp
	 */
	if( portl != 514 ){
		return 0;
	}
	/*
	 * Now this DeleGate might be working as a proxy rsh daemon.
	 * It can be detected by peeking the first packet in rsh
	 * protocol which will  be a port number string in ASCII
	 * terminated with '\0'.
	 */
	if( 0 < PollIn(0,100) ){
		int rcc,ci;
		CStr(buf,8);
		rcc = recvPeekTIMEOUT(0,AVStr(buf),7);
		if( 0 < rcc )
		if( buf[rcc-1] == '\0' )
		if( isdigits(buf) ){
			return 0;
		}
	}
}

	hosti = peerHostport(0,&porti);
	if( hosti == -1 || porti<0 || porti<512 || 1023<porti )
		return 0;
	hosto = peerHostport(1,&porto);
	if( hosto == -1 || porto<0 || porto<512 || 1023<porto )
		return 0;
	if( hosti != hosto )
		return 0;

	_fromRsh = 1;
	return 1;
}
Example #4
0
// Retrieve cell text
CStr CProfileNodeTable::GetCellText(size_t row, size_t col)
{
	CProfileNode* child;
	size_t nrchildren = node->GetChildren()->size();
	size_t nrscriptchildren = node->GetScriptChildren()->size();
	char buf[256] = "?";
	
	if (row < nrchildren)
		child = (*node->GetChildren())[row];
	else if (row < nrchildren + nrscriptchildren)
		child = (*node->GetScriptChildren())[row - nrchildren];
	else if (row > nrchildren + nrscriptchildren)
		return "!bad row!";
	else
	{
		// "unlogged" row
		if (col == 0)
			return "unlogged";
		else if (col == 1)
			return "";
		else if (col == 4)
			return "";
		
		double unlogged_time_frame = node->GetFrameTime();
		double unlogged_time_turn = node->GetTurnTime();
		double unlogged_mallocs_frame = node->GetFrameMallocs();
		double unlogged_mallocs_turn = node->GetTurnMallocs();
		CProfileNode::const_profile_iterator it;

		for (it = node->GetChildren()->begin(); it != node->GetChildren()->end(); ++it)
		{
			unlogged_time_frame -= (*it)->GetFrameTime();
			unlogged_time_turn -= (*it)->GetTurnTime();
			unlogged_mallocs_frame -= (*it)->GetFrameMallocs();
			unlogged_mallocs_turn -= (*it)->GetTurnMallocs();
		}
		for (it = node->GetScriptChildren()->begin(); it != node->GetScriptChildren()->end(); ++it)
		{
			unlogged_time_frame -= (*it)->GetFrameTime();
			unlogged_time_turn -= (*it)->GetTurnTime();
			unlogged_mallocs_frame -= (*it)->GetFrameMallocs();
			unlogged_mallocs_turn -= (*it)->GetTurnMallocs();
		}
		
		// The root node can't easily count per-turn values (since Turn isn't called until
		// halfway though a frame), so just reset them the zero to prevent weird displays
		if (!node->GetParent())
		{
			unlogged_time_turn = 0.0;
			unlogged_mallocs_turn = 0.0;
		}

		if (col == 2)
			sprintf_s(buf, ARRAY_SIZE(buf), "%.3f", unlogged_time_frame * 1000.0f);
		else if (col == 3)
			sprintf_s(buf, ARRAY_SIZE(buf), "%.1f", unlogged_mallocs_frame);
		else if (col == 5)
			sprintf_s(buf, ARRAY_SIZE(buf), "%.3f", unlogged_time_turn * 1000.f);
		else if (col == 6)
			sprintf_s(buf, ARRAY_SIZE(buf), "%.1f", unlogged_mallocs_turn);
		
		return CStr(buf);
	}
	
	switch(col)
	{
	default:
	case 0:
		return child->GetName();
		
	case 1:
		sprintf_s(buf, ARRAY_SIZE(buf), "%.1f", child->GetFrameCalls());
		break;
	case 2:
		sprintf_s(buf, ARRAY_SIZE(buf), "%.3f", child->GetFrameTime() * 1000.0f);
		break;
	case 3:
		sprintf_s(buf, ARRAY_SIZE(buf), "%.1f", child->GetFrameMallocs());
		break;
	case 4:
		sprintf_s(buf, ARRAY_SIZE(buf), "%.1f", child->GetTurnCalls());
		break;
	case 5:
		sprintf_s(buf, ARRAY_SIZE(buf), "%.3f", child->GetTurnTime() * 1000.0f);
		break;
	case 6:
		sprintf_s(buf, ARRAY_SIZE(buf), "%.1f", child->GetTurnMallocs());
		break;
	}
	return CStr(buf);
}
Example #5
0
/*
static int forkSftp(PCStr(host),int port,PCStr(user),PCStr(pass),int tf[2]){
*/
static int forkSftp(PCStr(host),int port,PCStr(user),PCStr(pass),int tf[2],PVStr(rresp)){
	CStr(com,1024);
	CStr(resp,0x10000);
	int pty;
	IStr(name,128);
	FILE *fs;
	FILE *ts;
	int to[2];
	int from[2];
	int rcode;
	int slog = LOG_type1;

	LOG_type1 &= ~L_CONSOLE; /* 9.9.8 suppress logging to pty by child */
	if( curLogFd() == fileno(stderr) ){
		dupLogFd(); /* 9.8.2 not to send log-output to pty */
	}
	if( lSFTP_FILTER() ){ /* 9.9.6 "-Esf" to apply SOCKS, SRCIF, ..*/
		IStr(lhost,MaxHostNameLen);
		int lport;
		lport = sftpsv(port,host,AVStr(lhost));
		port = lport;
		host = (const char*)lhost;
	}
	pid = Forkpty(&pty,(char*)name);
	if( 0 < pid ){
  int retrying = 0; /* fix-110921a for retrying auth. with sftp */
  IStr(prompt1,sizeof(resp));

		PollIn(pty,3*1000); /* wait a response from sftp */
		LOG_type1 = slog; /* LOG_type1 is on shared memory */

		SftpPid = pid;
		SftpPty = pty;
		DEBUG("--SFTP: pid=%d pty master %d %s\n",pid,pty,name);
		tf[0] = pty;
		tf[1] = pty;

		msleep(100);
		fs = fdopen(pty,"r");
		relay_resp(fs,-1,15*1000,AVStr(resp),"FORK-1",1);
		strcpy(prompt1,resp);

		if( strstr(resp,"Are you sure you want to continue") ){
			sprintf(com,"yes\n");
			IGNRETP write(pty,com,strlen(com));
			DEBUG("--SFTP: answered yes for...\n%s\n",resp);
			relay_resp(fs,-1,15*1000,AVStr(resp),"FORK-2",1);
		}

  for( retrying = 0; retrying < 10; retrying++ ){
		sprintf(com,"%s\r\n",pass);
		IGNRETP write(pty,com,strlen(com));
		DEBUG("--SFTP: sent the password...\n");
		relay_resp(fs,-1,15*1000,AVStr(resp),"FORK-3",1);

		if( strtailstr(resp,"Password:"******"Password: "******"password: "******"Enter passphrase for key")
		){
    if( retrying || strtailstr(prompt1,resp) != NULL ){ /* fix-110921a */
	DEBUG("--SFTP REPEAT %d %s\n",retrying,resp);
	clearVStr(resp);
	continue;
    }
			DEBUG("--SFTP %s\n",resp);
if( lGATEWAY() )
sv1log("####@@@@ KILL sftp pid=%d\n",pid);
			Kill(SftpPid,SIGTERM);
			strcpy(rresp,resp);
			return -1;
		}
    break;
  }

		sprintf(com,"progress\r\n");
		IGNRETP write(pty,com,strlen(com));
		relay_resp(fs,-1,5*1000,AVStr(resp),"FORK-4",1);

		return 0;
	}

	sprintf(com,"[%s]","sftp");
	Xsprintf(TVStr(com),sftp_com,port,user,host);
	DEBUG("--SFTP: %s\n",com);
if( lGATEWAY() )
sv1log("####@@@@ command %s\n",com);

	if( pid == 0 ){
		closeAll();
		Stty(0,"-echo");
		/*
		system("stty raw");
		*/
		/*
		rcode = system(com);
		printf("ssh exit(%d)\n",rcode);
		*/
		execsystem("sftp",com);
		printf("ssh exec(%s) failed\n",com);
		_exit(0);
	}

	IGNRETZ pipe(to);
	IGNRETZ pipe(from);
	if( Fork("Sftp") == 0 ){
		close(to[1]);
		dup2(to[0],0);
		close(from[0]);
		dup2(from[1],1);
		closeAll();
		rcode = system(com);
		printf("ssh exit(%d)\n",rcode);
		_exit(0);
	}
	close(to[0]);
	close(from[1]);
	tf[0] = from[0];
	tf[1] = to[1];
	fs = fdopen(from[0],"r");
	relay_resp(fs,-1,20*1000,AVStr(resp),"FORK-1",1);
	return 0;
}
Example #6
0
CMaterial CMaterialManager::LoadMaterial(const VfsPath& pathname)
{
	if (pathname.empty())
		return CMaterial();

	std::map<VfsPath, CMaterial>::iterator iter = m_Materials.find(pathname);
	if (iter != m_Materials.end())
		return iter->second;

	CXeromyces xeroFile;
	if (xeroFile.Load(g_VFS, pathname, "material") != PSRETURN_OK)
		return CMaterial();

	#define EL(x) int el_##x = xeroFile.GetElementID(#x)
	#define AT(x) int at_##x = xeroFile.GetAttributeID(#x)
	EL(alpha_blending);
	EL(alternative);
	EL(define);
	EL(shader);
	EL(uniform);
	EL(renderquery);
	EL(required_texture);
	EL(conditional_define);
	AT(effect);
	AT(if);
	AT(define);
	AT(quality);
	AT(material);
	AT(name);
	AT(value);
	AT(type);
	AT(min);
	AT(max);
	AT(conf);
	#undef AT
	#undef EL

	CMaterial material;

	XMBElement root = xeroFile.GetRoot();

	CPreprocessorWrapper preprocessor;
	preprocessor.AddDefine("CFG_FORCE_ALPHATEST", g_Renderer.m_Options.m_ForceAlphaTest ? "1" : "0");

	CVector4D vec(qualityLevel,0,0,0);
	material.AddStaticUniform("qualityLevel", vec);

	XERO_ITER_EL(root, node)
	{
		int token = node.GetNodeName();
		XMBAttributeList attrs = node.GetAttributes();
		if (token == el_alternative)
		{
			CStr cond = attrs.GetNamedItem(at_if);
			if (cond.empty() || !preprocessor.TestConditional(cond))
			{
				cond = attrs.GetNamedItem(at_quality);
				if (cond.empty())
					continue;
				else
				{
					if (cond.ToFloat() <= qualityLevel)
						continue;
				}
			}

			material = LoadMaterial(VfsPath("art/materials") / attrs.GetNamedItem(at_material).FromUTF8());
			break;
		}
		else if (token == el_alpha_blending)
		{
			material.SetUsesAlphaBlending(true);
		}
		else if (token == el_shader)
		{
			material.SetShaderEffect(attrs.GetNamedItem(at_effect));
		}
		else if (token == el_define)
		{
			material.AddShaderDefine(CStrIntern(attrs.GetNamedItem(at_name)), CStrIntern(attrs.GetNamedItem(at_value)));
		}
		else if (token == el_conditional_define)
		{
			std::vector<float> args;

			CStr type = attrs.GetNamedItem(at_type).c_str();
			int typeID = -1;

			if (type == CStr("draw_range"))
			{
				typeID = DCOND_DISTANCE;

				float valmin = -1.0f;
				float valmax = -1.0f;

				CStr conf = attrs.GetNamedItem(at_conf);
				if (!conf.empty())
				{
					CFG_GET_VAL("materialmgr." + conf + ".min", valmin);
					CFG_GET_VAL("materialmgr." + conf + ".max", valmax);
				}
				else
				{
					CStr dmin = attrs.GetNamedItem(at_min);
					if (!dmin.empty())
						valmin = attrs.GetNamedItem(at_min).ToFloat();

					CStr dmax = attrs.GetNamedItem(at_max);
					if (!dmax.empty())
						valmax = attrs.GetNamedItem(at_max).ToFloat();
				}

				args.push_back(valmin);
				args.push_back(valmax);

				if (valmin >= 0.0f)
				{
					std::stringstream sstr;
					sstr << valmin;
					material.AddShaderDefine(CStrIntern(conf + "_MIN"), CStrIntern(sstr.str()));
				}

				if (valmax >= 0.0f)
				{
					std::stringstream sstr;
					sstr << valmax;
					material.AddShaderDefine(CStrIntern(conf + "_MAX"), CStrIntern(sstr.str()));
				}
			}

			material.AddConditionalDefine(attrs.GetNamedItem(at_name).c_str(),
						      attrs.GetNamedItem(at_value).c_str(),
						      typeID, args);
		}
		else if (token == el_uniform)
		{
			std::stringstream str(attrs.GetNamedItem(at_value));
			CVector4D vec;
			str >> vec.X >> vec.Y >> vec.Z >> vec.W;
			material.AddStaticUniform(attrs.GetNamedItem(at_name).c_str(), vec);
		}
// --[  Method  ]---------------------------------------------------------------
//
//  - Class     : CStravaganzaMaxTools
//
//  - prototype : bool BuildShaders()
//
//  - Purpose   : Builds the shader list from MAX's materials.
//                Preview mode requires texture files to be stored with full
//                path in order to load them. When we export, we only store the
//                filename. Another thing is that in the export mode, we copy
//                all textures into the path specified by the user if that
//                option is checked.
//
// -----------------------------------------------------------------------------
bool CStravaganzaMaxTools::BuildShaders()
{
	std::vector<Mtl*>::iterator it;

	assert(m_vecShaders.empty());

	if(!m_bPreview && m_bCopyTextures && m_strTexturePath == "")
	{
		CLogger::NotifyWindow("Textures won't be copied\nSpecify a valid output texture path first");
	}

	LOG.Write("\n\n-Building shaders: ");

	for(it = m_vecMaterials.begin(); it != m_vecMaterials.end(); ++it)
	{
		Mtl* pMaxMaterial = *it;
		assert(pMaxMaterial);

		LOG.Write("\n    %s", pMaxMaterial->GetName().data());
		CShaderStandard* pShaderStd = new CShaderStandard;
		pShaderStd->SetName(pMaxMaterial->GetName().data());

		// Properties

		StdMat2 *pMaxStandardMtl = NULL;
		StdMat2 *pMaxBakedMtl    = NULL;

		float fAlpha;

		if(pMaxMaterial->ClassID() == Class_ID(DMTL_CLASS_ID, 0))
		{
			pMaxStandardMtl = (StdMat2 *)pMaxMaterial;
		}
		else if(pMaxMaterial->ClassID() == Class_ID(BAKE_SHELL_CLASS_ID, 0))
		{
			pMaxStandardMtl = (StdMat2 *)pMaxMaterial->GetSubMtl(0);
			pMaxBakedMtl    = (StdMat2 *)pMaxMaterial->GetSubMtl(1);
		}

		if(pMaxStandardMtl)
		{
			// Standard material

			fAlpha = pMaxStandardMtl->GetOpacity(0);

			Shader* pMaxShader = pMaxStandardMtl->GetShader();

			CVector4 v4Specular = ColorToVector4(pMaxStandardMtl->GetSpecular(0), 0.0f) * pMaxShader->GetSpecularLevel(0, 0);

			pShaderStd->SetAmbient  (ColorToVector4(pMaxStandardMtl->GetAmbient(0),  0.0f));
			pShaderStd->SetDiffuse  (ColorToVector4(pMaxStandardMtl->GetDiffuse(0),  fAlpha));
			pShaderStd->SetSpecular (v4Specular);
			pShaderStd->SetShininess(pMaxShader->GetGlossiness(0, 0) * 128.0f);

			if(pMaxStandardMtl->GetTwoSided() == TRUE)
			{
				pShaderStd->SetTwoSided(true);
			}

			// Need to cast to StdMat2 in order to get access to IsFaceted().
			// ¿Is StdMat2 always the interface for standard materials?
			if(((StdMat2*)pMaxStandardMtl)->IsFaceted())
			{
				pShaderStd->SetFaceted(true);
			}

			if(pMaxStandardMtl->GetWire() == TRUE)
			{
				pShaderStd->SetPostWire(true);
				pShaderStd->SetWireLineThickness(pMaxStandardMtl->GetWireSize(0));
			}
		}
		else
		{
			// Material != Standard

			fAlpha = 1.0f; // pMaxMaterial->GetXParency();

			pShaderStd->SetAmbient  (ColorToVector4(pMaxMaterial->GetAmbient(),  0.0f));
			pShaderStd->SetDiffuse  (ColorToVector4(pMaxMaterial->GetDiffuse(),  fAlpha));
			pShaderStd->SetSpecular (CVector4(0.0f, 0.0f, 0.0f, 0.0f));
			pShaderStd->SetShininess(0.0f);
		}

		// Layers

		if(!pMaxStandardMtl)
		{
			m_vecShaders.push_back(pShaderStd);
			continue;
		}

		bool bDiffuseMap32Bits = false;
		StdMat2 *pStandardMtl;

		for(int i = 0; i < 3; i++)
		{
			int nMap;

			pStandardMtl = pMaxStandardMtl;

			// 0 = diffuse, 1 == bump, 2 = lightmap (self illumination slot) or envmap (reflection slot)

			if(i == 0)
			{
				nMap = ID_DI;
			}
			else if(i == 1)
			{
				nMap = ID_BU;

				// If its a baked material, get the bump map from there

				if(pMaxBakedMtl)
				{
					pStandardMtl = pMaxBakedMtl;
				}
			}
			else if(i == 2)
			{
				bool bBaked = false;

				// If its a baked material, get the map2 (lightmap) from there

				if(pMaxBakedMtl)
				{
					if(pMaxBakedMtl->GetMapState(ID_SI) == MAXMAPSTATE_ENABLED)
					{
						bBaked       = true;
						nMap         = ID_SI;
						pStandardMtl = pMaxBakedMtl;
					}
				}

				if(!bBaked)
				{
					if(pStandardMtl->GetMapState(ID_SI) == MAXMAPSTATE_ENABLED)
					{
						nMap = ID_SI;
					}
					else
					{
						nMap = ID_RL;
					}
				}
			}

			// Check validity

			if(pStandardMtl->GetMapState(nMap) != MAXMAPSTATE_ENABLED)
			{
				if(i == 0)
				{
					LOG.Write("\n        No diffuse. Skipping.");
					break;
				}

				continue;
			}

			Texmap* pMaxTexmap = pStandardMtl->GetSubTexmap(nMap);

			if(!pMaxTexmap)
			{
				if(i == 0)
				{
					LOG.Write("\n        No diffuse. Skipping.");
					break;
				}

				continue;
			}

			// Get texmaps

			std::vector<std::string> vecTextures, vecPaths;

			CShaderStandard::SLayerInfo  layerInfo;
			CShaderStandard::SBitmapInfo bitmapInfo;

			if(pMaxTexmap->ClassID() == Class_ID(BMTEX_CLASS_ID, 0))
			{
				BitmapTex* pMaxBitmapTex = (BitmapTex*)pMaxTexmap;
				Bitmap*    pMaxBitmap    = pMaxBitmapTex->GetBitmap(SECONDS_TO_TICKS(m_fStartTime));
				StdUVGen*  pMaxUVGen     = pMaxBitmapTex->GetUVGen();

				if(!pMaxBitmap)
				{
					if(i == 0)
					{
						LOG.Write("\n        Invalid diffuse. Skipping.");
						break;
					}
					continue;
				}

				assert(pMaxUVGen);

				BitmapInfo bi = pMaxBitmap->Storage()->bi;

				// bi.Name() returns the full path
				// bi.Filename() returns just the filename

				vecTextures.push_back(bi.Filename());
				vecPaths.   push_back(bi.Name());

				LOG.Write("\n        Bitmap %s", vecTextures[0].data());

				// Check if diffuse texture has alpha channel

				if(i == 0)
				{
					CBitmap    bitmap;
					CInputFile bitmapFile;

					if(!bitmapFile.Open(bi.Name(), false))
					{
						CLogger::NotifyWindow("WARNING - CStravaganzaMaxTools::BuildShaders():\nUnable to load file %s", bi.Name());
					}
					else
					{
						if(!bitmap.Load(&bitmapFile, GetFileExt(bi.Name())))
						{
							CLogger::NotifyWindow("WARNING - CStravaganzaMaxTools::BuildShaders():\nUnable to load bitmap %s", bi.Name());
						}
						else
						{
							if(bitmap.GetBpp() == 32)
							{
								bDiffuseMap32Bits = true;
								LOG.Write(" (with alpha channel)");
							}
							bitmap.Free();
						}
						bitmapFile.Close();
					}
				}

				// Ok, copy properties

				layerInfo.texInfo.bLoop        = false;
				layerInfo.texInfo.eTextureType = UtilGL::Texturing::CTexture::TEXTURE2D;

				bitmapInfo.strFile         = m_bPreview ? bi.Name() : bi.Filename();
				bitmapInfo.bTile           = ((pMaxUVGen->GetTextureTiling() & (U_WRAP | V_WRAP)) == (U_WRAP | V_WRAP)) ? true : false;
				bitmapInfo.fSeconds        = 0.0f;
				bitmapInfo.bForceFiltering = false;
				bitmapInfo.eFilter         = UtilGL::Texturing::FILTER_TRILINEAR; // won't be used (forcefiltering = false)
				
				layerInfo.texInfo.m_vecBitmaps.push_back(bitmapInfo);

				layerInfo.eTexEnv          = nMap == ID_RL ? CShaderStandard::TEXENV_ADD : CShaderStandard::TEXENV_MODULATE;
				layerInfo.eUVGen           = pMaxUVGen->GetCoordMapping(0) == UVMAP_SPHERE_ENV ? CShaderStandard::UVGEN_ENVMAPPING : CShaderStandard::UVGEN_EXPLICITMAPPING;
				layerInfo.uMapChannel      = pMaxUVGen->GetMapChannel();
				layerInfo.v3ScrollSpeed    = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3RotationSpeed  = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3ScrollOffset   = CVector3(pMaxUVGen->GetUOffs(0), pMaxUVGen->GetVOffs(0), 0.0f);
				layerInfo.v3RotationOffset = CVector3(pMaxUVGen->GetUAng(0),  pMaxUVGen->GetVAng(0),  pMaxUVGen->GetWAng(0));
			}
			else if(pMaxTexmap->ClassID() == Class_ID(ACUBIC_CLASS_ID, 0))
			{
				ACubic*       pMaxCubic  = (ACubic*)pMaxTexmap;
				IParamBlock2* pBlock     = pMaxCubic->pblock;
				Interval      validRange = m_pMaxInterface->GetAnimRange();

				for(int nFace = 0; nFace < 6; nFace++)
				{
					int nMaxFace;

					switch(nFace)
					{
					case 0: nMaxFace = 3; break;
					case 1: nMaxFace = 2; break;
					case 2: nMaxFace = 1; break;
					case 3: nMaxFace = 0; break;
					case 4: nMaxFace = 5; break;
					case 5: nMaxFace = 4; break;
					}

					TCHAR *name;
					pBlock->GetValue(acubic_bitmap_names, TICKS_TO_SECONDS(m_fStartTime), name, validRange, nMaxFace);

					vecPaths.push_back(name);

					CStr path, file, ext;
					SplitFilename(CStr(name), &path, &file, &ext);

					std::string strFile = std::string(file.data()) + ext.data();

					vecTextures.push_back(strFile);

					bitmapInfo.strFile         = m_bPreview ? name : strFile;
					bitmapInfo.bTile           = false;
					bitmapInfo.fSeconds        = 0.0f;
					bitmapInfo.bForceFiltering = false;
					bitmapInfo.eFilter         = UtilGL::Texturing::FILTER_TRILINEAR;
					
					layerInfo.texInfo.m_vecBitmaps.push_back(bitmapInfo);
				}

				layerInfo.texInfo.bLoop        = false;
				layerInfo.texInfo.eTextureType = UtilGL::Texturing::CTexture::TEXTURECUBEMAP;

				layerInfo.eTexEnv          = nMap == ID_RL ? CShaderStandard::TEXENV_ADD : CShaderStandard::TEXENV_MODULATE;
				layerInfo.eUVGen           = CShaderStandard::UVGEN_ENVMAPPING;
				layerInfo.uMapChannel      = 0;
				layerInfo.v3ScrollSpeed    = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3RotationSpeed  = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3ScrollOffset   = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3RotationOffset = CVector3(0.0f, 0.0f, 0.0f);
			}
			else
			{
				if(i == 0)
				{
					LOG.Write("\n        No diffuse. Skipping.");
					break;
				}
				continue;
			}

			if(!m_bPreview && m_bCopyTextures && m_strTexturePath != "")
			{
				for(int nTex = 0; nTex != vecTextures.size(); nTex++)
				{
					// Copy textures into the specified folder

					std::string strDestPath = m_strTexturePath;

					if(strDestPath[strDestPath.length() - 1] != '\\')
					{
						strDestPath.append("\\", 1);
					}

					strDestPath.append(vecTextures[nTex]);

					if(!CopyFile(vecPaths[nTex].data(), strDestPath.data(), FALSE))
					{
						CLogger::NotifyWindow("Unable to copy %s to\n%s", vecPaths[i], strDestPath.data());
					}
				}
			}

			if(layerInfo.eUVGen == CShaderStandard::UVGEN_ENVMAPPING && i == 1)
			{
				CLogger::NotifyWindow("%s : Bump with spheremapping not supported", pShaderStd->GetName().data());
			}
			else
			{
				// Add layer

				switch(i)
				{
				case 0: pShaderStd->SetLayer(CShaderStandard::LAYER_DIFF, layerInfo); break;
				case 1: pShaderStd->SetLayer(CShaderStandard::LAYER_BUMP, layerInfo); break;
				case 2: pShaderStd->SetLayer(CShaderStandard::LAYER_MAP2, layerInfo); break;
				}
			}
		}

		// ¿Do we need blending?

		if(ARE_EQUAL(fAlpha, 1.0f) && !bDiffuseMap32Bits)
		{
			pShaderStd->SetBlendSrcFactor(UtilGL::States::BLEND_ONE);
			pShaderStd->SetBlendDstFactor(UtilGL::States::BLEND_ZERO);
		}
		else
		{
			pShaderStd->SetBlendSrcFactor(UtilGL::States::BLEND_SRCALPHA);
			pShaderStd->SetBlendDstFactor(UtilGL::States::BLEND_INVSRCALPHA);
		}

		// Add shader

		m_vecShaders.push_back(pShaderStd);
	}

	return true;
}
Example #8
0
//---------------------------------------------------------------------
//
//   dump    Output the compiled form of the pattern.
//           Debugging function only.
//
//---------------------------------------------------------------------
void   RegexPattern::dumpOp(int32_t index) const {
    (void)index;  // Suppress warnings in non-debug build.
#if defined(REGEX_DEBUG)
    static const char * const opNames[] = {URX_OPCODE_NAMES};
    int32_t op          = fCompiledPat->elementAti(index);
    int32_t val         = URX_VAL(op);
    int32_t type        = URX_TYPE(op);
    int32_t pinnedType  = type;
    if ((uint32_t)pinnedType >= UPRV_LENGTHOF(opNames)) {
        pinnedType = 0;
    }

    printf("%4d   %08x    %-15s  ", index, op, opNames[pinnedType]);
    switch (type) {
    case URX_NOP:
    case URX_DOTANY:
    case URX_DOTANY_ALL:
    case URX_FAIL:
    case URX_CARET:
    case URX_DOLLAR:
    case URX_BACKSLASH_G:
    case URX_BACKSLASH_X:
    case URX_END:
    case URX_DOLLAR_M:
    case URX_CARET_M:
        // Types with no operand field of interest.
        break;

    case URX_RESERVED_OP:
    case URX_START_CAPTURE:
    case URX_END_CAPTURE:
    case URX_STATE_SAVE:
    case URX_JMP:
    case URX_JMP_SAV:
    case URX_JMP_SAV_X:
    case URX_BACKSLASH_B:
    case URX_BACKSLASH_BU:
    case URX_BACKSLASH_D:
    case URX_BACKSLASH_Z:
    case URX_STRING_LEN:
    case URX_CTR_INIT:
    case URX_CTR_INIT_NG:
    case URX_CTR_LOOP:
    case URX_CTR_LOOP_NG:
    case URX_RELOC_OPRND:
    case URX_STO_SP:
    case URX_LD_SP:
    case URX_BACKREF:
    case URX_STO_INP_LOC:
    case URX_JMPX:
    case URX_LA_START:
    case URX_LA_END:
    case URX_BACKREF_I:
    case URX_LB_START:
    case URX_LB_CONT:
    case URX_LB_END:
    case URX_LBN_CONT:
    case URX_LBN_END:
    case URX_LOOP_C:
    case URX_LOOP_DOT_I:
    case URX_BACKSLASH_H:
    case URX_BACKSLASH_R:
    case URX_BACKSLASH_V:
        // types with an integer operand field.
        printf("%d", val);
        break;

    case URX_ONECHAR:
    case URX_ONECHAR_I:
        if (val < 0x20) {
            printf("%#x", val);
        } else {
            printf("'%s'", CStr(UnicodeString(val))());
        }
        break;

    case URX_STRING:
    case URX_STRING_I:
        {
            int32_t lengthOp       = fCompiledPat->elementAti(index+1);
            U_ASSERT(URX_TYPE(lengthOp) == URX_STRING_LEN);
            int32_t length = URX_VAL(lengthOp);
            UnicodeString str(fLiteralText, val, length);
            printf("%s", CStr(str)());
        }
        break;

    case URX_SETREF:
    case URX_LOOP_SR_I:
        {
            UnicodeString s;
            UnicodeSet *set = (UnicodeSet *)fSets->elementAt(val);
            set->toPattern(s, TRUE);
            printf("%s", CStr(s)());
        }
        break;

    case URX_STATIC_SETREF:
    case URX_STAT_SETREF_N:
        {
            UnicodeString s;
            if (val & URX_NEG_SET) {
                printf("NOT ");
                val &= ~URX_NEG_SET;
            }
            UnicodeSet *set = fStaticSets[val];
            set->toPattern(s, TRUE);
            printf("%s", CStr(s)());
        }
        break;


    default:
        printf("??????");
        break;
    }
    printf("\n");
#endif
}
Example #9
0
/*
 * name can be defined
 */
int Vstat(PCStr(file),PVStr(path),PVStr(name),int isDGV,int lev,FileStat *st){
	refQStr(dp,path);
	refQStr(ep,name);
	FILE *fp;
	CStr(line,4096);
	CStr(facts,4096);
	CStr(fact1,128);
	const char *fcp;
	int rcc;
	int isdgv;

	if( 8 < lev ){
		return -1;
	}
	if( isDGV ){
		dp = 0;
	}else{
		dp = strrchr(path,'.');
		if( dp == 0 || !strcaseeq(dp,VNODE_EXT) )
			return -2;
	}
	if( (fp = fopen(path,"r+")) == 0 ){
		return -3;
	}
	truncVStr(facts);
	while( fgets(line,sizeof(line),fp) != NULL ){
		if( strncaseeq(line,"MLST-Facts:",11) ){
			lineScan(line+11,facts);
			break;
		}
		if( *line == ' ' && strcasestr(line,"Type=") ){
			lineScan(line+1,facts);
			break;
		}
	}

	if( lev == 0 ){
		FileStat vst;

		if( dp ){
			setVStrEnd(dp,0);
		}
		strcpy(name,file);
		if( ep = strrchr(name,'.') )
			setVStrEnd(ep,0);
		bzero(st,sizeof(FileStat));
		st->st_mode |= S_IFDIR;
		st->st_nlink = 1;
		if( stat(path,&vst) == 0 ){
			st->st_dev = vst.st_dev;
			st->st_ino = vst.st_ino;
		}
	}

	isdgv = 0;
	for( fcp = facts; *fcp; ){
		refQStr(f1,fact1);
		fcp = scan_ListElem1(fcp,';',AVStr(fact1));
		if( f1 = strpbrk(fact1,"\r\n") )
			setVStrEnd(f1,0);
		if( *fact1 == ' ' ){
			break;
		}else
		if( strncaseeq(fact1,"x-ref=",6) ){
			CStr(xpath,1024);
			refQStr(xp,xpath);
			strcpy(xpath,path);
			if( xp = strrpbrk(xpath,"/\\") ){
				truncVStr(xp);
			}
			chdir_cwd(AVStr(xpath),fact1+6,0);
			if( File_is(xpath) ){
				if( isdgv ){
fprintf(stderr,"--->>>> dgv ... %s\n",xpath);
				Vstat(file,AVStr(xpath),BVStr(name),1,lev+1,st);
				}else
				stat(xpath,st);
			}else{
				strcat(xpath,VNODE_EXT);
				Vstat(file,AVStr(xpath),BVStr(name),1,lev+1,st);
			}
		}else
		if( strncaseeq(fact1,"type=",5) ){
			if( strcaseeq(fact1+5,"file") )
				st->st_mode |= S_IFREG;
			else
			if( strcaseeq(fact1+5,"dir") )
				st->st_mode |= S_IFDIR;
			else
			if( strcaseeq(fact1+5,"vno") )
				isdgv = 1;
			else
			if( strcaseeq(fact1+5,"MLST") )
				isdgv = 2;
		}else
		if( strncaseeq(fact1,"perm=",5) ){
			st->st_mode |= permMode(fact1+5);
		}else
		if( strncaseeq(fact1,"size=",5) ){
			st->st_size = atoi(fact1+5);
		}else
		if( strncaseeq(fact1,"modify=",7) ){
			st->st_mtime = scanYmdHMS_GMT(fact1+7);
		}
	}
	fclose(fp);
	return 0;
}
Example #10
0
// Look up each key binding in the config file and set the mappings for
// all key combinations that trigger it.
static void LoadConfigBindings()
{
	std::vector<std::pair<CStr, CConfigValueSet> > bindings = g_ConfigDB.GetValuesWithPrefix( CFG_USER, CStr( "hotkey." ));

	CParser multikeyParser;
	multikeyParser.InputTaskType( "multikey", "<[~$arg(_negate)]$value_+_>_[~$arg(_negate)]$value" );

	for( std::vector<std::pair<CStr, CConfigValueSet> >::iterator bindingsIt = bindings.begin(); bindingsIt != bindings.end(); ++bindingsIt )
	{
		std::string hotkeyName = bindingsIt->first.substr(7); // strip the "hotkey." prefix

		for( CConfigValueSet::iterator it = bindingsIt->second.begin(); it != bindingsIt->second.end(); ++it )
		{
			std::string hotkey;
			if( it->GetString( hotkey ) )
			{
				std::vector<SKey> keyCombination;

				CParserLine multikeyIdentifier;
				multikeyIdentifier.ParseString( multikeyParser, hotkey );

				// Iterate through multiple-key bindings (e.g. Ctrl+I)

				bool negateNext = false;

				for( size_t t = 0; t < multikeyIdentifier.GetArgCount(); t++ )
				{

					if( multikeyIdentifier.GetArgString( (int)t, hotkey ) )
					{
						if( hotkey == "_negate" )
						{
							negateNext = true;
							continue;
						}

						// Attempt decode as key name
						int mapping = FindKeyCode( hotkey );

						// Attempt to decode as a negation of a keyname
						// Yes, it's going a bit far, perhaps.
						// Too powerful for most uses, probably.
						// However, it got some hardcoding out of the engine.
						// Thus it makes me happy.

						if( !mapping )
						{
							LOGWARNING(L"Hotkey mapping used invalid key '%hs'", hotkey.c_str() );
							continue;
						}

						SKey key = { (SDLKey)mapping, negateNext };
						keyCombination.push_back(key);

						negateNext = false;

					}
				}

				std::vector<SKey>::iterator itKey, itKey2;

				for( itKey = keyCombination.begin(); itKey != keyCombination.end(); itKey++ )
				{
					SHotkeyMapping bindCode;

					bindCode.name = hotkeyName;
					bindCode.negated = itKey->negated;

					for( itKey2 = keyCombination.begin(); itKey2 != keyCombination.end(); itKey2++ )
					{
						// Push any auxiliary keys.
						if( itKey != itKey2 )
							bindCode.requires.push_back( *itKey2 );
					}

					g_HotkeyMap[itKey->code].push_back( bindCode );
				}
			}
		}
	}
}
Example #11
0
int VtModelParser::LoadCooked(
	const xtime::TimeSlice &time,
	Engine &engine,
	const pkg::Asset::Ref &asset,
	int flags
) {
	if (m_state == kS_None) {
#if defined(RAD_OPT_TOOLS)
		if (!asset->cooked) {
			const String *s = asset->entry->KeyValue<String>("AnimStates.Source", P_TARGET_FLAGS(flags));
			if (!s)
				return SR_MetaError;

			m_statesRef = engine.sys->packages->Resolve(s->c_str, asset->zone);
			if (!m_statesRef)
				return SR_FileNotFound;

			int r = m_statesRef->Process(
				xtime::TimeSlice::Infinite,
				flags
			);

			if (r != SR_Success)
				return r;

			m_states = SkAnimStatesParser::Cast(m_statesRef);
			if (!m_states || !m_states->valid)
				return SR_ParseError;
		} else {
#endif
		const Package::Entry::Import *import = asset->entry->Resolve(0);
		if (!import)
			return SR_MetaError;

		m_statesRef = asset->entry->Resolve(*import, asset->zone);
		if (!m_statesRef)
			return SR_FileNotFound;

		int r = m_statesRef->Process(
			xtime::TimeSlice::Infinite,
			flags
		);

		if (r != SR_Success)
			return r;

		m_states = SkAnimStatesParser::Cast(m_statesRef);
		if (!m_states || !m_states->valid)
			return SR_ParseError;
#if defined(RAD_OPT_TOOLS)
		}
#endif

		m_state = kS_Load0;
	}

	if (m_state == kS_Load0) {
		if (!m_mm[0]) {
#if defined(RAD_OPT_TOOLS)
			if (!asset->cooked) {
				m_cooker = asset->AllocateIntermediateCooker();
				CookStatus status = m_cooker->Status(P_TARGET_FLAGS(flags));

				if (status == CS_Ignore)
					return SR_CompilerError;

				if (status == CS_NeedRebuild) {
					COut(C_Info) << asset->path.get() << " is out of date, rebuilding..." << std::endl;
					int r = m_cooker->Cook(P_TARGET_FLAGS(flags));
					if (r != SR_Success)
						return r;
				} else {
					COut(C_Info) << asset->path.get() << " is up to date, using cache." << std::endl;
				}

				String path(CStr(asset->path));
				path += ".0.bin";

				m_mm[0] = m_cooker->MapFile(path.c_str, r::ZSkm);
				if (!m_mm[0])
					return SR_FileNotFound;
			}
			else {
#endif
			String path(CStr("Cooked/"));
			path += CStr(asset->path);
			path += ".0.bin";

			m_mm[0] = engine.sys->files->MapFile(path.c_str, r::ZSkm);
			if (!m_mm[0])
				return SR_FileNotFound;
#if defined(RAD_OPT_TOOLS)
			}
#endif
		}

		m_state = kS_Load1;
	}

	if (m_state == kS_Load1) {
		if (!m_mm[1]) {
#if defined(RAD_OPT_TOOLS)
			if (!asset->cooked)
			{
				String path(CStr(asset->path));
				path += ".1.bin";

				m_mm[1] = m_cooker->MapFile(path.c_str, r::ZSkm);
				m_cooker.reset();

				if (!m_mm[1])
					return SR_FileNotFound;
			}
			else {
#endif
			String path(CStr("Cooked/"));
			path += asset->path.get();
			path += ".1.bin";

			m_mm[1] = engine.sys->files->MapFile(path.c_str, r::ZSkm);
			if (!m_mm[1])
				return SR_FileNotFound;
#if defined(RAD_OPT_TOOLS)
			}
#endif
		}

		const void *data[2];
		AddrSize size[2];

		data[0] = m_mm[0]->data;
		data[1] = m_mm[1]->data;
		size[0] = m_mm[0]->size;
		size[1] = m_mm[1]->size;

		int r = m_dvtm.Parse(data, size);
		if (r < SR_Success)
			return r;

		m_state = kS_Done;
	}

	return SR_Success;
}
Example #12
0
bool GLSLTool::Assemble(
	Engine &engine,
	const r::Material &material,
	const Shader::Ref &shader,
	const r::MaterialInputMappings &mapping,
	const Shader::TexCoordMapping &tcMapping,
	r::Shader::Pass pass,
	AssembleFlags flags,
	std::ostream &out
) {
	std::stringstream ss;

	const bool GLES = (flags & kAssemble_GLES) ? true : false;

	if (!(flags&(kAssemble_VertexShader|kAssemble_PixelShader)))
		flags |= kAssemble_VertexShader;

	bool vertexShader = (flags & kAssemble_VertexShader) ? true : false;

	if (!GLES)
		ss << "#version 120\r\n";

	if (vertexShader) {
		ss << "#define VERTEX\r\n";
	} else {
		ss << "#define FRAGMENT\r\n";
		ss << "#define MATERIAL\r\n";
	}

	switch (shader->precisionMode) {
	case Shader::kPrecision_Low:
		ss << "#define PFLOAT FIXED\r\n";
		ss << "#define PFLOAT2 FIXED2\r\n";
		ss << "#define PFLOAT3 FIXED3\r\n";
		ss << "#define PFLOAT4 FIXED4\r\n";
		ss << "#define PFLOAT4X4 FIXED4X4\r\n";
		break;
	case Shader::kPrecision_Medium:
		ss << "#define PFLOAT HALF\r\n";
		ss << "#define PFLOAT2 HALF2\r\n";
		ss << "#define PFLOAT3 HALF3\r\n";
		ss << "#define PFLOAT4 HALF4\r\n";
		ss << "#define PFLOAT4X4 HALF4X4\r\n";
		break;
	case Shader::kPrecision_High:
		ss << "#define PFLOAT FLOAT\r\n";
		ss << "#define PFLOAT2 FLOAT2\r\n";
		ss << "#define PFLOAT3 FLOAT3\r\n";
		ss << "#define PFLOAT4 FLOAT4\r\n";
		ss << "#define PFLOAT4X4 FLOAT4X4\r\n";
		break;
	}

	if (pass != r::Shader::kPass_Preview) {
		if (material.skinMode == r::Material::kSkinMode_Sprite)
			ss << "#define SKIN_SPRITE\r\n";
		if (material.skinMode == r::Material::kSkinMode_Billboard)
			ss << "#define SKIN_BILLBOARD\r\n";
	}

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Color) > 0)
		ss << "#define SHADER_COLOR\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_VertexColor) > 0)
		ss << "#define SHADER_VERTEX_COLOR\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Vertex) > 0)
		ss << "#define SHADER_POSITION\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_MV) > 0)
		ss << "#define SHADER_MV\r\n";
	
	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_PRJ) > 0)
		ss << "#define SHADER_PRJ\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_MVP) > 0)
		ss << "#define SHADER_MVP\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_InverseMV) > 0)
		ss << "#define SHADER_INVERSE_MV\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_InverseMVP) > 0)
		ss << "#define SHADER_INVERSE_MVP\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_InversePRJ) > 0)
		ss << "#define SHADER_INVERSE_PRJ\r\n";

	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_PFXVars) > 0)
		ss << "#define PFX_VARS\r\n";
		
	if (shader->MaterialSourceUsage(pass, Shader::kMaterialSource_EyeVertex) > 0)
		ss << "#define SHADER_EYE_VERTEX\r\n";

	int numTextures = 0;
	for (int i = 0; i < r::kMaxTextures; ++i) {
		if (mapping.textures[i][0] == r::kInvalidMapping)
			break; // no more texture bindings
		switch (mapping.textures[i][0]) {
		case r::kMaterialTextureSource_Texture:
			ss << "#define T" << i << "TYPE sampler2D" << "\r\n";
			break;
		default:
			break;
		}
		switch(shader->SamplerPrecisionMode(i)) {
		case Shader::kPrecision_Low:
			ss << "#define T" << i << "PRECISION lowp" << "\r\n";
			break;
		case Shader::kPrecision_Medium:
			ss << "#define T" << i << "PRECISION mediump" << "\r\n";
			break;
		case Shader::kPrecision_High:
			ss << "#define T" << i << "PRECISION highp" << "\r\n";
			break;
		}
		++numTextures;
	}

	if (numTextures > 0)
		ss << "#define TEXTURES " << numTextures << "\r\n";
	
	const Shader::IntSet &tcUsage = shader->AttributeUsage(pass, Shader::kMaterialSource_TexCoord);
	int numTexCoords = (int)tcUsage.size();
	if (numTexCoords > 0) {
		// Shaders files can read from r::kMaxTexture unique texture coordinate slots.
		// The set of read texcoord registers may be sparse. Additionally the engine only supports
		// 2 UV channels in most model data. We do some work here to map the set of read texcoord
		// registers onto the smallest possible set:
		//
		// A tcMod may take an input UV channel and modify it, meaning that texture channel is unique,
		// however there are a lot of cases where the tcMod is identity and therefore a texture coordinate
		// register in a shader can be mapped to a commmon register.

		int numTCMods = 0;
		for (int i = 0; i < r::kMaterialTextureSource_MaxIndices; ++i) {
			if (mapping.tcMods[i] == r::kInvalidMapping)
				break;
			++numTCMods;
		}
		
		// numTCMods is the number of unique texture coordinates read by the pixel shader.
		// (which have to be generated by the vertex shader).

		ss << "#define TEXCOORDS " << numTCMods << "\r\n";

		RAD_VERIFY(tcUsage.size() == tcMapping.size());

		if (vertexShader) {
			Shader::IntSet tcInputs;
			
			bool genReflect = false;
			bool genProject = false;

			for (int i = 0; i < r::kMaterialTextureSource_MaxIndices; ++i) {
				if (mapping.tcMods[i] == r::kInvalidMapping)
					break;
				int tcIndex = (int)mapping.tcMods[i];
				tcInputs.insert(material.TCUVIndex(tcIndex));

				int tcMod = material.TCModFlags(tcIndex);
				if (tcMod & r::Material::kTCModFlag_Rotate)
					ss << "#define TEXCOORD" << i << "_ROTATE\r\n";
				if (tcMod & r::Material::kTCModFlag_Scale)
					ss << "#define TEXCOORD" << i << "_SCALE\r\n";
				if (tcMod & r::Material::kTCModFlag_Shift)
					ss << "#define TEXCOORD" << i << "_SHIFT\r\n";
				if (tcMod & r::Material::kTCModFlag_Scroll)
					ss << "#define TEXCOORD" << i << "_SCROLL\r\n";
				if (tcMod & r::Material::kTCModFlag_Turb)
					ss << "#define TEXCOORD" << i << "_TURB\r\n";

				int tcGen = material.TCGen(tcIndex);
				if (tcGen == r::Material::kTCGen_EnvMap) {
					if (!genReflect) {
						genReflect = true;
						ss << "#define GENREFLECT\r\n";
					}
					ss << "#define TEXCOORD" << i << "_GENREFLECT\r\n";
				} else if (tcGen == r::Material::kTCGen_Projected) {
					if (!genProject) {
						genProject = true;
						ss << "#define GENPROJECT\r\n";
					}
					ss << "#define TEXCOORD" << i << "_GENPROJECT\r\n";
				}
			}

			ss << "#define TCINPUTS " << tcInputs.size() << "\r\n";

			for (int i = 0; i < r::kMaterialTextureSource_MaxIndices; ++i) {
				if (mapping.tcMods[i] == r::kInvalidMapping)
					break;
				int tcIndex = (int)mapping.tcMods[i];
				int uvIndex = material.TCUVIndex(tcIndex);

				int ofs = 0;
				for (Shader::IntSet::const_iterator it2 = tcInputs.begin(); it2 != tcInputs.end(); ++it2) {
					if (uvIndex == *it2)
						break;
					++ofs;
				}

				RAD_VERIFY(ofs < (int)tcInputs.size());
				ss << "#define TEXCOORD" << i << " tc" << ofs << "\r\n";
			}
		} else {
			// fragment shader inputs used generated tc's, which may have expanded from the
			// the vertex shader inputs.
			int ofs = 0;
			for (Shader::IntSet::const_iterator it = tcUsage.begin(); it != tcUsage.end(); ++it, ++ofs) {
				ss << "#define TEXCOORD" << ofs << " tc" << tcMapping[ofs].first << "\r\n";
			}
		}
	}
	
	int numColors = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Color);

	if (numColors > 0)
		ss << "#define COLORS " << numColors << "\r\n";

	int numSpecularColors = std::max(
		shader->MaterialSourceUsage(pass, Shader::kMaterialSource_SpecularColor),
		shader->MaterialSourceUsage(pass, Shader::kMaterialSource_SpecularExponent)
	);
	if (numSpecularColors > 0)
		ss << "#define SHADER_SPECULAR_COLORS " << numSpecularColors << "\r\n";

	int numLightPos = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightPos);
	int numLightVec = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightVec);
	int numLightHalfVec = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightHalfVec);
	int numLightVertex = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightVertex);
	int numLightTanVec = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightTanVec);
	int numLightTanHalfVec = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightTanHalfVec);
	int numLightDiffuseColor = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightDiffuseColor);
	int numLightSpecularColor = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_LightSpecularColor);

	int numShaderNormals = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Normal);
	int numShaderTangents = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Tangent);
	int numShaderBitangents = shader->MaterialSourceUsage(pass, Shader::kMaterialSource_Bitangent);

	int numNormals = numShaderNormals;
	int numTangents = numShaderTangents;
	int numBitangents = numShaderBitangents;

	bool needTangents = vertexShader && (numLightTanVec || numLightTanHalfVec);
	if (needTangents) {
		numNormals = std::max(1, numShaderNormals);
		numTangents = std::max(1, numShaderTangents);
		numBitangents = std::max(1, numShaderBitangents);

		ss << "#define TANGENT_FRAME" << "\r\n";
	}

	if (numNormals > 0)
		ss << "#define NORMALS " << numNormals << "\r\n";
	if (numTangents > 0)
		ss << "#define TANGENTS " << numTangents << "\r\n";
	if (numBitangents > 0)
		ss << "#define BITANGENTS " << numBitangents << "\r\n";

	if (numShaderNormals > 0)
		ss << "#define NUM_SHADER_NORMALS " << numShaderNormals << "\r\n";
	if (numShaderTangents > 0)
		ss << "#define NUM_SHADER_TANGENTS " << numShaderTangents << "\r\n";
	if (numShaderBitangents > 0)
		ss << "#define NUM_SHADER_BITANGENTS " << numShaderBitangents << "\r\n";

	int numLights = std::max(
		numLightPos, 
		std::max(
			numLightVec, 
			std::max(
				numLightHalfVec,
				std::max(
					numLightVertex,
					std::max(
						numLightTanVec,
						std::max(
							numLightTanHalfVec,
							std::max(numLightDiffuseColor, numLightSpecularColor)
						)
					)
				)
			)
		)
	);

	if (numLights > 0) {
		ss << "#define LIGHTS " << numLights << "\r\n";
		if (numLightPos > 0)
			ss << "#define SHADER_LIGHT_POS " << numLightPos << "\r\n";
		if (numLightVec > 0)
			ss << "#define SHADER_LIGHT_VEC " << numLightVec << "\r\n";
		if (numLightHalfVec > 0)
			ss << "#define SHADER_LIGHT_HALFVEC " << numLightHalfVec << "\r\n";
		if (numLightVertex > 0)
			ss << "#define SHADER_LIGHT_VERTEXPOS " << numLightVertex << "\r\n";
		if (numLightTanVec > 0)
			ss << "#define SHADER_LIGHT_TANVEC " << numLightTanVec << "\r\n";
		if (numLightTanHalfVec > 0)
			ss << "#define SHADER_LIGHT_TANHALFVEC " << numLightTanHalfVec << "\r\n";
		if (numLightDiffuseColor > 0)
			ss << "#define SHADER_LIGHT_DIFFUSE_COLOR " << numLightDiffuseColor << "\r\n";
		if (numLightSpecularColor > 0)
			ss << "#define SHADER_LIGHT_SPECULAR_COLOR " << numLightSpecularColor << "\r\n";
	}

	if (GLES) {
		ss << "#define _GLES\r\n";
		ss << "#define MOBILE\r\n";
	}
	
	if (!Inject(engine, "@r:/Source/Shaders/Nodes/GLSL.c", ss))
		return false;
	if (!Inject(engine, "@r:/Source/Shaders/Nodes/Common.c", ss))
		return false;
	if (!Inject(engine, "@r:/Source/Shaders/Nodes/Shader.c", ss))
		return false;

	std::stringstream ex;
	if (!ExpandIncludes(*this, ss, ex))
		return false;

	if (flags & kAssemble_Optimize) {
		String in(ex.str());

		glslopt_ctx *glslopt = glslopt_initialize(GLES);

		glslopt_shader *opt_shader = glslopt_optimize(
			glslopt,
			vertexShader ? kGlslOptShaderVertex : kGlslOptShaderFragment,
			in.c_str, 
			0
		);

		char szPass[32];
		sprintf(szPass, "_pass%d", (int)pass);
		
		{
			engine.sys->files->CreateDirectory("@r:/Temp/Shaders/Logs");
			String path(CStr("@r:/Temp/Shaders/Logs/"));
			path += shader->name;
			path += szPass;
			path += "_unoptimized";
			if (vertexShader) {
				path += ".vert.glsl";
			} else {
				path += ".frag.glsl";
			}
			tools::shader_utils::SaveText(engine, path.c_str, in.c_str);
		}

		if (!glslopt_get_status(opt_shader)) {
			COut(C_Error) << "Error optimizing shader: " << std::endl << in << std::endl << glslopt_get_log(opt_shader) << std::endl;
			engine.sys->files->CreateDirectory("@r:/Temp/Shaders/Logs");

			String path;
			for (int i = 0;; ++i) {
				path.PrintfASCII("@r:/Temp/Shaders/Logs/%s_error_%d.log", shader->name.get(), i);
				if (!engine.sys->files->FileExists(path.c_str)) {
					SaveText(engine, path.c_str, in.c_str);
					break;
				}
			}
			glslopt_shader_delete(opt_shader);
			glslopt_cleanup(glslopt);
			return false;
		}

		std::stringstream z;
		if (GLES) {
			switch (shader->precisionMode) {
			case Shader::kPrecision_Low:
				z << "precision lowp float;\r\n";
				break;
			case Shader::kPrecision_Medium:
				z << "precision mediump float;\r\n";
				break;
			case Shader::kPrecision_High:
				z << "precision highp float;\r\n";
				break;
			}
		}
		z << glslopt_get_output(opt_shader);
		glslopt_shader_delete(opt_shader);
		glslopt_cleanup(glslopt);

		Copy(z, out);

		{
			engine.sys->files->CreateDirectory("@r:/Temp/Shaders/Logs");
			String path(CStr("@r:/Temp/Shaders/Logs/"));
			path += shader->name;
			path += szPass;
			path += "_optimized";
			if (vertexShader) {
				path += ".vert.glsl";
			} else {
				path += ".frag.glsl";
			}
			tools::shader_utils::SaveText(engine, path.c_str, z.str().c_str());
		}
	} else {
		Copy(ex, out);
	}

	return true;
}
Example #13
0
static void imap_change_server(Connection *Conn,PVStr(login))
{	const char *dp;
	IStr(proto,64);
	CStr(host,LNSIZE);
	const char *opts;
	CStr(user,LNSIZE);
	CStr(tmp,LNSIZE);
	int port;

	if( *login == '"' )
		wordScanY(login+1,user,"^\"");
	else	wordScan(login,user);
	if( dp = strrpbrk(user,"@%") ){
		truncVStr(dp);
		strcpy(tmp,user);
		wordScan(dp+1,host);
		sprintf(user,"//%s/%s",host,tmp);
	}
	opts = CTX_mount_url_to(Conn,NULL,"GET",AVStr(user));
	strcpy(proto,"imap");
	if( strncasecmp(user,"imap://",7) == 0 )
	{
		ovstrcpy(user,user+5);
	}
	if( strncasecmp(user,"imaps://",8) == 0 )
	{
		strcpy(proto,"imaps");
		ovstrcpy(user,user+6);
	}

	if( Xsscanf(user,"//%[^/]/%s",AVStr(tmp),AVStr(user)) == 2 ){
		/*
		port = scan_hostportX("imap",tmp,AVStr(host),sizeof(host));
		*/
		port = scan_hostportX(proto,tmp,AVStr(host),sizeof(host));
		sprintf(login,"\"%s\"",user);
		goto SWSERV;
	}

	dp = strrpbrk(login,"@%");
	if( dp == 0 )
		return;

	/*
	port = scan_hostportX("imap",dp+1,AVStr(host),sizeof(host));
	*/
	port = scan_hostportX(proto,dp+1,AVStr(host),sizeof(host));
	if( strtailchr(login) == '"' )
		*(char*)dp++ = '"'; /**/
	truncVStr(dp);

SWSERV:
	sv1log("IMAP LOGIN  %s @ %s:%d\n",login,host,port);
	/*
	set_realserver(Conn,"imap",host,port);
	*/
	set_realserver(Conn,proto,host,port);
	if( streq(CLNT_PROTO,"imaps") && (ClientFlags & PF_MITM_DO) ){
		ServerFlags |= (PF_SSL_IMPLICIT | PF_STLS_DO);
	}
	connect_to_serv(Conn,FromC,ToC,0);
}
Example #14
0
int service_imap(Connection *Conn)
{	FILE *fc,*tc,*ts,*fs;
	FILE *fpv[2]; /**/
	int rds[2],idle;
	const char *dp;
	const char *ap;
	CStr(req,LNSIZE);
	CStr(qtag,LNSIZE);
	CStr(qcmd,LNSIZE);
	CStr(qarg,LNSIZE);
	CStr(qrem,LNSIZE);
	CStr(resp,LNSIZE);
	CStr(rtag,LNSIZE);
	CStr(rstat,LNSIZE);
	CStr(myhost,LNSIZE);
	IStr(serv,MaxHostNameLen);
	int newconn;

	fc = fdopen(FromC,"r");
	tc = fdopen(ToC,"w");

	if( 0 <= ToS ){
		ts = fdopen(ToS,"w");
		fs = fdopen(FromS,"r");
		if( fgetsTIMEOUT(AVStr(resp),sizeof(resp),fs) == NULL )
			return -1;
		sv1log("S: %s",resp);
		IMAP_STARTTLS_withSV(Conn,ts,fs,"");
	}else{
		ts = NULL;
		fs = NULL;
		ClientIF_name(Conn,FromC,AVStr(myhost));
		sprintf(resp,"* OK %s Proxy IMAP4 server DeleGate/%s\r\n",
			myhost,DELEGATE_ver());
		sv1log("D: %s",resp);
	}
	capSTLS(Conn,AVStr(resp));
	fputs(resp,tc);

	for(;;){
		fflush(tc);
		if( pollYY(Conn,"IMAP-REQ",fc) != 0 ){
			break;
		}
		if( fgetsTIMEOUT(AVStr(req),sizeof(req),fc) == NULL ){
			sv1log("C: EOF\n");
			break;
		}
		dp = wordScan(req,qtag);
		ap = wordScan(dp,qcmd);
		dp = wordScan(ap,qarg);
		lineScan(dp,qrem);
		if( strcaseeq(qcmd,"LOGIN") ){
			sv1log("C: %s %s %s ****\n",qtag,qcmd,qarg);
		}else	sv1log("C: %s",req);

		if( method_permitted(Conn,"imap",qcmd,1) == 0 ){
			fprintf(tc,"%s NO (forbidden) %s\r\n",qtag,qcmd);
			fflush(tc);
			continue;
		}
		if( IMAP_STARTTLS_withCL(Conn,fc,tc,qtag,qcmd,qarg) ){
			continue;
		}
		if( needSTLS(Conn) ){
			if( !strcaseeq(qcmd,"XECHO") )
			if( !strcaseeq(qcmd,"LOGOUT") )
			if( !strcaseeq(qcmd,"CAPABILITY") ){
				fprintf(tc,"%s BAD Say STARTTLS first.\r\n",qtag);
				continue;
			}
		}

		if( ts == NULL ){
			if( strcaseeq(qcmd,"XECHO") ){
				while( *ap == ' ' || *ap == '\t' )
					ap++;
				fputs(ap,tc);
				continue;
			}
			if( strcaseeq(qcmd,"LOGOUT") ){
				sv1log("D: %s OK %s\r\n",qtag,qcmd);
				fprintf(tc,"%s OK %s\r\n",qtag,qcmd);
				fflush(tc);
				break;
			}
			if( strcaseeq(qcmd,"CAPABILITY") ){
				sv1log("D: %s OK %s\r\n",qtag,qcmd);
/*
				fprintf(tc,"* CAPABILITY IMAP4 AUTH-LOGIN\r\n");
*/
/*
				fprintf(tc,"* CAPABILITY IMAP4 AUTH-LOGIN");
*/
				fprintf(tc,"* CAPABILITY IMAP4");
				fprintf(tc," IMAP4rev1");
				fprintf(tc," AUTH-LOGIN");
				if( willSTLS_CL(Conn) ){
					fprintf(tc," STARTTLS");
				}
				fprintf(tc,"\r\n");
				fprintf(tc,"%s OK %s\r\n",qtag,qcmd);
				continue;
			}
			if( strcaseeq(qcmd,"LOGIN") )
				imap_change_server(Conn,AVStr(qarg));

			if( ToS < 0 ){
				fprintf(tc,"%s BAD LOGIN user@host first.\r\n",
					qtag);
				sv1log("D: %s BAD LOGIN user@host first.\r\n",
					qtag);
				imaplog(Conn,qcmd,qarg);
				continue;
			}
			ts = fdopen(ToS,"w");
			fs = fdopen(FromS,"r");
			if( fgetsTIMEOUT(AVStr(resp),sizeof(resp),fs) == NULL )
				return -1;
			sv1log(">>>> %s",resp);
			sprintf(req,"%s %s %s %s\r\n",qtag,qcmd,qarg,qrem);
			sv1log(">>>> %s %s %s ****\n",qtag,qcmd,qarg);
			IMAP_STARTTLS_withSV(Conn,ts,fs,"");
			newconn = 1;
		}
		else	newconn = 0;

		if( strcaseeq(qcmd,"AUTHENTICATE") ){
			if( CTX_withAuth(Conn) ){
				sv1log("#### NO AUTHENTICATE [%s]\n",qarg);
				fprintf(tc,"%s NO do LOGIN instead\r\n",qtag);
				fflush(tc);
				continue;
			}
		}
		if( strcaseeq(qcmd,"LOGIN") ){
			CStr(user,64);
			CStr(pass,64);
			if( *qarg == '"' )
				wordScanY(qarg+1,user,"^\"");
			else	wordScan(qarg,user);
			if( *qrem == '"' )
				wordScanY(qrem+1,pass,"^\"");
			else	wordScan(qrem,pass);
			/*
			if( CTX_auth(Conn,user,qrem) < 0 ){
			*/
			if( CTX_auth(Conn,user,pass) < 0 ){
				sv1log("#### [%s] LOGIN forbidden\n",user);
				fprintf(tc,"%s NO LOGIN forbidden\r\n",qtag);
				fflush(tc);
				continue;
			}
		}
		fputs(req,ts);
		fflush(ts);

		rstat[0] = 0;
/*
		if( strcaseeq(qcmd,"IDLE") || strcaseeq(qcmd,"APPEND") ){
*/
		if( strcaseeq(qcmd,"IDLE")
		 || strcaseeq(qcmd,"APPEND")
		 || strcaseeq(qcmd,"AUTHENTICATE")
		){
			fpv[0] = fc;
			fpv[1] = fs;
			idle = 1;
		}else	idle = 0;
		for(;;){
			if( idle ){
				fflush(tc);
				if( fPollIns(0,2,fpv,rds) < 0 )
					break;
				if( 0 < rds[0] ){
					if( fgets(req,sizeof(req),fc) == NULL ){
						sv1log("C> EOF in IDLE\n");
						goto EXIT;
					}
					Verbose("C> %s",req);
					fputs(req,ts);
					fflush(ts);
				}
				if( rds[1] <= 0 )
					continue;
			}
			if( fgetsTIMEOUT(AVStr(resp),sizeof(resp),fs) == NULL ){
				sv1log("S: EOF\n");
				break;
			}
			dp = wordScan(resp,rtag);
			dp = wordScan(dp,rstat);

			if( streq(rtag,"*") && strcaseeq(qcmd,"CAPABILITY") ){
				capSTLS(Conn,QVStr((char*)dp,resp));
			}
			if( redirect(fs,qcmd,resp,AVStr(serv),AVStr(req)) ){
				sv1log("IMAP redirect=>%s %s\n",serv,req);
				set_realserver(Conn,"imap",serv,143);
				connect_to_serv(Conn,FromC,ToC,0);
				if( 0 <= ToS ){
					redirectSV(Conn,serv,req,AVStr(resp),
						&fs,&ts);
				}
			}
			fputs(resp,tc);
			if( qtag[0] == 0 || strcmp(qtag,rtag) == 0 )
				break;
			Verbose("S> %s",resp);
		}
		sv1log("S: %s",resp);
		fflush(tc);
		if( strcaseeq(qcmd,"LOGOUT") && strcaseeq(rstat,"OK")
		 || feof(fs) )
			break;

		if( strcaseeq(qcmd,"LOGIN") )
		if( newconn )
		if( !strcaseeq(rstat,"OK") ){
			fprintf(ts,"X LOGOUT\r\n");
			/*
			fclose(ts);
			fclose(fs);
			*/
			finishServYY(FL_ARG,Conn);
			CTX_fcloses(FL_ARG,"IMAPserv",Conn,ts,fs);
			ts = fs = NULL;
			ToS = FromS = -1;
			sv1log(">>>> IMAP connection to the server closed.\n");
			/* must clear FSV,FTOSV,FFROMSV if exists */
		}
		if( strcaseeq(qcmd,"LOGIN") )
			imaplog(Conn,qcmd,qarg);
	}
EXIT:
	finishServYY(FL_ARG,Conn);
	CTX_fcloses(FL_ARG,"IMAPserv",Conn,ts,fs);
	CTX_fcloses(FL_ARG,"IMAPclnt",Conn,tc,fc);
	return 0;
}
Example #15
0
void udp_relayX(Connection *Conn,int csc,int csv[])
{	int svsock;
	int sockv[1024],readyv[1024],sx; /* must be lt/eq FD_SESIZE */
	int nsock; /* number of clients */
	CStr(buff,0x8000);
	int rcc,wcc;
	int nready;
	CStr(ihost,64);
	int iport;
	CStr(svhost,64);
	int svport;
	const char *clhost;
	int clport;
	UDP_Assoc *ua;
	UDP_Assoc *udpav[MAXASSOC*4]; /**/
	int udpxv[MAXASSOC*4];
	int lastrelay,idle;
	const char *aaddr;
	int svportmap;
	int portnumv[64];
	int csi;
	int istcp[MAXASSOC];
	int ccc = 0; /* tcp clients */
	int usocks = 0; /* UDP SOCKS */
	int update = 0;
	int ai;

	/* is this necessary or effective ? */
	socks_addservers();

	if( MAXASSOC < UDPRELAY_MAXASSOC ){
		UDPRELAY_MAXASSOC = MAXASSOC;
	}
	sv1log("MAXIMA=udprelay:%d (max. udp assoc.)\n",UDPRELAY_MAXASSOC);

	if( (aaddr = gethostaddr(DST_HOST)) == NULL ){
		sv1log("#### ERROR: bad destination host [%s]\n",DST_HOST);
		return;
	}
	strcpy(svhost,aaddr);
	svport = DST_PORT;
	svportmap = DFLT_PORTMAP;
	if( svportmap ){
		/* get port numbers of incoming ports ... */
		for( csi = 0; csi < csc; csi++ ){
			portnumv[csi] = sockPort(csv[csi]) + svportmap;
			portnumv[csi] &= ~0x40000000; /* clear IS_PORTMAP */
		}
	}

	expand_fdset(MAXASSOC);
	uassocv = (UDP_Assoc**)calloc(MAXASSOC+1,sizeof(UDP_Assoc*));
	for( csi = 0; csi < csc; csi++ )
		sockv[csi] = csv[csi];
	for( csi = 0; csi < csc; csi++ )
		istcp[csi] = !isUDPsock(sockv[csi]);
	nsock = 0;
	lastrelay = 0;

	for(;;){
UPDATE:
		if( update ){
			int ai;
			update = 0;
			ccc = 0;
			for( ai = 0; ua = uassocv[ai]; ai++ ){
				if( ua->ua_clpriv ){
				udpxv[csc + ccc] = ai;
				udpav[csc + ccc] = ua;
				sockv[csc + ccc++] = ua->ua_clsock;
				}
			}
			nsock = 0;
			for( ai = 0; ua = uassocv[ai]; ai++ ){
				udpxv[csc+ccc + nsock] = ai;
				udpav[csc+ccc + nsock] = ua;
				sockv[csc+ccc + nsock++] = ua->ua_svsock;
			}
			usocks = 0;
			for( ai = 0; ua = uassocv[ai]; ai++ ){
				int ns = csc+ccc+nsock;
				if( 0 <= ua->ua_svSOCKS ){
					udpxv[ns+usocks] = ai;
					udpav[ns+usocks] = ua;
					sockv[ns+usocks] = ua->ua_svSOCKS;
					usocks++;
				}
			}
		}
		/*
		nready = PollIns(10*1000,csc+nsock+ccc,sockv,readyv);
		*/
		nready = PollIns(10*1000,csc+ccc+nsock+usocks,sockv,readyv);
		if( nready < 0 ){
			/*
			sv1log("UDPRELAY: ABORT PollIns(%d) = %d\n",nready);
			*/
			sv1log("UDPRELAY: ABORT PollIns(%d+%d+%d+%d)=%d\n",
				csc,ccc,nsock,usocks,nready);
			for( ai = 0; ai < csc+ccc+nsock+usocks; ai++ ){
				sv1log("[%2d] %d\n",ai,sockv[ai]);
			}
			break;
		}
		if( nready == 0 ){
			idle = time(0) - lastrelay;
			if( SERVER_TIMEOUT && lastrelay )
			if( SERVER_TIMEOUT < idle){
				sv1log("UDPRELAY: SERVER TIMEOUT (idle %ds)\n",
					idle);
				break;
			}
			killTimeouts(uassocv);
			/*
			nsock = getsocks(uassocv,&sockv[csc]);
			*/
			update = 1;
			continue;
		}
		lastrelay = time(0);

		for( sx = 0; sx < csc; sx++ )
		if( 0 < readyv[sx] && istcp[sx] ){
			CStr(local,256);
			CStr(remote,256);
			int clsk;
			strcpy(remote,"*:*");
			strcpy(local,"*:*");
			clsk = VSocket(Conn,"ACPT/",sockv[sx],AVStr(local),AVStr(remote),"");
/*
			setNonblockingIO("UDPRELAY-CL",clsk,1);
*/
			SetNonblockingIO("UDPRELAY-CL",clsk,1);
			iport = getpeerAddr(clsk,AVStr(ihost));
			if( clsk <= 0 || iport <= 0 ){
				sv1log("UDPRELAY: accept() errno=%d\n",errno);
				continue;
			}
			if( svportmap ){
				svport = portnumv[sx];
			}
			ua = newUA(Conn,uassocv,ihost,iport,svhost,svport);
			ua->ua_clsock = clsk;
			ua->ua_clpriv = 1;
			update = 1;
		}else
		if( 0 < readyv[sx] ){
			rcc = recvFromA(sockv[sx],AVStr(buff),sizeof(buff),0,AVStr(ihost),&iport);
			if( rcc <= 0 ){
				sv1log("UDPRELAY: recv() == 0, errno=%d\n",errno);
				break;
			}
			if( svportmap ){
				svport = portnumv[sx];
			}
			ua = findUAbysrc(uassocv,ihost,iport,svhost,svport);
			if( ua == NULL ){
				ua = newUA(Conn,uassocv,ihost,iport,svhost,svport);
				if( ua == NULL ){
					continue;
				}
				ua->ua_clsock = sockv[sx];
				if( ua->ua_svsock < 0 )
					continue;
				/*
				nsock = getsocks(uassocv,&sockv[csc]);
				*/
				update = 1;
			}
			toServ(ua,buff,rcc,svhost,svport,ihost,iport);
			/*
			ua->ua_mtime = time(0);
			ua->ua_upcnt++;
			ua->ua_upbytes += rcc;
			if( UDPRELAY_RPORT_FIX )
				wcc = Send(ua->ua_svsock,buff,rcc);
			else	wcc = SendTo(ua->ua_svsock,buff,rcc,svhost,svport);
			Verbose("TO SERV#%d: %s:%d %3d> %s:%d\n",
				ua->ua_id,ihost,iport,rcc,svhost,svport);
			*/
			if( nready == 1 )
				continue;
		}

		for( sx = csc; sx < csc+ccc; sx++ )
		if( 0 < readyv[sx] ){
			rcc = recv(sockv[sx],buff,sizeof(buff),0);
			if( rcc <= 0 ){
				int ux = getUAx(uassocv,udpav[sx]);
				if( ux < 0 ){
					sv1log("## delUA-CL(%d)?\n",ux);
					continue;
				}
				delUA(uassocv,ux,"TCPreset-CL",1);
				/* here udpxv[] becomes inconsistent */
				update = 1;
			}else{
				ua = udpav[sx];
				toServ(ua,buff,rcc,svhost,svport,NULL,0);
			}
		}

		/*
		for( sx = csc; sx < csc+nsock; sx++ ){
		*/
		for( sx = csc+ccc; sx < csc+ccc+nsock; sx++ ){
			if( readyv[sx] <= 0 )
				continue;
			ua = udpav[sx];
			svsock = sockv[sx];

			if( 0 <= ua->ua_svSOCKS )
			rcc = RecvFrom(svsock,buff,sizeof(buff),AVStr(ihost),&iport);
			else
			rcc = recvFromA(svsock,AVStr(buff),sizeof(buff),0,AVStr(ihost),&iport);

			if( rcc <= 0 ){
				if( ua->ua_svtcp ){
					int ux = getUAx(uassocv,udpav[sx]);
					if( ux < 0 ){
						sv1log("## delUA-SV(%d)?\n",ux);
						continue;
					}
					delUA(uassocv,ux,"TCPreset-SV",1);
					update = 1;
				}
				readyv[sx] = -1;
				continue;
			}

			/*
			ua = findUAbysock(uassocv,svsock);
			*/
			ua->ua_mtime = time(0);
			ua->ua_downcnt++;
			ua->ua_downbytes += rcc;
			clhost = ua->ua_clhost;
			clport = ua->ua_clport;
			/*
			wcc = SendTo(ua->ua_clsock,buff,rcc,clhost,clport);
			*/
			wcc = sendToA(ua->ua_clsock,buff,rcc,0,clhost,clport);

			Verbose("TO CLNT#%d: %s:%d <%-3d %s:%d\n",
				ua->ua_id,clhost,clport,rcc,ihost,iport);
		}
		for( sx = csc+ccc+nsock; sx < csc+ccc+nsock+usocks; sx++ ){
			int ux;
			if( readyv[sx] <= 0 )
				continue;
			ua = udpav[sx];
			ux = getUAx(uassocv,udpav[sx]);
			if( ux < 0 ){
				sv1log("## delUA-CTL(%d)?\n",ux);
				continue;
			}
			sv1log("## detected disconn. by SOCKS CTL [%d]\n",ux);
			delUA(uassocv,ux,"SOCKSCTLreset-SV",1);
			update = 1;
		}
	}
}
Example #16
0
static int ls1(PCStr(file),LsArg *lsa)
{	const char *dir = lsa->l_dir;
	const char *fmt = lsa->l_fmt;
	const char *oline = lsa->l_buf;
	const char *sp;
	char sc;
	FileStat st;
	int rcode;
	int st_ok;
	int width;
	CStr(path,1024);
	CStr(name,1024);
	CStr(buf,1024);
	refQStr(op,lsa->l_buf); /**/
	const char *tail;
	/*
	char *tfmt = 0;
	*/
	const char *tfmt = lsa->l_tfmt;

	((char*)oline)[0] = 0;
	lsa->l_ikey = 0;
	if( file[0] == '.' && !lsa->l_all )
		return 0;

	if( lsa->l_maskrexp ){
		tail = frex_match(lsa->l_maskrexp,file);
		if( tail == NULL || *tail != 0 )
			return 0;
	}

	st_ok = 0;
	path[0] = 0;
	if( dir && dir[0] )
		strcpy(path,dir);
	if( *path )
	if( strtailchr(path) != '/' )
	if( *file != '/' )
		strcat(path,"/");
	strcat(path,file);

	if( lsa->l_stp ){
		st = *lsa->l_stp;
		st_ok = 1;
	}

	op = (char*)oline;
	for( sp = fmt; sc = *sp; sp++ ){
		assertVStr(lsa->l_buf,op+1);
		if( op[0] != 0 )
			op += strlen(op);

		if( sc != '%' || sp[1] == 0 ){
			setVStrPtrInc(op,sc); setVStrEnd(op,0);
			continue;
		}
		sp++;
		width = numscan(&sp);
		sc = *sp;

		if( sc == 'V' ){
			const char *rp;
			if( dir == 0 || dir[0] == 0 ){
				strcpy(op,lsa->l_vbase);
				continue;
			}
			strcpy(op,lsa->l_vbase);
			rp = strrpbrk(file,"/\\");
			if( rp && rp != file && rp[1] )
				rp += 1;
			else	rp = file;
			if( *op && strtailchr(op) != '/' && *rp != '/' )
				strcat(op,"/");
			strcat(op,rp);
			continue;
		}
		if( st_ok == 0 && lsa->l_virtual ){
			if( Vstat(file,AVStr(path),AVStr(name),0,0,&st)==0 ){
				file = name;
				st_ok = 1;
			}else{
				CStr(xpath,1024);
				sprintf(xpath,"%s%s",path,VNODE_EXT);
				if( File_is(xpath) ){
					truncVStr(oline);
					break;
				}
			}
		}
		if( sc == 'N' ){
			strcpy(op,file);
			continue;
		}
		if( sc == 'A' ){
			strcpy(op,path);
			continue;
		}
		if( st_ok == 0 ){
			errno = 0;
			if( lsa->l_reflink || !INHERENT_lstat() )
				rcode = stat(path,&st);
			else	rcode = lstat(path,&st);
			if( rcode != 0 ){
				/* maybe errno=EOVERFLOW */
				fprintf(stderr,"FAILED stat(%s), errno=%d\n",
					path,errno);
				((char*)oline)[0] = 0;
				break;
			}
			st_ok = 1;
		}
		if( sc == 'x' ){
			sc = *++sp;
			switch( sc ){
			    case 0: return 0;
			    case 'P':
				mlstPerm(AVStr(op),&st);
				continue;
			    case 'Y':
				if( S_ISDIR(st.st_mode) ){
					if( streq(file,".") )
						sprintf(op,"cdir");
					else
					if( streq(file,"..") )
						sprintf(op,"pdir");
					else	sprintf(op,"dir");
				}else
				if( S_ISREG(st.st_mode) )
					sprintf(op,"file");
				else	sprintf(op,"unknown");
				continue;
				break;
			    default:
				continue;
			    case 'T':
				tfmt = "%Y%m%d%H%M%S";
				sc = *++sp;
				break;
			    case 'U':
			    {
				struct {
					int u_dev;
					int u_ino;
				} u;
				u.u_dev = st.st_dev;
				u.u_ino = st.st_ino;
				str_to64((char*)&u,sizeof(u),AVStr(buf),sizeof(buf),1);
				Xsscanf(buf,"%[a-zA-Z0-9/+]",AVStr(op));
				continue;
			    }
			    break;
			}
		}

		switch( sc ){
			case 'd': {
				void ftoMD5(FILE *fp,char md5[]);
				FILE *fp;
				CStr(digest,64);
				if( fp = fopen(path,"r") ){
					ftoMD5(fp,(char*)digest);
					fclose(fp);
				}else	strcpy(digest,"-");
				sprintf(op,"%*s",width,digest);
				break;
			}
			case 'm': lsa->l_ikey = st.st_mtime; break;
			case 'a': lsa->l_ikey = st.st_atime; break;
			case 'z': lsa->l_ikey = st.st_size; break;
			case 'I': sprintf(op,"%*d",width,ll2i(st.st_ino)); break;
			case 'T': setVStrPtrInc(op,Ftypec(st)); setVStrEnd(op,0); break;
			case 'M': strcpy(op,Fmodes(st)); break;
			case 'L': sprintf(op,"%*d",width,ll2i(Fnlink(st))); break;
			case 'O': sprintf(op,"%*s",width,Fowner(st,AVStr(buf))); break;
			case 'G': sprintf(op,"%*s",width,Fgroup(st,AVStr(buf))); break;
			/*
			case 'S': sprintf(op,"%*d",width,Fbytes(st)); break;
			*/
			/*
			case 'S': sprintf(op,"%*u",width,Fbytes(st)); break;
			*/
			case 'S': sprintf(op,"%*lld",width,Fbytes(st)); break;
			case 'K': sprintf(op,"%*d",width,Fkbytes(st)); break;
			/*
			case 'D': sprintf(op,"%*s",width,rsctime(st.st_mtime,AVStr(buf))); break;
			case 'U': sprintf(op,"%*s",width,rsctime(st.st_atime,AVStr(buf))); break;
			*/
			case 'C': printTime(op,width,tfmt,st.st_ctime); break;
			case 'D': printTime(op,width,tfmt,st.st_mtime); break;
			case 'U': printTime(op,width,tfmt,st.st_atime); break;
		}
	}
	return 0;
}
Example #17
0
void InitGraphics(const CmdLineArgs& args, int flags)
{
	const bool setup_vmode = (flags & INIT_HAVE_VMODE) == 0;

	if(setup_vmode)
	{
		InitSDL();

		if (!g_VideoMode.InitSDL())
			throw PSERROR_System_VmodeFailed(); // abort startup

#if !SDL_VERSION_ATLEAST(2, 0, 0)
		SDL_WM_SetCaption("0 A.D.", "0 A.D.");
#endif
	}

	RunHardwareDetection();

	tex_codec_register_all();

	const int quality = SANE_TEX_QUALITY_DEFAULT;	// TODO: set value from config file
	SetTextureQuality(quality);

	ogl_WarnIfError();

	// Optionally start profiler GPU timings automatically
	// (By default it's only enabled by a hotkey, for performance/compatibility)
	bool profilerGPUEnable = false;
	CFG_GET_VAL("profiler2.gpu.autoenable", Bool, profilerGPUEnable);
	if (profilerGPUEnable)
		g_Profiler2.EnableGPU();

	if(!g_Quickstart)
	{
		WriteSystemInfo();
		// note: no longer vfs_display here. it's dog-slow due to unbuffered
		// file output and very rarely needed.
	}

	if(g_DisableAudio)
	{
		// speed up startup by disabling all sound
		// (OpenAL init will be skipped).
		// must be called before first snd_open.
#if CONFIG2_AUDIO
		ISoundManager::SetEnabled(false);
#endif
	}

	g_GUI = new CGUIManager(g_ScriptingHost.GetScriptInterface());

	// (must come after SetVideoMode, since it calls ogl_Init)
	if (ogl_HaveExtensions(0, "GL_ARB_vertex_program", "GL_ARB_fragment_program", NULL) != 0 // ARB
		&& ogl_HaveExtensions(0, "GL_ARB_vertex_shader", "GL_ARB_fragment_shader", NULL) != 0) // GLSL
	{
		DEBUG_DISPLAY_ERROR(
			L"Your graphics card doesn't appear to be fully compatible with OpenGL shaders."
			L" In the future, the game will not support pre-shader graphics cards."
			L" You are advised to try installing newer drivers and/or upgrade your graphics card."
			L" For more information, please see http://www.wildfiregames.com/forum/index.php?showtopic=16734"
		);
		// TODO: actually quit once fixed function support is dropped
	}

	const char* missing = ogl_HaveExtensions(0,
		"GL_ARB_multitexture",
		"GL_EXT_draw_range_elements",
		"GL_ARB_texture_env_combine",
		"GL_ARB_texture_env_dot3",
		NULL);
	if(missing)
	{
		wchar_t buf[500];
		swprintf_s(buf, ARRAY_SIZE(buf),
			L"The %hs extension doesn't appear to be available on your computer."
			L" The game may still work, though - you are welcome to try at your own risk."
			L" If not or it doesn't look right, upgrade your graphics card.",
			missing
		);
		DEBUG_DISPLAY_ERROR(buf);
		// TODO: i18n
	}

	if (!ogl_HaveExtension("GL_ARB_texture_env_crossbar"))
	{
		DEBUG_DISPLAY_ERROR(
			L"The GL_ARB_texture_env_crossbar extension doesn't appear to be available on your computer."
			L" Shadows are not available and overall graphics quality might suffer."
			L" You are advised to try installing newer drivers and/or upgrade your graphics card.");
		g_Shadows = false;
	}

	ogl_WarnIfError();
	InitRenderer();

	InitInput();

	ogl_WarnIfError();

	try
	{
		if (!Autostart(args))
		{
			const bool setup_gui = ((flags & INIT_NO_GUI) == 0);
			// We only want to display the splash screen at startup
			CScriptValRooted data;
			if (g_GUI)
			{
				ScriptInterface& scriptInterface = g_GUI->GetScriptInterface();
				scriptInterface.Eval("({})", data);
				scriptInterface.SetProperty(data.get(), "isStartup", true);
			}
			InitPs(setup_gui, L"page_pregame.xml", data.get());
		}
	}
	catch (PSERROR_Game_World_MapLoadFailed& e)
	{
		// Map Loading failed

		// Start the engine so we have a GUI
		InitPs(true, L"page_pregame.xml", JSVAL_VOID);

		// Call script function to do the actual work
		//	(delete game data, switch GUI page, show error, etc.)
		CancelLoad(CStr(e.what()).FromUTF8());
	}
}
Example #18
0
void dir2ls(PCStr(dirpath),FileStat *stp,PCStr(opt),xPVStr(fmt),FILE *fp)
{	const char *op;
	const char *dp;
	int onow;
	int flags;
	char sortspec;
	LsArg lsa;
	CStr(fmt_s,256);
	CStr(fmt_a,256);
	CStr(line,2048);
	int f_l,f_s;
	CStr(fmt_b,256);
	CStr(spath,1024);
	const char *vbase = 0;
	CStr(vbaseb,1024);

	CStr(xpath,1024);
	if( pathnorm("sort_ls",dirpath,AVStr(xpath)) ){
		dirpath = xpath;
	}

	if( opt == NULL )
		opt = "";

	bzero(&lsa,sizeof(lsa));
	lsa.l_tfmt = getenv("LSTFMT");
	flags = 0;

	for( op = opt; *op; op++ ){
		switch( *op ){
			case 'a':
				lsa.l_all = 1;
				break;
			case 'l':
				flags |= O_FORM_L;
				break;
			case 's':
				flags |= O_FORM_S;
				break;
			case 'L':
				lsa.l_reflink = 1;
				break;
			case 'V':
				lsa.l_virtual = 1;
				break;
			case 'd':
				flags |= O_PUTSELF;
				break;
			case 't':
				flags |= O_TIMESORT;
				break;
			case 'z':
				flags |= O_SIZESORT;
				break;
			case 'u':
				flags |= O_BYATIME;
				break;
			case '*':
				flags |= O_REXP;
				break;
			case '/':
				flags |= O_VBASE;
				vbase = op + 1;
				while( op[1] ) *op++; /* skip remaining */
				if( strpbrk(vbase,"*?[") ){
/* vbase is "const" */
					strcpy(vbaseb,vbase);
					vbase = vbaseb;
					if( dp = strrchr(vbase,'/') )
						((char*)dp)[1] = 0;
					else	Xstrcpy(QVStr((char*)vbase,vbaseb),"");
				}
				break;
		}
	}
	if( (DoFileRexp || (flags & O_REXP)) && strpbrk(dirpath,"*?[") ){
		strcpy(spath,dirpath);
		dirpath = spath;
		if( dp = strrchr(dirpath,'/') ){
			lsa.l_maskrexp = frex_create(dp + 1);
			truncVStr(dp);
		}else{
			lsa.l_maskrexp = frex_create(dirpath);
			dirpath = ".";
		}
	}

	if( fmt == NULL ){
		cpyQStr(fmt,fmt_b);
		setVStrEnd(fmt,0);

		if( flags & O_FORM_S )
			strcat(fmt,"%4K ");
		if( flags & O_FORM_L )
			strcat(fmt,"%T%M %2L %-8O %8S %D ");
			/*
			strcat(fmt,"%T%M%3L %-8O %8S %D ");
			*/

		if( flags & O_VBASE )
			strcat(fmt,"%V");
		else	strcat(fmt,"%N");
	}

	if( flags & O_TIMESORT ){
		if( flags & O_BYATIME )
			sortspec = 'a';
		else	sortspec = 'm';
		sprintf(fmt_s,"%%%c%s",sortspec,fmt);
		fmt = fmt_s;
	}
	if( flags & O_SIZESORT ){
		sprintf(fmt_s,"%%%c%s",'z',fmt);
		fmt = fmt_s;
	}
	if( flags & O_BYATIME ){
		strcpy(fmt_a,fmt);
		fmt = fmt_a;
		if( dp = strstr(fmt,"%D") )
			((char*)dp)[1] = 'U';
	}

	lsa.l_dir = dirpath;
	lsa.l_vbase = (char*)vbase;
	lsa.l_stp = stp;
	lsa.l_fmt = (char*)fmt;
	lsa.l_out = fp;
	setQStr(lsa.l_buf,line,sizeof(line));
	line[0] = 0;

	onow = TIME_NOW;
	TIME_NOW = time(0);
	setpwent();

	if( !(flags & O_PUTSELF) && fileIsdir(dirpath) )
		sort_ls(dirpath,&lsa);
	else{
		lsa.l_dir = "";
		lsa.l_all = 1;
		ls1(dirpath,&lsa);
		fprintf(fp,"%s\r\n",lsa.l_buf);
	}

	endpwent();
	TIME_NOW = onow;

	if( lsa.l_maskrexp )
		frex_free(lsa.l_maskrexp);
	return;
}
Example #19
0
void CGmObjSplashTxt::AppendLine( const char *pcLine )
{
	m_oArrTxt.Append( CStr( pcLine ) );
}
Example #20
0
int LIST_compress(FILE *in,FILE *out,int isactive,int level)
{	CStr(prev,2048);
	CStr(line,2048);
	CStr(CRLF,128);
	CStr(xline,2048);
	refQStr(xp,xline); /**/
	const char *words[4]; /**/
	CStr(tmp,64);
	int max,min;
	int len;
	int total;

	total = 0;
	if( isactive && level != 0 ){
		sprintf(line,"compress %d\r\n",level);
		fputs(line,out);
		total = strlen(line) + strlen(CRLF);
	}

	prev[0] = 0;
	while( Fgets(AVStr(line),sizeof(line),in,AVStr(CRLF),NULL) != NULL ){
		if( !isactive ){
			fputs(line,out);
			fputs(CRLF,out);
			total += strlen(line);
			continue;
		}else{
			Mode = NULL;
			scanwords(line,4,words);
			if( Mode == NULL || Mode[0] == 0 )
				continue;

			max = atoi(Max);
			min = atoi(Min);
			if( max < 0 ) max = 0;
			if( min < 0 ) min = 0;
			if( level == 0 ){
				sprintf(xline,"%s %d %d %c%s",
					Group,max,min,Mode[0],CRLF);
				total += strlen(xline);
				fputs(xline,out);
				continue;
			}
		}
		for( len = 0; len < 63; len++ )
			if( Group[len] != prev[len] )
				break;
		strcpy(prev,Group);
		xp = xline;
		sprintf(xp,"%c%c%s %s",basis_64[len],Mode[0],Group+len,
			itoB64(max,tmp,sizeof(tmp)));
		xp += strlen(xp);
		if( min != max + 1 ){
			sprintf(xp," %s",itoB64(min,tmp,sizeof(tmp)));
			xp += strlen(xp);
		}
		strcpy(xp,CRLF);
		fputs(xline,out);
		total += strlen(xline);
	}
	return total;
}
Example #21
0
 CStr    GetErrorMsg()
 {
     return (myHSTMT != NULL)? myHSTMT->GetErrorMsg() : CStr("Unknown error.");
 }
Example #22
0
int FTP_STARTTLS_withSV(Connection *Conn,FILE *ts,FILE *fs){
	if( REAL_PROTO[0] == 0 ){
		sv1log("--WARN FTP_STARTTLS_withSV no REAL_PROTO (%s)\n",
			DFLT_PROTO);
	}
	if( dontDupSTLS(Conn,"FSV") ){
		return 0;
	}
	if( 0 <= ToS )
	if( willSTLS_SV(Conn) ){
		CStr(resp,128);

		if( ServerFlags & PF_SSL_IMPLICIT ){ /* ftps://serv */
			if( ServerFlags & PF_STLS_ON ){
				return 1;
			}
			strcpy(resp,"200\r\n");
		}else{
		if( ServerFlags & PF_STLS_SSL )
			fprintf(ts,"AUTH SSL\r\n");
		else	fprintf(ts,"AUTH TLS\r\n");
		fflush(ts);
		fgets(resp,sizeof(resp),fs);
			sv1log("--AUTH resp: %s",resp);
			/* 9.9.7 might be a resp. in multi-lines */
		}
		
		if( *resp == '2' ){
			int fsv;
			checkFTP_STLS(Conn);
			fsv = insertTLS_SV(Conn,ToC,ToS);
			if( 0 <= fsv ){
				ToSX = dup(ToS); /* for ServSock() */
				    /* to be closed on closing the server */
				dup2(fsv,fileno(ts));
				dup2(fsv,fileno(fs));
				close(fsv);

				if( (ServerFlags & PF_STLS_SSL) == 0 ){
					/* AUTH TLS */
					if( *resp == '2' ){
						fprintf(ts,"PBSZ 0\r\n");
						fflush(ts);
						fgets(resp,sizeof(resp),fs);
					}
					if( *resp == '2' ){
						if( ConnectFlags&COF_NODATASSL )
						fprintf(ts,"PROT C\r\n");
						else
						fprintf(ts,"PROT P\r\n");
						fflush(ts);
						fgets(resp,sizeof(resp),fs);
					}
				}
				return 1;
			}
		}
		if( (ServerFlags & PF_STLS_OPT) == 0 ){
			return -1;
		}
	}
	return 0;
}
Example #23
0
static void relay_resp(FILE *fs,int dsock,int timeout,PVStr(resp),PCStr(com),int dolog){
	CStr(res,1024);
	FILE *fp;
	refQStr(rp,resp);
	refQStr(dp,res);
	int tout0;
	int tout;

	if( 0 < timeout )
		tout0 = tout = timeout;
	else	tout0 = tout = 3*1000;

	if( resp )
		setVStrEnd(resp,0);
	if( fPollIn(fs,tout) <= 0 ){
		DEBUG("--SFTP >> response timeout [%s]%d\n",com,tout);
		return;
	}
	if( 0 <= dsock )
		fp = fdopen(dsock,"w");
	else	fp = NULL;

	for(;;){
		if( 0 < fgetsBuffered(AVStr(res),sizeof(res),fs) ){
		}else
		if( fgetsTO(AVStr(res),sizeof(res),fs,tout,1) == NULL ){
			break;
		}
		if( *res == '@' ){
			dolog = 1;
			ErrorResp = 1;
		}
		if( dolog ){
			if( strchr(res,'\n') )
				DEBUG("--SFTP >>(%s) %s",com,res);
			else	DEBUG("--SFTP >>(%s/NO-NL)[%s]\n",com,res);
		}
		if( strtailstr(res,"sftp> ") ){
			if( rp ){
if( lGATEWAY() )
sv1log("####@@@@ resp[%s][%s]\n",res,resp);
				strcpy(rp,res);
				rp += strlen(rp);
			}
			if( fPollIn(fs,10) <= 0 )
				break;
		}
		if( dp = strpbrk(res,"\r\n") )
			strcpy(dp,"\r\n");
		if( fp != NULL )
			fputs(res,fp);
		if( streq(res,"\r\n") || streq(res,"\n") ){
			/* ignore empty lines */
		}else
		if( rp ){
			strcpy(rp,res);
			rp += strlen(rp);
		}
		if( resp && *resp == 0 ){
			tout = tout0;
		}else
		if( strtailstr(res,":")
		 || strtailstr(res,": ")
		 || strtailstr(res,"? ")
		){
			tout = 1;
		}else
		if( *res == '\r' || *res == '\n' )
			tout = 100;
		else	tout = tout0;
	}
	if( fp != NULL )
		fflush(fp);
	ErrorResp = 0;
}
Example #24
0
void scan_STLS(Connection *Conn,PCStr(stls)){
	CStr(filt,1024);
	CStr(proto,1024);
	CStr(cmapb,1024);
	CStr(map,1024);
	CStr(opt1,1024);
	const char *cmap;
	const char *fp;
	refQStr(np,filt);
	refQStr(op,opt1);
	int fcl = 0;
	int fsv = 0;
	int opt = 0;
	const char *com = "sslway";
	CStr(comb,1024);

	/*
	cmap = wordscanY(stls,AVStr(filt),sizeof(filt),"^:");
	if( *cmap == ':' )
		cmap++;
	cmap = wordscanY(cmap,AVStr(proto),sizeof(proto),"^:");
	if( proto[0] )
		sprintf(cmapb,"starttls/{%s}%s",proto,cmap);
	else	sprintf(cmapb,"starttls%s",cmap);
	*/
	strcpy(filt,"");
	strcpy(proto,"");
	strcpy(map,"");
	scan_Listlist(stls,':',AVStr(filt),AVStr(proto),AVStr(map),VStrNULL,VStrNULL);
	if( proto[0] )
		/*
		sprintf(cmapb,"starttls/{%s}%s%s",proto,*map?":":"",map);
		*/
		sprintf(cmapb,"starttls//{%s}%s%s",proto,*map?":":"",map);
	else	sprintf(cmapb,"starttls%s%s",*map?":":"",map);

	for( fp = filt; *fp;){
		int optL;
		np = wordscanY(fp,AVStr(opt1),sizeof(opt1),"^,");
		optL = 0;

		if( strncaseeq(opt1,"-im",3) ){
			STLS_implicit_wait = -1;
			STLS_wait_set = 1;
			if( (fsv & PF_STLS_DO) && (fcl & PF_STLS_DO)==0 ){
				STLS_implicit_waitSV = -1;
				STLS_wait_setSV = 1;
			}
			goto NEXT;
		}
		if( strncaseeq(opt1,"im",2) ){
			STLS_implicit_wait = Scan_period(opt1+2,'s',0);
			STLS_wait_set = 1;
			if( (fsv & PF_STLS_DO) && (fcl & PF_STLS_DO)==0 ){
				STLS_implicit_waitSV = STLS_implicit_wait;
				STLS_wait_setSV = 1;
			}
			if( STLS_implicit_wait && STLS_implicit_wait < 0.001 )
				STLS_implicit_wait = 0.001;
			goto NEXT;
		}
		if( *opt1 == '-' ){
			ovstrcpy(opt1,opt1+1);
			optL |= PF_STLS_OPT;
		}
		if( op = strchr(opt1,'/') ){
			setVStrPtrInc(op,0);
			if( strncaseeq(op,"ssl",3) ){
				optL |= PF_STLS_SSL;
			}
		}
		if( strcaseeq(opt1,"opt") ){
			opt = PF_STLS_OPT;
		}else
		if( strcaseeq(opt1,"ssl") ){
			opt = PF_STLS_SSL;
		}else
		if( strcaseeq(opt1,"mim") || strcaseeq(opt1,"mitm") ){
			fsv = PF_STLS_DO | opt | optL | PF_MITM_DO;
			fcl = PF_STLS_DO | opt | optL | PF_MITM_DO;
		}else
		if( strcaseeq(opt1,"FSV") || strcaseeq(opt1,"SV") ){
			fsv = PF_STLS_DO | opt | optL;
			if( strneq(op,"im",2) ) fsv |= PF_SSL_IMPLICIT;
		}else
		if( strcaseeq(opt1,"FCL") || strcaseeq(opt1,"CL") ){
			fcl = PF_STLS_DO | opt | optL;
			if( strneq(op,"im",2) ) fcl |= PF_SSL_IMPLICIT;
		}else{
			syslog_ERROR("FILTER[%s]: %s\n",com,fp);
			com = fp;
			if( 1 < num_ListElems(com,':') ){
				sprintf(comb,"{%s}",com);
				com = comb;
			}
			break;
		}
	NEXT:
		fp = np;
		if( *fp == ',' )
			fp++;
	}
	if( fsv & PF_STLS_DO ){
		withSTLS_FSV++;
		sprintf(map,"%s:FSV:%s",com,cmapb);
		if( fsv & PF_MITM_DO  ) Strins(AVStr(map),"--mitm,");
		if( fsv & PF_STLS_SSL ) Strins(AVStr(map),"-ss,");
		if( fsv & PF_SSL_IMPLICIT ) Strins(AVStr(map),"--im,");
		if( fsv & PF_STLS_OPT ) Strins(AVStr(map),"-o,");
		scan_CMAP(Conn,map);
		sv1log("STLS -> CMAP=\"%s\"\n",map);
	}
	if( fcl & PF_STLS_DO ){
		withSTLS_FCL++;
		sprintf(map,"%s:FCL:%s",com,cmapb);
		if( fcl & PF_MITM_DO  ) Strins(AVStr(map),"--mitm,");
		if( fcl & PF_STLS_SSL ) Strins(AVStr(map),"-ss,");
		if( fcl & PF_SSL_IMPLICIT ) Strins(AVStr(map),"--im,");
		if( fcl & PF_STLS_OPT ) Strins(AVStr(map),"-o,");
		scan_CMAP(Conn,map);
		sv1log("STLS -> CMAP=\"%s\"\n",map);
	}
}
Example #25
0
static void SftpGW(PCStr(host),int port,int gw){
	int tofrom_sftp[2];
	FILE *fc;
	FILE *tc;
	FILE *ts;
	FILE *fs;
	int rcc;
	CStr(req,1024);
	CStr(com,1024);
	const unsigned char *ucom = (const unsigned char*)com;
	CStr(arg,1024);
	CStr(scom,1024);
	CStr(user,128);
	CStr(passMD5,128);
	CStr(md5,1024);
	CStr(logindir,1024);
	CStr(rnfr,512);
	CStr(res,1024);
	CStr(xcom,1024);
	const char *dp;
	int vsock = -1;
	int dsock = -1;
	CStr(fifo,1024);
	CStr(sresp,0x10000);
	CStr(path,1024);
	CStr(resp1,1024);
	int Ok;
	int Bad;
	int xpid;
	int nready;
	int nfc;
	FILE *fpv[2];
	int rdv[2];
	int ncc = 0;
	int leng;

	FileSize datamax = DATA_MAX;
	IStr(opt1,128);
	if( getMountOpt1(MainConn(),"datamax",AVStr(opt1),sizeof(opt1)) ){
		datamax = kmxatoi(opt1);
		sv1log("## datamax=%s 0x%llX\n",opt1,datamax);
	}

	DEBUG("--SFTPGW start\n");
	fc = fdopen(gw,"r");
	tc = fdopen(gw,"w");
	putresp(tc,220,"SFTP/FTP gateway ready.");
	fflush(tc);
	ts = NULL;
	fs = NULL;

	logindir[0] = 0;
	fpv[0] = fc;
	nfc = 1;
	for(;;){
		nready = fPollIns(0,nfc,fpv,rdv);
		if( nready == 0 && errno == EINTR ){
			DEBUG("--SFTPGW ignored EINTR\n");
			sleep(1);
			continue;
		}
		if( nready <= 0 ){
			break;
		}
		if( 1 < nfc && 0 < rdv[1] ){
			DEBUG("--SFTPGW EOF from server?\n");
			relay_resp(fs,-1,0,AVStr(sresp),"",1);
			break;
		}

		fflush(tc);
		if( fgets(req,sizeof(req),fc) == 0 )
			break;
		dp = wordScan(req,com);
		if( *dp == ' ' ){
			textScan(dp+1,arg);
		}else
		lineScan(dp,arg);
		if( strcaseeq(com,"PASS") )
			DEBUG("--SFTPGW << [%s][****]\n",com);
		else	DEBUG("--SFTPGW << [%s][%s]\n",com,arg);

		if( strcaseeq(com,"QUIT") ){
			putresp(tc,221,"Ok Bye.");
			fclose(fc);
			fclose(tc);
			fc = 0;
			tc = 0;
			if( fs == NULL ){
				DEBUG("--SFTPGW DONE (not started)\n");
				break;
			}
			gw = CC_accept("sftp",host,port,user,fileno(fs));
			if( 0 <= gw ){
				putsftp(ts,"cd .","");
				relay_resp(fs,-1,0,AVStr(sresp),"restart",1);
				if( sresp[0] == 0 ){
					sv1log("##sftp_CC NotAlive\n");
					break;
				}
				fc = fdopen(gw,"r");
				fpv[0] = fc;
				tc = fdopen(gw,"w");
				ncc++;
				DEBUG("--SFTPGW SFTPCC restart #%d\n",ncc);
				putresp(tc,220,"Ok (reusing)");
				continue;
			}
			DEBUG("--SFTPGW DONE\n");
			break;
		}else
		if( strcaseeq(com,"NOOP") ){
			putresp(tc,200,"Ok");
		}else
		if( strcaseeq(com,"USER") ){
			strcpy(user,arg);
			putresp(tc,331,"Send password or passphrase for '%s'",
				arg);
		}else
		if( strcaseeq(com,"PASS") ){
			if( ts != NULL ){
				toMD5(arg,md5);
				DEBUG("--SFTP reusing user[%s]pass[%s][%s]\n",
					user,passMD5,md5);
				if( !streq(md5,passMD5) ){
					putresp(tc,530,"No");
					continue;
				}else	putresp(tc,230,"Ok");
				putsftp(ts,"cd %s",logindir);
				relay_resp(fs,-1,0,AVStr(sresp),"restart",1);
				continue;
			}
			/*
			if( forkSftp(host,port,user,arg,tofrom_sftp) != 0 ){
			*/
			if( forkSftp(host,port,user,arg,tofrom_sftp,AVStr(sresp)) != 0 ){
				IStr(prompt,1024);
				lineScan(sresp,prompt);
				DEBUG("--SFTP login failed\n");
				/*
				putresp(tc,530,"No (Login failed)");
				*/
				putresp(tc,530,"No (Login failed:'%s')",prompt);
if( lGATEWAY() )
sv1log("####@@@@ LOGIN FAILURE\n");
continue; /* to return normal resp. for following commands... */
				break;
			}
			toMD5(arg,passMD5);
			fs = fdopen(tofrom_sftp[0],"r");
			ts = fdopen(tofrom_sftp[1],"w");
			fpv[1] = fs;
			nfc = 2;
			putresp(tc,230,"Ok");

			putsftp(ts,"pwd");
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			/*
			if( strneq(sresp,"Remote working directory: ",26) ){
				CStr(path,1024);
				lineScan(sresp+26,path);
			*/
			if( scanresp(sresp,"Remote working directory:",
			    AVStr(path),sizeof(path)) ){
				strcpy(logindir,path);
			}
		}else
		if( strcaseeq(com,"TYPE") ){
			putresp(tc,200,"Ok");
		}else
		if( strcaseeq(com,"PASV") ){
			PASV(tc,&vsock);
#if 0
			VSAddr ba;
			int balen;
			CStr(mport,128);
			vsock = server_open("SftpGW",VStrNULL,0,1);
			if( 0 <= vsock ){
				balen = sizeof(ba);
				getsockname(vsock,(SAP)&ba,&balen);
#if defined(__CYGWIN__)
				if( VSA_addrisANY(&ba) ){
				    /*connection to 0.0.0.0 fails on CYGWIN?*/
				    VSA_atosa(&ba,VSA_port(&ba),"127.0.0.1");
				}
#endif
				VSA_prftp(&ba,AVStr(mport));
			putresp(tc,227,"Enterning Passive Mode (%s)",mport);
			}else{
				putresp(tc,500,"No");
			}
#endif
		}else
		if( ts == NULL ){
			sv1log("Not Logged In: %s",req);
			putresp(tc,530,"Please login with USER and PASS.");
		}else
		if( strcaseeq(com,"PWD") ){
			putsftp(ts,"pwd");
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			/*
			if( strneq(sresp,"Remote working directory: ",26) ){
				CStr(path,1024);
				lineScan(sresp+26,path);
			*/
			if( scanresp(sresp,"Remote working directory:",
			    AVStr(path),sizeof(path)) ){
				putresp(tc,257,"\"%s\"",path);
			}else{
				putresp(tc,257,"\"/\"");
			}
		}else
		if( strcaseeq(com,"CWD") ){
			putsftp(ts,"cd %s",arg);
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			/*
			if( strneq(sresp,"Couldn't",8)
			 || strneq(sresp,"Can't",4) ){
			*/
			if( linehead(sresp,"Couldn't",0)
			 || linehead(sresp,"Can't",0) ){
				if( strstr(sresp,BadPath) )
					putresp(tc,550,BadPath);
				else
				putresp(tc,550,"No");
			}else	putresp(tc,250,"Ok");
		}else
		/*
		if( strcaseeq(com,"SIZE") ){
			putsftp(ts,"ls -ld %s",arg);
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			if( *sresp == '-' ){
				int sz = 0;
				sscanf(sresp,"%*s %*s %*s %*s %d",&sz);
				putresp(tc,213,"%d",sz);
			}else{
				putresp(tc,550,"Not a plain file");
			}
		}else
		*/
		if( strcaseeq(com,"STOR") ){
			if( vsock < 0 ){
				putresp(tc,500,"No");
				continue;
			}
			dsock = ACCEPT(vsock,1,-1,10);
			if( 0 <= dsock ){
				CStr(tmpf,1024);
				FILE *dfp;
				FILE *tmp;
				/*
				int bytes;
				*/
				FileSize Bytes;
				int isbin;
				double St;

				dfp = fdopen(dsock,"r");
				if( dfp == NULL ){
					putresp(tc,500,"No-1");
					continue;
				}
				tmp = getfile(AVStr(tmpf),"w",0);
				if( tmp == NULL ){
					putresp(tc,500,"No-2");
					fclose(dfp);
					continue;
				}
				putresp(tc,150,"Ok");
				St = Time();
				/*
				bytes = file_copy(dfp,tmp,NULL,DATA_MAX,&isbin);
				DEBUG("--SFTPGW bin=%d,%d bytes upload\n",
					isbin,bytes);
				*/
				Bytes = file_copy(dfp,tmp,NULL,datamax,&isbin);
				DEBUG("--SFTPGW bin=%d,%lld bytes upload\n",
					isbin,Bytes);
				fclose(tmp);
				fclose(dfp);

				DEBUG("--SFTPGW put %s (%lld %lld)\n",tmpf,
					Bytes,File_sizeX(tmpf));
				putsftp(ts,"put %s %s",tmpf,arg);
				/*
				relay_resp(fs,-1,15*1000,AVStr(sresp),com,1);
				*/
				relay_resp(fs,-1,5*1000,AVStr(sresp),com,1);

				if( strneq(sresp,"Uploading ",10)
				 && strstr(sresp,"sftp>") == 0 ){
					waitUploaded(com,AVStr(sresp),fs,fc,tc,
						Time()-St,&vsock);
				}else
				if( strncmp(sresp,"Could",5) == 0 )
					putresp(tc,550,"No");
				else	putresp(tc,226,"Ok");
				unlink(tmpf);
				dsock = -1;
			}else{
				putresp(tc,500,"accept error");
			}
			vsock = -1;
		}else
		if( strcaseeq(com,"RETR") ){
			if( vsock < 0 ){
				putresp(tc,500,"No");
				continue;
			}
			dsock = ACCEPT(vsock,1,-1,10);
			if( arg[0]==0 ||streq(arg,".") ||strtailstr(arg,"/") ){
				putresp(tc,550,"RETR for dir [%s]",arg);
				if( 0 <= dsock ){
					close(dsock);
					dsock = -1;
				}
			}else
			if( 0 <= dsock ){
				CStr(rpath,1024);
				FILE *rfp;
				int pid;

				truncVStr(rpath);
				getfile(AVStr(fifo),NULL,1);
				if( SFTP_WITH_SEEK ){
					/* newer sftp with output seeking */
					sprintf(rpath,"%sr",fifo);
					rfp = fopen(rpath,"w+");
					if( rfp ){
					  pid = Fork("SFTP-DATA");
					  if( pid == 0 ){
						/*
						relayFile2Fifo(rfp,rpath,fifo);
						*/
						relayFile2Fifo(fs,rfp,rpath,fifo);
						_exit(0);
					  }
					  else{
						fclose(rfp); /* 9.9.8 */
					  }
					}
					putsftp(ts,"get %s %s",arg,rpath);
				}else{
				putsftp(ts,"get %s %s",arg,fifo);
				}
				/*
				if( relay_fifo(fs,tc,fifo,dsock,com)==0 )
				*/
				leng = relay_fifo(fs,tc,fifo,dsock,com,AVStr(sresp));
				if( leng <= 0 ){
					sv1log("RETR ERROR: %s\n",sresp);
				}
				if( leng == 0 && strstr(sresp,BadPath) )
					putresp(tc,550,BadPath);
				else
				if( 0 < leng )
					putresp(tc,226,"Ok");
				else	putresp(tc,550,"No");
				relay_resp(fs,-1,1,AVStr(sresp),com,1);
				if( rpath[0] ){
					unlink(rpath);
					xpid = NoHangWait();
					DEBUG("--SFTP-DATA finished, pid=%d\n",
						xpid);
				}
				close(dsock);
				dsock = -1;
				unlink(fifo);
			}else{
				putresp(tc,500,"accept error");
			}
			if( 0 <= vsock ){
				close(vsock); /* 9.9.8 */
			}
			vsock = -1;
		}else
		if( strcaseeq(com,"NLST") || strcaseeq(com,"LIST") ){
			if( vsock < 0 ){
				putresp(tc,500,"No");
				continue;
			}
			dsock = ACCEPT(vsock,1,-1,10);
			if( 0 <= dsock ){
				putresp(tc,150,"Ok");
				if( arg[0] == '-' ){
					char *op;
					for( op = arg+1; *op; ){
						if( strchr(" \t\r\n",*op) )
							break;
						if( strchr("L",*op) ){
							ovstrcpy(op,op+1);
						}else	op++;
					}
				}
				/*
				if( streq(com,"NLST") || strstr(arg,"-l") )
					putsftp(ts,"ls %s",arg);
				else	putsftp(ts,"ls -l %s",arg);
				relay_resp(fs,dsock,0,VStrNULL,com,0);
				*/
				if( streq(com,"NLST") || strstr(arg,"-l") )
					sprintf(scom,"ls %s",arg);
				else	sprintf(scom,"ls -l %s",arg);
				putsftp(ts,"%s",scom);
				relay_list(fs,dsock,scom);
				close(dsock);
				dsock = -1;
				putresp(tc,226,"Ok");
			}else{
				putresp(tc,500,"accept error");
			}
			vsock = -1;
		}else
		if( ucom[0]==0xFF && ucom[1]==0xF4 /* IAC+IP */
		 && ucom[2]==0xF2 /* SYNC */
		 && strcaseeq(com+3,"ABOR") ){
			sv1log("--SFTPGW ABOR\n");
		}else
		if( strcaseeq(com,"RNFR") ){
			strcpy(rnfr,arg);
			putresp(tc,350,"Ok");
		}else
		if( strcaseeq(com,"RNTO") ){
			putsftp(ts,"rename %s %s",rnfr,arg);
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			if( dp = strstr(sresp,"Couldn't") ){
				lineScan(dp,resp1);
				putresp(tc,550,"No %s",resp1);
			}else	putresp(tc,250,"Ok");
		}else
		if( strcaseeq(com,"MKD") || strcaseeq(com,"RMD")
		 || strcaseeq(com,"DELE")
		){ 
			Bad = 550;
			if( strcaseeq(com,"MKD") ){
				Ok = 257;
				putsftp(ts,"mkdir %s",arg);
			}else
			if( strcaseeq(com,"RMD") ){
				Ok = 250;
				putsftp(ts,"rmdir %s",arg);
			}else{
				Ok = 250;
				putsftp(ts,"rm %s",arg);
			}
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			if( dp = strstr(sresp,"Couldn't") ){
				lineScan(dp,resp1);
				putresp(tc,Bad,"No %s",resp1);
			}else	putresp(tc,Ok,"Ok");
		}else
		{
			putresp(tc,502,"No not supported");
		}
	}
	if( fs != NULL && !feof(fs) ){
		putsftp(ts,"quit");
		relay_resp(fs,-1,0,AVStr(sresp),com,1);
	}
	xpid = NoHangWait();
	DEBUG("--SFTPGW finished, pid=%d\n",xpid);
}
Example #26
0
CMaterial& CMaterialManager::LoadMaterial(const VfsPath& pathname)
{
	if(pathname.empty())
		return NullMaterial;

	std::map<VfsPath, CMaterial*>::iterator iter = m_Materials.find(pathname);
	if(iter != m_Materials.end())
	{
		if((*iter).second)
			return *(*iter).second;
	}

	CXeromyces xeroFile;
	if(xeroFile.Load(g_VFS, pathname) != PSRETURN_OK)
		return NullMaterial;

	#define EL(x) int el_##x = xeroFile.GetElementID(#x)
	#define AT(x) int at_##x = xeroFile.GetAttributeID(#x)
	EL(texture);
	EL(alpha);
	AT(usage);
	#undef AT
	#undef EL

	CMaterial *material = NULL;
	try
	{
		XMBElement root = xeroFile.GetRoot();
		XMBElementList childNodes = root.GetChildNodes();
		material = new CMaterial();

		for(int i = 0; i < childNodes.Count; i++)
		{
			XMBElement node = childNodes.Item(i);
			int token = node.GetNodeName();
			XMBAttributeList attrs = node.GetAttributes();
			CStr temp;
			if(token == el_texture)
			{
				CStr value(node.GetText());
				material->SetTexture(value);
			}
			else if(token == el_alpha)
			{
				temp = CStr(attrs.GetNamedItem(at_usage));

				// Determine whether the alpha is used for basic transparency or player color
				if (temp == "playercolor")
					material->SetUsePlayerColor(true);
				else if (temp == "objectcolor")
					material->SetUseTextureColor(true);
				else
					material->SetUsesAlpha(ParseUsage(temp));
			}
		}

		m_Materials[pathname] = material;
	}
	catch(...)
	{
		SAFE_DELETE(material);
		throw;
	}

	return *material;
}
Example #27
0
int authRsh(/*int *bg*/)
{	const char *home;
	CStr(path,1024);
	FILE *fp;
	CStr(paddr,1024);
	CStr(saddr,1024);
	CStr(line,1024);
	CStr(hosts,1024);
	CStr(phost1,1024); /* client's host */
	const char *paddr1;
	CStr(shost1,1024); /* server's host (optional) */
	const char *saddr1;
	int ok;

	if( (home = getenv("HOME")) == NULL ){
		fprintf(stderr,"Permission denied: no $HOME set\n");
		return -1;
	}

	sprintf(path,"%s/%s",home,RHOSTS);
	fp = fopen(path,"r");
	if( fp == NULL ){
		fprintf(stderr,"Permission denied: no %s\n",RHOSTS);
		return 1;
	}

	getpeerAddr(0,AVStr(paddr));
	gethostAddr(0,AVStr(saddr));

	ok = 0;
	while( fgets(line,sizeof(line),fp) ){
		wordScan(line,hosts);
		if( hosts[0] == 0 )
			continue;
		phost1[0] = shost1[0] = 0;
		if( Xsscanf(hosts,"%[^:]:%s",AVStr(phost1),AVStr(shost1)) < 1 )
			continue;

		if( phost1[0] && strcmp(phost1,"*") != 0 ){
			if( (paddr1 = gethostaddr(phost1)) == NULL )
				continue;
			if( strcmp(paddr,paddr1) != 0 )
				continue;
		}
		if( shost1[0] && strcmp(shost1,"*") != 0 ){
			if( (saddr1 = gethostaddr(shost1)) == NULL )
				continue;
			if( strcmp(saddr,saddr1) != 0 )
				continue;
		}
		ok = 1;
		break;
	}
	fclose(fp);
	if( ok ){
		return 0;
	}else{
		fprintf(stderr,"Permission denied: not in %s\n",RHOSTS);
		return -1;
	}
}
Example #28
0
static UDP_Assoc *newUA(Connection *Conn,UDP_Assoc *uav[],PCStr(clhost),int clport,PCStr(svhost),int svport)
{	int ux;
	UDP_Assoc *ua;
	int svsock;
	int rcode;
	CStr(msg,128);
	CStr(lhost,256);
	int lport;
	CStr(local,256);
	CStr(remote,256);
	int SOCKSctl = -1;
	CStr(rh,256);
	int rp;

	rcode = -1;
	if( !permitted(clhost,clport,svhost,svport) )
		return NULL;

	sprintf(local,"*:*");
	sprintf(remote,"%s:%d",svhost,svport);
	Conn->from_cached = 1;
	VA_setClientAddr(Conn,clhost,clport,0);
	Conn->no_dstcheck_proto = serviceport("tcprelay");
	initConnect(Conn);
	setupConnect(Conn);

	ServerFlags |= PF_UDP;
	Conn->sv.p_SOCKSCTL = -1;
	svsock = connectViaSocks(Conn,svhost,svport,AVStr(rh),&rp);
	if( 0 <= svsock ){
		sv1log("via SOCKS UDP:%d@%s CTL:%d\n",svsock,
			Conn->sv.p_SOCKSADDR,Conn->sv.p_SOCKSCTL);
		SOCKSctl = Conn->sv.p_SOCKSCTL;
		goto ADDUA;
	}

	svsock = VSocket(Conn,"CNCT/UDPRELAY",-1,AVStr(local),AVStr(remote),"");
	if( 0 <= svsock ){
/*
		setNonblockingIO("UDPRELAY-SV",svsock,1);
*/
		SetNonblockingIO("UDPRELAY-SV",svsock,1);
		goto ADDUA;
	}

	strcpy(lhost,"*");
	lport = 0;
	SRCIFfor(Conn,"udprelay",svhost,svport,AVStr(lhost),&lport);
	if( strcmp(lhost,"*") == 0 )
		lhost[0] = 0;

	svsock = server_open("UDPRELAY",AVStr(lhost),lport,-1);
	if( svsock < 0 ){
		if( uav[0] == 0 ){
			return NULL;
		}
		ux = longestIdle(uav);
		sv1log("push out longest idle 1 [%d]\n",ux);
		delUA(uav,ux,"NoMoreSocket",1);
		svsock = server_open("UDPRELAY",AVStr(lhost),lport,-1);
		if( svsock < 0 )
			return NULL;
	}

	if( UDPRELAY_RPORT_FIX ){
	rcode = __connectServer(svsock,"UDPRELAY","udprelay",svhost,svport /*,1*/);
	if( rcode < 0 ){
		sv1log("UDPRELAY: connect(%d) error %d\n",svsock,rcode);
		close(svsock);
		return NULL;
	}
	}

ADDUA:
	for( ux = 0; uav[ux]; ux++ )
		;
	if( UDPRELAY_MAXASSOC <= ux ){
		ux = longestIdle(uav);
		sv1log("push out longest idle 2 [%d]\n",ux);
		delUA(uav,ux,"NoMoreClient",0);
	}

	ua = (UDP_Assoc*)calloc(1,sizeof(UDP_Assoc));
	ua->ua_id = ++uaid;
	ua->ua_ctime = time(0);
	ua->ua_clhost = stralloc(clhost);
	ua->ua_clport = clport;
	ua->ua_svsock = svsock;
	ua->ua_svbound = (0 < peerPort(svsock));
	ua->ua_svtcp = !isUDPsock(svsock);
	ua->ua_svhost = stralloc(svhost);
	ua->ua_svport = svport;
	ua->ua_svSOCKS = SOCKSctl;
	VSA_aptosa(&ua->ua_SOCKSADDR,Conn->sv.p_SOCKSADDR);
	uav[ux] = ua;

	msghead(AVStr(msg),"start",ua,ux);
	sv1log("%s > %s:%d\n",msg,svhost,svport);
	return ua;
}
Example #29
0
static int do_bind(int sock,PVStr(lport),PCStr(opts),int *sharedp,PVStr(sockname),int toC)
{	int svsock;
	CStr(host,MaxHostNameLen);
	CStr(ports,256);
	int port;
	int nlisten;
	int wcc;
	int sockid;

	*sharedp = 0;
	host[0] = 0;
	ports[0] = 0;
	port = 0;
	nlisten = 0;

	if( lport[0] == '/' ){
		svsock = server_open_un("vsap",AVStr(lport),1);
		daemonlog("E","## SVPORT %s [%d]\n",lport,svsock);
		if( svsock < 0 ){
		wcc = SockPrintf(toC,"%s %d not bound-1\r\n",VER,NO_BIND);
		return -1;
		}
		strcpy(sockname,lport);
		*sharedp = 1;
		goto BOUND;
	}

	if( strchr(lport,':') )
		Xsscanf(lport,"%[^:]:%s",AVStr(host),AVStr(ports));
	else	Xsscanf(lport,"%s",AVStr(ports));
	port = atoi(ports);

	if( strncmp(opts,"-l=",3) == 0 )
		nlisten = atoi(opts+3);

	daemonlog("D","bind: %s:%d nlisten=%d\n",host,port,nlisten);

	if( 0 <= (svsock = ServSockOf(host,port)) ){
		daemonlog("D","## SVPORT %d\n",svsock);
		*sharedp = 1;
	}else
	if( 0 <= (svsock = ReservedPortSock(host,port)) ){
		daemonlog("D","## RESV_PORT %d\n",svsock);
		*sharedp = 1;
	}else
	if( lSINGLEP()
	 && 0 <= (svsock = findopen_port("VSAP",AVStr(host),port,nlisten)) ){
		daemonlog("D","## SHARED_PORT %d\n",svsock);
		*sharedp = 1;
	}else
	if( 0 <= (svsock = NewPort(lport,AVStr(host),port,toC,nlisten)) ){
		daemonlog("D","## NEW_PORT %d\n",svsock);
		*sharedp = 0;
	}else{
		wcc = SockPrintf(toC,"%s %d not bound-2 %s\r\n",VER,NO_BIND,
			lport);
		return -1;
	}
	gethostName(svsock,AVStr(sockname),"%A:%P");

BOUND:
	sockid = add_svsock(svsock);
	wcc = SockPrintf(toC,"%s %d %d %s bound.\r\n",VER,OK_BIND,
		sockid,sockname);
	return svsock;
}
Example #30
0
CTextureConverter::SettingsFile* CTextureConverter::LoadSettings(const VfsPath& path) const
{
    CXeromyces XeroFile;
    if (XeroFile.Load(m_VFS, path) != PSRETURN_OK)
        return NULL;

    // Define all the elements used in the XML file
#define EL(x) int el_##x = XeroFile.GetElementID(#x)
#define AT(x) int at_##x = XeroFile.GetAttributeID(#x)
    EL(textures);
    EL(file);
    AT(pattern);
    AT(format);
    AT(mipmap);
    AT(normal);
    AT(alpha);
    AT(filter);
    AT(kaiserwidth);
    AT(kaiseralpha);
    AT(kaiserstretch);
#undef AT
#undef EL

    XMBElement root = XeroFile.GetRoot();

    if (root.GetNodeName() != el_textures)
    {
        LOGERROR("Invalid texture settings file \"%s\" (unrecognised root element)", path.string8());
        return NULL;
    }

    std::unique_ptr<SettingsFile> settings(new SettingsFile());

    XERO_ITER_EL(root, child)
    {
        if (child.GetNodeName() == el_file)
        {
            Match p;

            XERO_ITER_ATTR(child, attr)
            {
                if (attr.Name == at_pattern)
                {
                    p.pattern = attr.Value.FromUTF8();
                }
                else if (attr.Name == at_format)
                {
                    CStr v(attr.Value);
                    if (v == "dxt1")
                        p.settings.format = FMT_DXT1;
                    else if (v == "dxt3")
                        p.settings.format = FMT_DXT3;
                    else if (v == "dxt5")
                        p.settings.format = FMT_DXT5;
                    else if (v == "rgba")
                        p.settings.format = FMT_RGBA;
                    else if (v == "alpha")
                        p.settings.format = FMT_ALPHA;
                    else
                        LOGERROR("Invalid attribute value <file format='%s'>", v.c_str());
                }
                else if (attr.Name == at_mipmap)
                {
                    CStr v(attr.Value);
                    if (v == "true")
                        p.settings.mipmap = MIP_TRUE;
                    else if (v == "false")
                        p.settings.mipmap = MIP_FALSE;
                    else
                        LOGERROR("Invalid attribute value <file mipmap='%s'>", v.c_str());
                }
                else if (attr.Name == at_normal)
                {
                    CStr v(attr.Value);
                    if (v == "true")
                        p.settings.normal = NORMAL_TRUE;
                    else if (v == "false")
                        p.settings.normal = NORMAL_FALSE;
                    else
                        LOGERROR("Invalid attribute value <file normal='%s'>", v.c_str());
                }
                else if (attr.Name == at_alpha)
                {
                    CStr v(attr.Value);
                    if (v == "none")
                        p.settings.alpha = ALPHA_NONE;
                    else if (v == "player")
                        p.settings.alpha = ALPHA_PLAYER;
                    else if (v == "transparency")
                        p.settings.alpha = ALPHA_TRANSPARENCY;
                    else
                        LOGERROR("Invalid attribute value <file alpha='%s'>", v.c_str());
                }
                else if (attr.Name == at_filter)
                {
                    CStr v(attr.Value);
                    if (v == "box")
                        p.settings.filter = FILTER_BOX;
                    else if (v == "triangle")
                        p.settings.filter = FILTER_TRIANGLE;
                    else if (v == "kaiser")
                        p.settings.filter = FILTER_KAISER;
                    else
                        LOGERROR("Invalid attribute value <file filter='%s'>", v.c_str());
                }
                else if (attr.Name == at_kaiserwidth)
                {
                    p.settings.kaiserWidth = CStr(attr.Value).ToFloat();
                }
                else if (attr.Name == at_kaiseralpha)
                {
                    p.settings.kaiserAlpha = CStr(attr.Value).ToFloat();
                }
                else if (attr.Name == at_kaiserstretch)
                {
                    p.settings.kaiserStretch = CStr(attr.Value).ToFloat();
                }
                else
                {
                    LOGERROR("Invalid attribute name <file %s='...'>", XeroFile.GetAttributeString(attr.Name).c_str());
                }
            }

            settings->patterns.push_back(p);
        }
    }