Exemplo n.º 1
0
/* GetDBTape
 *      Load a DB tape, read and over write its label.
 *      Leave the tape mounted.
 */
afs_int32
GetDBTape(afs_int32 taskId, Date expires, struct butm_tapeInfo *tapeInfoPtr,
	  afs_uint32 dumpid, afs_int32 sequence, int queryFlag,
	  int *wroteLabel)
{
    afs_int32 code = 0;
    int interactiveFlag;
    char tapeName[BU_MAXTAPELEN];
    char strlevel[5];
    struct timeval tp;
    struct timezone tzp;
    afs_int32 curTime;
    int tapecount = 1;

    struct butm_tapeLabel oldTapeLabel, newLabel;
    struct tapeEntryList *endList;

    /* construct the name of the tape */
    sprintf(tapeName, "%s.%-d", DUMP_TAPE_NAME, sequence);

    interactiveFlag = queryFlag;
    *wroteLabel = 0;

    while (!*wroteLabel) {	/*w */
	if (interactiveFlag) {	/* need a tape to write */
	    code =
		PromptForTape(SAVEDBOPCODE, tapeName, dumpid, taskId,
			      tapecount);
	    if (code)
		ERROR_EXIT(code);
	}
	interactiveFlag = 1;
	tapecount++;

	code = butm_Mount(tapeInfoPtr, tapeName);
	if (code) {
	    TapeLog(0, taskId, code, tapeInfoPtr->error, "Can't open tape\n");
	    goto getNewTape;
	}

	memset(&oldTapeLabel, 0, sizeof(oldTapeLabel));
	code = butm_ReadLabel(tapeInfoPtr, &oldTapeLabel, 1);	/* rewind tape */
	if (code) {
	    oldTapeLabel.useCount = 0;	/* no label exists */
	    oldTapeLabel.structVersion = 0;
	    strcpy(oldTapeLabel.pName, "");
	} else {
	    /* If tape has a name, it must be null or database tape name */
	    if (dump_namecheck && strcmp(oldTapeLabel.AFSName, "")
		&& !databaseTape(oldTapeLabel.AFSName)) {
		char gotName[BU_MAXTAPELEN + 32];

		LABELNAME(gotName, &oldTapeLabel);
		TLog(taskId,
		     "This tape %s must be a database tape or NULL tape\n",
		     gotName);

	      getNewTape:
		unmountTape(taskId, tapeInfoPtr);
		continue;
	    }

	    /* Do not overwrite a tape that belongs to this dump */
	    if (oldTapeLabel.dumpid && (oldTapeLabel.dumpid == dumpid)) {
		ErrorLog(0, taskId, 0, 0,
			 "Can't overwrite tape containing the dump in progress\n");
		goto getNewTape;
	    }

	    /* On first tape, the savedb has not started yet, so the database is not locked
	     * and we can therefore, access information from it. This is easier to do because
	     * database dumps don't have appended dumps (nor appended).
	     */
	    if (sequence == 1) {
		afs_uint32 dmp;
		struct budb_dumpEntry de, de2;

		/* Verify the tape has not expired
		 * Early database dumps don't have a dumpid
		 */
		if (!tapeExpired(&oldTapeLabel)) {
		    TLog(taskId, "This tape has not expired\n");
		    goto getNewTape;
		}

		/* Since the dumpset on this tape will be deleted from database, check if
		 * any of the dumps in this dumpset are most-recent-dumps.
		 */
		for (dmp = oldTapeLabel.dumpid; dmp; dmp = de.appendedDumpID) {
		    if (dmp == lastDump.id) {
			memcpy(&de, &lastDump, sizeof(de));
			memcpy(&de2, &lastDump, sizeof(de2));
		    } else {
			code = bcdb_FindDumpByID(dmp, &de);
			if (code)
			    break;
			sprintf(strlevel, "%d", de.level);
			code =
			    bcdb_FindLatestDump(de.volumeSetName, strlevel,
						&de2);
			if (code)
			    continue;
		    }

		    if (de.id == de2.id) {
			if (strcmp(DUMP_TAPE_NAME, de2.name) == 0) {
			    ErrorLog(0, taskId, 0, 0,
				     "Warning: Overwriting most recent dump %s (DumpID %u)\n",
				     de.name, de.id);
			} else {
			    ErrorLog(0, taskId, 0, 0,
				     "Warning: Overwriting most recent dump of the '%s' volumeset: %s (DumpID %u)\n",
				     de.volumeSetName, de.name, de.id);
			}
		    }
		}
	    }

	    /* Otherwise, the savedb is in progress and we can't
	     * access the database (it's locked). So we rely on the
	     * information available (and not the backup database).
	     */
	    else {
		/* Check the tape's expiration date. Use the expiration on the label */
		gettimeofday(&tp, &tzp);
		curTime = tp.tv_sec;
		if (curTime < oldTapeLabel.expirationDate) {
		    TLog(taskId, "This tape has not expired\n");
		    goto getNewTape;
		}

		/* Check if this previous-dump of the dump-in-progress is on this tape */
		if (oldTapeLabel.dumpid
		    && (oldTapeLabel.dumpid == lastDump.id)) {
		    ErrorLog(0, taskId, 0, 0,
			     "Warning: Overwriting most recent dump %s (DumpID %u)\n",
			     lastDump.name, lastDump.id);
		}

	    }
	}

	GetNewLabel(tapeInfoPtr, oldTapeLabel.pName, tapeName, &newLabel);
	newLabel.expirationDate = expires;
	newLabel.useCount = oldTapeLabel.useCount + 1;
	newLabel.dumpid = dumpid;
	newLabel.size = tapeInfoPtr->tapeSize;

	code = butm_Create(tapeInfoPtr, &newLabel, 1);	/* rewind tape */
	if (code) {
	    TapeLog(0, taskId, code, tapeInfoPtr->error,
		    "Can't label tape\n");
	    goto getNewTape;
	}

	*wroteLabel = 1;

	/* Initialize a tapeEntry for later inclusion into the database */
	listEntryPtr =
	    (struct tapeEntryList *)malloc(sizeof(struct tapeEntryList));
	if (!listEntryPtr)
	    ERROR_EXIT(TC_NOMEMORY);
	memset(listEntryPtr, 0, sizeof(struct tapeEntryList));

	/* Remember dumpid so we can delete it later */
	if ((oldTapeLabel.structVersion >= TAPE_VERSION_3)
	    && oldTapeLabel.dumpid)
	    listEntryPtr->oldDumpId = oldTapeLabel.dumpid;

	/* Fill in tape entry so we can save it later */
	strcpy(tapeEntryPtr->name, TNAME(&newLabel));
	tapeEntryPtr->flags = BUDB_TAPE_BEINGWRITTEN;
	tapeEntryPtr->written = newLabel.creationTime;
	tapeEntryPtr->expires = expires;
	tapeEntryPtr->seq = sequence;
	tapeEntryPtr->useCount = oldTapeLabel.useCount + 1;
	tapeEntryPtr->dump = dumpid;
	tapeEntryPtr->useKBytes = 0;
	tapeEntryPtr->labelpos = 0;

	/* Thread onto end of single-linked list */
	if (listEntryHead) {
	    endList = listEntryHead;
	    while (endList->next)
		endList = endList->next;
	    endList->next = listEntryPtr;
	} else
	    listEntryHead = listEntryPtr;
    }				/*w */

  error_exit:
    return (code);
}
Exemplo n.º 2
0
int worker( struct TcpdaemonEntryParam *pep , struct TcpdaemonServerEnv *pse )
{
	struct sembuf		sb ;
	fd_set			readfds ;
	
	struct sockaddr		accept_addr ;
	socklen_t		accept_addrlen ;
	int			accept_sock ;
	
	int			nret = 0 ;
	
	while(1)
	{
		DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | waiting for entering accept mutex\n" , pse->index );
		
		/* 进入临界区 */
		memset( & sb , 0x00 , sizeof(struct sembuf) );
		sb.sem_num = 0 ;
		sb.sem_op = -1 ;
		sb.sem_flg = SEM_UNDO ;
		nret = semop( pse->accept_mutex , & sb , 1 ) ;
		if( nret == -1 )
		{
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | enter accept mutex failed , errno[%d]\n" , pse->index , errno );
			return -1;
		}
		else
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | enter accept mutex ok\n" , pse->index );
		}
		
		/* 监控侦听socket或存活管道事件 */
		FD_ZERO( & readfds );
		FD_SET( pse->listen_sock , & readfds );
		FD_SET( pse->alive_pipe->fd[0] , & readfds );
		nret = select( MAX_INT(pse->listen_sock,pse->alive_pipe->fd[0])+1 , & readfds , NULL , NULL , NULL ) ;
		if( nret == -1 )
		{	
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | select failed , errno[%d]\n" , pse->index , errno );
			break;
		}
		
		if( FD_ISSET( pse->alive_pipe->fd[0] , & readfds ) )
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | alive_pipe received quit command\n" , pse->index );
			break;
		}
		
		/* 接受新客户端连接 */
		accept_addrlen = sizeof(struct sockaddr) ;
		memset( & accept_addr , 0x00 , accept_addrlen );
		accept_sock = accept( pse->listen_sock , & accept_addr , & accept_addrlen ) ;
		if( accept_sock == -1 )
		{
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | accept failed , errno[%d]\n" , pse->index , errno );
			break;
		}
		else
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | accept ok , [%d]accept[%d]\n" , pse->index , pse->listen_sock , accept_sock );
		}
		
		if( pep->tcp_nodelay > 0 )
		{
			setsockopt( accept_sock , IPPROTO_TCP , TCP_NODELAY , (void*) & (pep->tcp_nodelay) , sizeof(int) );
		}
		
		if( pep->tcp_linger > 0 )
		{
			struct linger	lg ;
			lg.l_onoff = 1 ;
			lg.l_linger = pep->tcp_linger - 1 ;
			setsockopt( accept_sock , SOL_SOCKET , SO_LINGER , (void *) & lg , sizeof(struct linger) );
		}
		
		/* 离开临界区 */
		memset( & sb , 0x00 , sizeof(struct sembuf) );
		sb.sem_num = 0 ;
		sb.sem_op = 1 ;
		sb.sem_flg = SEM_UNDO ;
		nret = semop( pse->accept_mutex , & sb , 1 ) ;
		if( nret == -1 )
		{
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | leave accept mutex failed , errno[%d]\n" , pse->index , errno );
			return -1;
		}
		else
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | leave accept mutex ok\n" , pse->index );
		}
		
		/* 调用通讯数据协议及应用处理回调函数 */
		DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | 调用tcpmain\n" , pse->index );
		nret = pse->pfunc_tcpmain( pep->param_tcpmain , accept_sock , & accept_addr ) ;
		if( nret < 0 )
		{
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | tcpmain return[%d]\n" , pse->index , nret );
			return -1;
		}
		else if( nret > 0 )
		{
			WarnLog( __FILE__ , __LINE__ , "WORKER(%ld) | tcpmain return[%d]\n" , pse->index , nret );
		}
		else
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | tcpmain return[%d]\n" , pse->index , nret );
		}
		
		/* 关闭客户端连接 */
		close( accept_sock );
		DebugLog( __FILE__ , __LINE__ , "close[%d]\n" , accept_sock );
		
		/* 检查工作进程处理数量 */
		pse->requests_per_process++;
		if( pep->max_requests_per_process != 0 && pse->requests_per_process >= pep->max_requests_per_process )
		{
			InfoLog( __FILE__ , __LINE__ , "WORKER(%ld) | maximum number of processing[%ld][%ld] , ending\n" , pse->index , pse->requests_per_process , pep->max_requests_per_process );
			return -1;
		}
	}
	
	/* 最终离开临界区 */
	memset( & sb , 0x00 , sizeof(struct sembuf) );
	sb.sem_num = 0 ;
	sb.sem_op = 1 ;
	sb.sem_flg = SEM_UNDO ;
	nret = semop( pse->accept_mutex , & sb , 1 ) ;
	if( nret == -1 )
	{
		InfoLog( __FILE__ , __LINE__ , "WORKER(%ld) | leave accept mutex finally failed , errno[%d]\n" , pse->index , errno );
		return -1;
	}
	else
	{
		DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | leave accept mutex finally ok\n" , pse->index );
	}
	
	return 0;
}
Exemplo n.º 3
0
bool GameDBChannel::SelectUser(int64_t userNo, UserInfo* userInfo)
{
	char query[256] = { 0, };

	sprintf(query,
		SELECT_USER_QUERY,
		userNo);

	MYSQL_RES* resultSet = NULL;
	_dbConn.ProcessResultQuery(query, &resultSet);

	bool isExists = false;

	if (resultSet)
	{
		MYSQL_ROW row;

		while ((row = mysql_fetch_row(resultSet)) != NULL)
		{
			mysql_field_seek(resultSet, 0);

			if (mysql_num_fields(resultSet) != USER_FIELD_COUNT)
			{
				ErrorLog("the retrieved field is incorrect, fields:%d", mysql_num_fields(resultSet));
				mysql_free_result(resultSet);
				return false;
			}
            
            memset(userInfo, 0, sizeof(UserInfo));
            
            if (row[USER_USER_NO]) userInfo->userNo = atoll(row[USER_USER_NO]);
            if (row[USER_NICK_NAME])
            {
                strcpy(userInfo->nickName, row[USER_NICK_NAME]);
                userInfo->nickNameLen = strlen(row[USER_NICK_NAME]);
            }
			if (row[USER_COMMON_WIN]) userInfo->commonWin = atoi(row[USER_COMMON_WIN]);
			if (row[USER_COMMON_LOSE]) userInfo->commonLose = atoi(row[USER_COMMON_LOSE]);
			if (row[USER_COMMON_DISS]) userInfo->commonDiss = atoi(row[USER_COMMON_DISS]);
			if (row[USER_RANK_WIN]) userInfo->rankWin = atoi(row[USER_RANK_WIN]);
			if (row[USER_RANK_LOSE]) userInfo->rankLose = atoi(row[USER_RANK_LOSE]);
			if (row[USER_RANK_DISS]) userInfo->rankDiss = atoi(row[USER_RANK_DISS]);
			if (row[USER_GRADE]) userInfo->grade = atoi(row[USER_GRADE]);
			if (row[USER_GRADE_REACHED_COUNT]) userInfo->gradeReachedCount = atoi(row[USER_GRADE_REACHED_COUNT]);
			if (row[USER_POINT]) userInfo->point = atoi(row[USER_POINT]);
			if (row[USER_COIN]) userInfo->coin = atoi(row[USER_COIN]);
            if (row[USER_CLAN_NO]) userInfo->clanNo = atoi(row[USER_CLAN_NO]);
            if (row[USER_CLAN_CLASS]) userInfo->clanClass = atoi(row[USER_CLAN_CLASS]);
            
//          if (row[USER_CREATED_TIME]) userInfo->createTime = atoi(row[USER_CREATED_TIME]);
//			if (row[USER_LAST_LOGIN_TIME]) userInfo->lastLoginTime = atoi(row[USER_LAST_LOGIN_TIME]);
//			if (row[USER_LAST_LOGOUT_TIME]) userInfo->lastLogoutTime = atoi(row[USER_LAST_LOGOUT_TIME]);

			isExists = true;
		}

		mysql_free_result(resultSet);
	}

	if (false == isExists)
	{
		ErrorLog("the user do not exist, userNo = %lld", userNo);
		return false;
	}

	return true;
}
Exemplo n.º 4
0
int main(int argc, char **argv)
{
	DWORD dwRet;
	dwRet = InitLog(E_LOG_CONSOLE);
	//dwRet = InitLog(E_LOG_FILE);

	if (argc < 2) {
		DebugLog("[Usage] : Server Port, Server DB Queue [Default 4]");
		return E_RET_FAIL;
	}

	DebugLog("******************************************");
	DebugLog("******* Broker Giver Server Init *********");
	DebugLog("******************************************");

	/*
		you have to configure argument for server
		argv[1] : Port
		argv[2] : Backlog
	*/
	std::string strPort, strDBQueue;
	DWORD dwPort, dwDBQueue;
	strPort = argv[1];
	dwPort = ::atoi(strPort.c_str());

	if (argc == 2) {
#define DEFAULT_QUEUE_SIZE 4
		dwDBQueue = DEFAULT_QUEUE_SIZE;
	}
	else {
		strDBQueue = argv[2];
		dwDBQueue = ::atoi(strDBQueue.c_str());
	}

	CBGServer *BGServer = NULL;
	BGServer = new CBGServer();
	if (!BGServer) {
		ErrorLog("Fail to get memory of AYServer");
		return E_RET_FAIL;
	}

	DebugLog("******************************************");
	DebugLog("****** Broker Giver Server Start *********");
	DebugLog("******************************************");

	try
	{
		dwRet = BGServer->StartServer(dwPort, dwDBQueue);
		if (dwRet != E_RET_SUCCESS) {
			throw std::exception("Fail to start server");
		}
	}
	catch (std::exception &e)
	{
		ErrorLog("******************************************");
		ErrorLog("****** Broker Giver Server Exit  *********");
		ErrorLog("******************************************");
		ErrorLog("%s", e.what());

		if (BGServer)
			delete BGServer;

		DeleteCriticalSection(&CriticalSection);
		return E_RET_FAIL;
	}

	DebugLog("******************************************");
	DebugLog("****** Broker Giver Server Exit  *********");
	DebugLog("******************************************");

	if (BGServer)
		delete BGServer;

	DeleteCriticalSection(&CriticalSection);
	return E_RET_SUCCESS;
}
Exemplo n.º 5
0
void FX_CCharManager::GenerateCharacterAffect	(	Fx_CHARACTER_t *pNewChar, int affectNum, int affectIdx[] )
{
	if	(	! pNewChar	)
	{
		ErrorLog( "NULL pointer inputed" );
		return;
	}
	if	(	affectNum	>	MAX_NUM_STATIC_EFFECT	)
	{
		ErrorLog( "affactNum<%d> exceeds MAX_NUM_STATIC_EFFECT. ignore all effect", affectNum );
		pNewChar->ren_numStaticEffects	=	0;
		memset( pNewChar->ren_staticEffectEntityIndex, 0, sizeof(pNewChar->ren_staticEffectEntityIndex) );
		memset( pNewChar->ren_staticEffectIndex, 0, sizeof(pNewChar->ren_staticEffectIndex) );
		memset( pNewChar->ren_staticEffectLevel, 0, sizeof(pNewChar->ren_staticEffectLevel) );
		return;
	}
	if	(	affectNum	<	0	)
	{
		ErrorLog( "affactNum<%d> has minus value", affectNum );
		pNewChar->ren_numStaticEffects	=	0;
		memset( pNewChar->ren_staticEffectEntityIndex, 0, sizeof(pNewChar->ren_staticEffectEntityIndex) );
		memset( pNewChar->ren_staticEffectIndex, 0, sizeof(pNewChar->ren_staticEffectIndex) );
		memset( pNewChar->ren_staticEffectLevel, 0, sizeof(pNewChar->ren_staticEffectLevel) );
		return;
	}

	 
	 
		 
	int		tempNumStaticEffects	=	0;
	int		tempStaticEffectsIndex [MAX_NUM_STATIC_EFFECT];
	int		tempStaticEffectsLevel [MAX_NUM_STATIC_EFFECT];
	int		tempStaticEffectsEntityIndex [MAX_NUM_STATIC_EFFECT];
	
	 
	 
	bool	flagProcessed [MAX_NUM_STATIC_EFFECT];
				 
	for	(	int	index	=	0;	\
			index	<	MAX_NUM_STATIC_EFFECT;	\
			++index		)
	{
		flagProcessed [index]	=	false;
	}
	
		 
	if	(	(	pNewChar->ren_numStaticEffects	<	0	)	||
			(	pNewChar->ren_numStaticEffects	>=	MAX_NUM_STATIC_EFFECT	)	)
	{
		ErrorLog( "entityType : %d, name : %s, ren_numStaticEffects : %d", pNewChar->entityType, pNewChar->name, pNewChar->ren_numStaticEffects );
		pNewChar->ren_numStaticEffects	=	0;
	}
	
	int	newEffectCount	=	affectNum;
	for	(	index	=	0;	\
			index	<	pNewChar ->ren_numStaticEffects;	\
			++index	)
	{
		int	effectIndex	=	pNewChar ->ren_staticEffectIndex [index];
		int	effectLevel	=	pNewChar ->ren_staticEffectLevel [index];
		int	effectEntityIndex	=	pNewChar ->ren_staticEffectEntityIndex [index];

		if	(	effectEntityIndex	<	0 || effectEntityIndex >= MAX_SIZE_EFFECT_ENTITY )	
		{
			ErrorLog( "effectEntityIndex is invalid(%d)", effectEntityIndex );
			continue;
		}

		if	(	effectLevel	<	0	)
			effectLevel	=	0;
		
		 
		bool	found	=	false;
		int		newEffectIndex;
		for	(	int	subindex	=	0;	\
					subindex	<	newEffectCount;	\
					++subindex	)
		{
			if	(	effectIndex	==	affectIdx [subindex]	)
			{
				newEffectIndex	=	subindex;
				found	=	true;
				break;
			}
		}

		if	(	found	)
		{
			 
			tempStaticEffectsIndex [tempNumStaticEffects]	=	effectIndex;
			tempStaticEffectsLevel [tempNumStaticEffects]	=	effectLevel;
			tempStaticEffectsEntityIndex [tempNumStaticEffects]	=	effectEntityIndex;
			++tempNumStaticEffects;
			
			 
			effectentity_t	*entity;
			entity	=	&g_effectMng ->m_entities [effectEntityIndex];
			mdleffectentity_t	*mdlEntity;
			mdlEntity	=	&g_effectMng ->m_MDLMng ->m_MDLEffectEntities [entity ->idxMDLEntity];
			mdlEntity ->attackerIdx	=	pNewChar ->idxOnServer;
			
			 
			flagProcessed [newEffectIndex]	=	true;
			
			continue;
		}
		
		 
		if	(	g_effectMng->m_entityInUse[ effectEntityIndex ]	)
		{
			 
			g_effectMng ->Delete ( effectEntityIndex );
		}
	}
	
				 
	if	(	tempNumStaticEffects	>	0	)
	{
		memcpy ( pNewChar ->ren_staticEffectIndex, tempStaticEffectsIndex, sizeof (int) * tempNumStaticEffects );
		memcpy ( pNewChar ->ren_staticEffectLevel, tempStaticEffectsLevel, sizeof (int) * tempNumStaticEffects );
		memcpy ( pNewChar ->ren_staticEffectEntityIndex, tempStaticEffectsEntityIndex, sizeof (int) * tempNumStaticEffects );
	}
	
		 
	
	
	CSkillEffect *pEffect;
	for	(	index	=	0;	\
			index	<	newEffectCount;	\
			++index		)
	{
		if	(	tempNumStaticEffects	>=	MAX_NUM_STATIC_EFFECT	)
		{
			ErrorLog( "entitytype : %d, name : %s, effectnum exceeded maxinum value : %d", pNewChar->entityType, pNewChar->name, tempNumStaticEffects );
			ErrorLog( "index : %d, newEffectCount : %d", index, newEffectCount );
			break;
		}

		 
		if	(	flagProcessed [index]	)	continue;

		 
		bool	found	=	false;
		for	(	int	subindex	=	0;	\
					subindex	<	tempNumStaticEffects;	\
					++subindex	)
		{
			if	(	affectIdx [index]	==	tempStaticEffectsIndex [subindex]	)
			{
				found	=	true;
				break;
			}
		}
		if	(	found	)	continue;
		
		 
		int		skillIndex	=	affectIdx [index];
		if	(	skillIndex	<	0	)
		{
			ErrorLog( "서버에서 minus 값을 가지는 skill index 날아왔음. %d", skillIndex );
			continue;
		}

		int		skillLevel	=	0;
		 
		pNewChar ->ren_staticEffectIndex [tempNumStaticEffects]	=	skillIndex;
		pNewChar ->ren_staticEffectLevel [tempNumStaticEffects]	=	skillLevel;
		
		
		CSkilTable *pSkillTable = g_SkillTableDB.FindDB(skillIndex);
		if(pSkillTable == NULL) continue;
		
		pEffect		= pSkillTable->GetSkillEffect();
		if(pEffect == NULL) continue;

		if	(	! pEffect->m_nIsSubEffect)	continue;
		if	(	pEffect->m_nSubEffectID	<	0	)
		{
			ErrorLog( "skillindex<%d> 의 subeffect index<%d> 가 잘못되었음", skillIndex, pEffect->m_nSubEffectID	);
			continue;
		}
		pNewChar ->ren_staticEffectEntityIndex [tempNumStaticEffects]
			=	g_effectMng ->AddSelfEffect (	GTH_EFFECT_CLASS_MODEL, 
												pEffect->m_nSubEffectID,
												pNewChar ->position,
												g_SkillLogic.GTH_GetSkillEffectLevel ( skillIndex, skillLevel ),
												true,
												pNewChar ->entityType,		
												pNewChar ->idxOnServer );	
		
		if	(	pNewChar ->ren_staticEffectEntityIndex [tempNumStaticEffects]	<	0	)
		{
			
			continue;
		}
		else
		{
			
			++tempNumStaticEffects;
		}
		

		
	}

	
	pNewChar ->ren_numStaticEffects	=	tempNumStaticEffects;

	return;
}
void InitMediaMananger()
{
	InitializeCriticalSection(&g_locker);

	HKEY hKey;
	LONG lRet;

	lRet = RegOpenKeyEx(HKEY_CURRENT_USER, REG_PATH, 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &hKey );
	if (lRet == ERROR_FILE_NOT_FOUND)
	{
		return ;
	}

	if( lRet != ERROR_SUCCESS )
	{
		WarnLog("Faild(%d) to RegOpenKeyEx\n", lRet);
		return ;
	}

	for(int i = 0; ; i++)
	{
		wchar_t achGuid[256];
		DWORD cchGuid = 256;
		struct MediaInfo info;

		if (RegEnumValue(hKey, i, achGuid, &cchGuid, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) break;

		DWORD cbData = REG_SIZE;
		DWORD dwType = REG_BINARY;
		lRet = RegQueryValueEx(hKey, achGuid, 0, &dwType, (LPBYTE)(&info), &cbData);
		if ((lRet != ERROR_SUCCESS ) || (dwType != REG_BINARY) || (cbData != REG_SIZE))
		{
			ErrorLog("Faild(%d) to RegQueryValueEx\n", lRet);
			RegDeleteValue(hKey, achGuid);
			continue;
		}

		if (CheckMediaInfo(&info) == FALSE)
		{
			lRet = RegDeleteValue(hKey, achGuid);
			continue;
		}

		g_media_list = (MediaInfo **)MemoryRealloc(g_media_list, (g_media_info_count + 1) * sizeof(MediaInfo*));
		g_media_list[g_media_info_count] = (MediaInfo *)MemoryAlloc(sizeof(MediaInfo));
		g_media_list[g_media_info_count][0] = info;
		g_media_info_count ++;
	}
	RegCloseKey( hKey );

	if (g_media_info_count > 1)
	{
		qsort(g_media_list, g_media_info_count, sizeof(MediaInfo *), (int32_t (__cdecl *)(const void *,const void *))mediainfo_compare);
	}

	// ɾ³ý
	wchar_t szFileFormat[MAX_PATH];
	StringCchPrintf(szFileFormat, MAX_PATH, L"%ls\\vmeisoft_v1_*.*", g_szTempPath);
	WIN32_FIND_DATAW wfd;
	HANDLE hFind = FindFirstFile(szFileFormat, &wfd);
	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			GUID id = GetGuidFromFileName(wfd.cFileName);

			BOOL bFound = FALSE;
			for(int i = 0; i < g_media_info_count; i++)
			{
				if (g_media_list[i]->m_Id == id)
				{
					bFound = TRUE;
					break;
				}
			}
			if (bFound == FALSE)
			{
				wchar_t szFileName[MAX_PATH];
				StringCchPrintf(szFileName, MAX_PATH, L"%ls\\%ls", g_szTempPath, wfd.cFileName);
				DeleteFile(szFileName);
			}
		}
		while (FindNextFile(hFind, &wfd) != 0);
		FindClose(hFind);
	}
}
Exemplo n.º 7
0
/*获取可用通道号*/
int GetChannelId( int nDspModule )
{
	int nCurChan, i;
	long	clock;

	if( GetChannelShm( ) != SUCC )
	{
		ErrorLog(ERROR,"GetChannelShm fail");
		return FAIL;
	}

	PSem( CHANNEL_SEM, 1 );

	nCurChan = gpShmChan->cur_channel[nDspModule];

	/*取空闲的通道或占用时间超过15分钟的通道*/
	time( &clock );
	for( i=nCurChan; i<MAX_CHANNEL_NUM; i++ )
	{
		if( gpShmChan->channel[nDspModule][i].time == 0 ||
		    (clock-gpShmChan->channel[nDspModule][i].time) > 900 )
		{
			gpShmChan->channel[nDspModule][i].time= clock;
			if( i >= (MAX_CHANNEL_NUM-1) )
			{
				gpShmChan->cur_channel[nDspModule] = 0;
			}
			else
			{
				gpShmChan->cur_channel[nDspModule] = i+1;
			}
			VSem( CHANNEL_SEM, 1 );

			return i;
		}
	}

	/*取空闲的通道或占用时间超过15分钟的通道*/
	time( &clock );
	for( i=0; i<nCurChan; i++ )
	{
		if( gpShmChan->channel[nDspModule][i].time == 0 ||
		    (clock-gpShmChan->channel[nDspModule][i].time) > 900 )
		{
			gpShmChan->channel[nDspModule][i].time = clock;
			if( i >= (MAX_CHANNEL_NUM-1) )
			{
				gpShmChan->cur_channel[nDspModule] = 0;
			}
			else
			{
				gpShmChan->cur_channel[nDspModule] = i+1;
			}
			VSem( CHANNEL_SEM, 1 );

			return i;
		}
	}
			
	VSem( CHANNEL_SEM, 1 );

	return -1;
}
Exemplo n.º 8
0
DWORD CDBPSServer::StartServer(DWORD dwPort, DWORD dwNumberOfConnection)
{
	/*
		Server have to be give a port for itself from Server Administrator
	*/
	DWORD dwRet = E_RET_SUCCESS;
	dwRet = InitServerSock(dwPort);
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to initailize Server Sock");
		return E_RET_FAIL;
	}

	/*
		Create Completion Port for opertation IOCP.
		the variable 0 mean that IOCP set value itself.
	*/
	dwRet = InitIOCompletionPort(0);
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to initailize Server Sock");
		return E_RET_FAIL;
	}

	/*
		Make worker threads for operating IOCP
	*/
	dwRet = InitWorkerThread();
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to initailize Server Sock");
		return E_RET_FAIL;
	}

	dwRet = InitDBCQueue(dwNumberOfConnection);
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to initailize DB Connection Queue");
		return E_RET_FAIL;
	}


	dwRet = InitServerValue(dwPort);
	if (dwRet != E_RET_SUCCESS) {
		ErrorLog("Fail to configure server value");
		return E_RET_FAIL;
	}

	m_bStartServer = TRUE;
	while (m_bStartServer)
	{
		try
		{
			ST_CLIENT_SOCKET stClientSocket;
			dwRet = AcceptServer(stClientSocket);
			if (dwRet != E_RET_SUCCESS) {
				continue;
			}

			dwRet = CompleteReadFromClient(stClientSocket);
			if (dwRet != E_RET_SUCCESS) {
				continue;
			}
		}
		catch (std::exception &e)
		{
			/*
				Abnormally Exception
			*/
			ErrorLog("%s", e.what());
			DestoryDBCQueue(dwNumberOfConnection);
			return dwRet;
		}
	}

	/*
		All Thread is waiting for stopping their operation
	*/
	WaitForMultipleObjects(m_stServerWorkerThreads.dwNumberOfThread, m_stServerWorkerThreads.phWorkerThread, TRUE, INFINITE);
	DestoryDBCQueue(dwNumberOfConnection);
	
	return dwRet;
}
Exemplo n.º 9
0
void DBConn::MysqlErrorLog(const char* msg)
{
    ErrorLog("%s, " MYSQL_ERROR_FMT, msg, MYSQL_ERROR_ARG(_conn));
}
Exemplo n.º 10
0
void *
saveDbToTape(void *param)
{
    struct saveDbIf *saveDbIfPtr = (struct saveDbIf *)param;
    afs_int32 code = 0;
    afs_int32 i;
    int wroteLabel;
    afs_uint32 taskId;
    Date expires;

    struct butm_tapeInfo tapeInfo;
    struct budb_dumpEntry dumpEntry;

    extern struct deviceSyncNode *deviceLatch;
    extern struct tapeConfig globalTapeConfig;

    expires = (saveDbIfPtr->archiveTime ? NEVERDATE : 0);
    taskId = saveDbIfPtr->taskId;

    setStatus(taskId, DRIVE_WAIT);
    EnterDeviceQueue(deviceLatch);	/* lock tape device */
    clearStatus(taskId, DRIVE_WAIT);

    printf("\n\n");
    TLog(taskId, "SaveDb\n");

    tapeInfo.structVersion = BUTM_MAJORVERSION;
    code = butm_file_Instantiate(&tapeInfo, &globalTapeConfig);
    if (code) {
	ErrorLog(0, taskId, code, tapeInfo.error,
		 "Can't initialize tape module\n");
	ERROR_EXIT(code);
    }

    /* Determine what the last database dump was */
    memset(&lastDump, 0, sizeof(lastDump));
    code = bcdb_FindLatestDump("", "", &lastDump);
    if (code) {
	if (code != BUDB_NODUMPNAME) {
	    ErrorLog(0, taskId, code, 0, "Can't read backup database\n");
	    ERROR_EXIT(code);
	}
	memset(&lastDump, 0, sizeof(lastDump));
    }

    code = CreateDBDump(&dumpEntry);	/* Create a dump for this tape */
    if (code) {
	ErrorLog(0, taskId, code, 0, "Can't create dump in database\n");
	ERROR_EXIT(code);
    }


    listEntryHead = NULL;

    /* Get the tape and write a new label to it */
    code =
	GetDBTape(taskId, expires, &tapeInfo, dumpEntry.id, 1, autoQuery,
		  &wroteLabel);

    /*
     * If did not write the label, remove created dump
     * Else if wrote the label, remove old dump from db so it's not saved.
     */
    if (!wroteLabel) {
	i = bcdb_deleteDump(dumpEntry.id, 0, 0, 0);
	dumpEntry.id = 0;
	if (i && (i != BUDB_NOENT))
	    ErrorLog(0, taskId, i, 0, "Unable to delete DB entry %u.\n",
		     dumpEntry.id);
    } else if (listEntryHead->oldDumpId) {
	i = bcdb_deleteDump(listEntryHead->oldDumpId, 0, 0, 0);
	listEntryHead->oldDumpId = 0;
	if (i && (i != BUDB_NOENT)) {
	    ErrorLog(0, taskId, i, 0, "Unable to delete old DB entry %u.\n",
		     listEntryHead->oldDumpId);
	    ERROR_EXIT(i);
	}
    }
    if (code)
	ERROR_EXIT(code);

    TapeLog(1, taskId, 0, 0, "Tape accepted - now dumping database\n");

    /* we have a writable tape */
    code = writeDbDump(&tapeInfo, taskId, expires, dumpEntry.id);
    if (code)
	ERROR_EXIT(code);

    /* Now delete the entries between time 0 and archive-time */
    if (saveDbIfPtr->archiveTime)
	code = bcdb_deleteDump(0, 0, saveDbIfPtr->archiveTime, 0);

  error_exit:
    unmountTape(taskId, &tapeInfo);

    /* Add this dump's tapes to the database and mark it finished */
    if (dumpEntry.id) {
	i = addTapesToDb(taskId);
	if (!code)
	    code = i;

	i = bcdb_FinishDump(&dumpEntry);
	if (!code)
	    code = i;
    }
    freeTapeList();

    if (code == TC_ABORTEDBYREQUEST) {
	TLog(taskId, "SaveDb: Aborted by request\n");
	clearStatus(taskId, ABORT_REQUEST);
	setStatus(taskId, ABORT_DONE);
    } else if (code) {
	TapeLog(0, taskId, code, 0, "SaveDb: Finished with errors\n");
	setStatus(taskId, TASK_ERROR);
    } else {
	TLog(taskId, "SaveDb: Finished\n");
    }
    setStatus(taskId, TASK_DONE);

    free(saveDbIfPtr);
    LeaveDeviceQueue(deviceLatch);
    return (void *)(intptr_t)(code);
}
Exemplo n.º 11
0
static int
restoreDbEntries(struct butm_tapeInfo *tapeInfoPtr,
		 struct rstTapeInfo *rstTapeInfoPtr)
{
    struct structDumpHeader netItemHeader, hostItemHeader;
    afs_int32 more = 1;
    afs_int32 taskId, code = 0;
    int count = 0;

    taskId = rstTapeInfoPtr->taskId;

    /* clear state for the buffer routine(s) */
    initTapeBuffering();

    code = butm_ReadFileBegin(tapeInfoPtr);
    if (code) {
	ErrorLog(0, taskId, code, tapeInfoPtr->error,
		 "Can't read FileBegin on tape\n");
	ERROR_EXIT(code);
    }

    /* get the first item-header */
    memset(&netItemHeader, 0, sizeof(netItemHeader));
    code =
	getTapeData(tapeInfoPtr, rstTapeInfoPtr, &netItemHeader,
		    sizeof(netItemHeader));
    if (code)
	ERROR_EXIT(code);
    structDumpHeader_ntoh(&netItemHeader, &hostItemHeader);

    while (more) {
	switch (hostItemHeader.type) {
	case SD_DBHEADER:
	    code =
		restoreDbHeader(tapeInfoPtr, rstTapeInfoPtr, &hostItemHeader);
	    if (code)
		ERROR_EXIT(code);
	    break;

	case SD_DUMP:
	    if (++count > 25) {	/*every 25 dumps, wait */
		waitDbWatcher();
		count = 0;
	    }
	    code =
		restoreDbDump(tapeInfoPtr, rstTapeInfoPtr, &hostItemHeader);
	    if (code)
		ERROR_EXIT(code);
	    break;

	case SD_TAPE:
	case SD_VOLUME:
	    ERROR_EXIT(-1);
	    break;

	case SD_TEXT_DUMPSCHEDULE:
	case SD_TEXT_VOLUMESET:
	case SD_TEXT_TAPEHOSTS:
	    code = restoreText(tapeInfoPtr, rstTapeInfoPtr, &hostItemHeader);
	    if (code)
		ERROR_EXIT(code);
	    break;

	case SD_END:
	    more = 0;
	    break;

	default:
	    TLog(taskId, "Unknown database header type %d\n",
		 hostItemHeader.type);
	    ERROR_EXIT(-1);
	    break;
	}
    }

    code = butm_ReadFileEnd(tapeInfoPtr);
    if (code) {
	ErrorLog(0, taskId, code, tapeInfoPtr->error,
		 "Can't read EOF on tape\n");
	ERROR_EXIT(code);
    }

    /* Mark tape as having been written */
    tapeEntryPtr->useKBytes =
	tapeInfoPtr->kBytes + (tapeInfoPtr->nBytes ? 1 : 0);
    tapeEntryPtr->flags = BUDB_TAPE_WRITTEN;

  error_exit:
    return (code);
}
Exemplo n.º 12
0
static int
writeDbDump(struct butm_tapeInfo *tapeInfoPtr, afs_uint32 taskId,
	    Date expires, afs_uint32 dumpid)
{
    afs_int32 blockSize;
    afs_int32 writeBufNbytes = 0;
    char *writeBlock = 0;
    char *writeBuffer = 0;
    char *writeBufPtr;
    afs_int32 transferSize;

    char *readBufPtr = NULL;
    afs_int32 maxReadSize;

    charListT charList;
    afs_int32 done;
    afs_int32 code;
    afs_int32 chunksize = 0;
    afs_int32 tc_EndMargin, tc_KEndMargin, kRemaining;
    int sequence;
    int wroteLabel;
    int firstcall;
#ifdef AFS_PTHREAD_ENV
    pthread_t alivePid;
    pthread_attr_t tattr;
    AFS_SIGSET_DECL;
#else
    PROCESS alivePid;
#endif

    extern struct tapeConfig globalTapeConfig;
    extern struct udbHandleS udbHandle;

    blockSize = BUTM_BLKSIZE;
    writeBlock = (char *)malloc(BUTM_BLOCKSIZE);
    if (!writeBlock)
	ERROR_EXIT(TC_NOMEMORY);

    writeBuffer = writeBlock + sizeof(struct blockMark);
    memset(writeBuffer, 0, BUTM_BLKSIZE);
    maxReadSize = 1024;

    /*
     * The margin of space to check for end of tape is set to the
     * amount of space used to write an end-of-tape multiplied by 2.
     * The amount of space is size of a 16K EODump marker, its EOF
     * marker, and up to two EOF markers done on close (1 16K blocks +
     * 3 EOF * markers).
     */
    tc_EndMargin = (16384 + 3 * globalTapeConfig.fileMarkSize) * 2;
    tc_KEndMargin = tc_EndMargin / 1024;

    /* have to write enclose the dump in file marks */
    code = butm_WriteFileBegin(tapeInfoPtr);
    if (code) {
	ErrorLog(0, taskId, code, tapeInfoPtr->error,
		 "Can't write FileBegin on tape\n");
	ERROR_EXIT(code);
    }

    writeBufPtr = &writeBuffer[0];
    firstcall = 1;
    sequence = 1;
    charList.charListT_val = 0;
    charList.charListT_len = 0;

    while (1) {			/*w */
	/* When no data in buffer, read data from the budb_server */
	if (charList.charListT_len == 0) {
	    /* get more data. let rx allocate space */
	    if (charList.charListT_val) {
		free(charList.charListT_val);
		charList.charListT_val = 0;
	    }

	    /* get the data */
	    code =
		ubik_Call_SingleServer(BUDB_DumpDB, udbHandle.uh_client,
				       UF_SINGLESERVER, firstcall,
				       maxReadSize, &charList, &done);
	    if (code) {
		ErrorLog(0, taskId, code, 0, "Can't read database\n");
		ERROR_EXIT(code);
	    }

	    /* If this if the first call to the budb server, create a thread
	     * that will keep the connection alive (during tape changes).
	     */
	    if (firstcall) {
#ifdef AFS_PTHREAD_ENV
		code = pthread_attr_init(&tattr);
		if (code) {
		    ErrorLog(0, taskId, code, 0,
			     "Can't pthread_attr_init Keep-alive process\n");
		    ERROR_EXIT(code);
		}

		code =
		    pthread_attr_setdetachstate(&tattr,
						PTHREAD_CREATE_DETACHED);
		if (code) {
		    ErrorLog(0, taskId, code, 0,
			     "Can't pthread_attr_setdetachstate Keep-alive process\n");
		    ERROR_EXIT(code);
		}

		AFS_SIGSET_CLEAR();
		code = pthread_create(&alivePid, &tattr, KeepAlive, 0);
		AFS_SIGSET_RESTORE();
#else
		code =
		    LWP_CreateProcess(KeepAlive, 16384, 1, (void *)NULL,
				      "Keep-alive process", &alivePid);
#endif
		/* XXX should we check code here ??? XXX */
	    }
	    firstcall = 0;

	    readBufPtr = charList.charListT_val;
	}

	if ((charList.charListT_len == 0) && done)
	    break;

	/* compute how many bytes and transfer to the write Buffer */
	transferSize =
	    (charList.charListT_len <
	     (blockSize -
	      writeBufNbytes)) ? charList.charListT_len : (blockSize -
							   writeBufNbytes);

	memcpy(writeBufPtr, readBufPtr, transferSize);
	charList.charListT_len -= transferSize;
	writeBufPtr += transferSize;
	readBufPtr += transferSize;
	writeBufNbytes += transferSize;

	/* If filled the write buffer, then write it to tape */
	if (writeBufNbytes == blockSize) {
	    code = butm_WriteFileData(tapeInfoPtr, writeBuffer, 1, blockSize);
	    if (code) {
		ErrorLog(0, taskId, code, tapeInfoPtr->error,
			 "Can't write data on tape\n");
		ERROR_EXIT(code);
	    }

	    memset(writeBuffer, 0, blockSize);
	    writeBufPtr = &writeBuffer[0];
	    writeBufNbytes = 0;

	    /* Every BIGCHUNK bytes check if aborted */
	    chunksize += blockSize;
	    if (chunksize > BIGCHUNK) {
		chunksize = 0;
		if (checkAbortByTaskId(taskId))
		    ERROR_EXIT(TC_ABORTEDBYREQUEST);
	    }

	    /*
	     * check if tape is full - since we filled a blockSize worth of data
	     * assume that there is more data.
	     */
	    kRemaining = butm_remainingKSpace(tapeInfoPtr);
	    if (kRemaining < tc_KEndMargin) {
		code = butm_WriteFileEnd(tapeInfoPtr);
		if (code) {
		    ErrorLog(0, taskId, code, tapeInfoPtr->error,
			     "Can't write FileEnd on tape\n");
		    ERROR_EXIT(code);
		}

		code = butm_WriteEOT(tapeInfoPtr);
		if (code) {
		    ErrorLog(0, taskId, code, tapeInfoPtr->error,
			     "Can't write end-of-dump on tape\n");
		    ERROR_EXIT(code);
		}

		/* Mark tape as having been written */
		tapeEntryPtr->useKBytes =
		    tapeInfoPtr->kBytes + (tapeInfoPtr->nBytes ? 1 : 0);
		tapeEntryPtr->flags = BUDB_TAPE_WRITTEN;

		unmountTape(taskId, tapeInfoPtr);

		/* Get next tape and writes its label */
		sequence++;
		code =
		    GetDBTape(taskId, expires, tapeInfoPtr, dumpid, sequence,
			      1, &wroteLabel);
		if (code)
		    ERROR_EXIT(code);

		code = butm_WriteFileBegin(tapeInfoPtr);
		if (code) {
		    ErrorLog(0, taskId, code, tapeInfoPtr->error,
			     "Can't write FileBegin on tape\n");
		    ERROR_EXIT(code);
		}
	    }
	}
    }				/*w */

    /* no more data to be read - if necessary, flush out the last buffer */
    if (writeBufNbytes > 0) {
	code = butm_WriteFileData(tapeInfoPtr, writeBuffer, 1, blockSize);
	if (code) {
	    ErrorLog(1, taskId, code, tapeInfoPtr->error,
		     "Can't write data on tape\n");
	    ERROR_EXIT(code);
	}
    }

    code = butm_WriteFileEnd(tapeInfoPtr);
    if (code) {
	ErrorLog(0, taskId, code, tapeInfoPtr->error,
		 "Can't write FileEnd on tape\n");
	ERROR_EXIT(code);
    }

    /* Mark tape as having been written */
    tapeEntryPtr->useKBytes =
	tapeInfoPtr->kBytes + (tapeInfoPtr->nBytes ? 1 : 0);
    tapeEntryPtr->flags = BUDB_TAPE_WRITTEN;

  error_exit:
    /* Let the KeepAlive process stop on its own */
    code =
	ubik_Call_SingleServer(BUDB_DumpDB, udbHandle.uh_client,
			       UF_END_SINGLESERVER, 0);

    if (writeBlock)
	free(writeBlock);
    if (charList.charListT_val)
	free(charList.charListT_val);
    return (code);
}
Exemplo n.º 13
0
int
getTapeData(struct butm_tapeInfo *tapeInfoPtr,
	    struct rstTapeInfo *rstTapeInfoPtr,
	    void *out, afs_int32 requestedBytes)
{
    char *buffer = (char *) out;
    afs_int32 taskId, transferBytes;
    afs_int32 code = 0;

    taskId = rstTapeInfoPtr->taskId;

    if (checkAbortByTaskId(taskId))
	ERROR_EXIT(TC_ABORTEDBYREQUEST);

    if (!tapeReadBuffer) {
	tapeReadBuffer = (char *)malloc(BUTM_BLOCKSIZE);
	if (!tapeReadBuffer)
	    ERROR_EXIT(TC_NOMEMORY);
    }

    while (requestedBytes > 0) {
	if (nbytes == 0) {
	    tapeReadBufferPtr = &tapeReadBuffer[sizeof(struct blockMark)];

	    /* get more data */
	    code =
		butm_ReadFileData(tapeInfoPtr, tapeReadBufferPtr,
				  BUTM_BLKSIZE, &nbytes);
	    if (code) {
		/* detect if we hit the end-of-tape and get next tape */
		if (code == BUTM_ENDVOLUME) {
		    /* Update fields in tape entry for this tape */
		    tapeEntryPtr->flags = BUDB_TAPE_WRITTEN;
		    tapeEntryPtr->useKBytes =
			tapeInfoPtr->kBytes + (tapeInfoPtr->nBytes ? 1 : 0);

		    unmountTape(taskId, tapeInfoPtr);

		    rstTapeInfoPtr->tapeSeq++;
		    code = readDbTape(tapeInfoPtr, rstTapeInfoPtr, 1);
		    if (code)
			ERROR_EXIT(code);

		    code = butm_ReadFileBegin(tapeInfoPtr);
		    if (code) {
			ErrorLog(0, taskId, code, tapeInfoPtr->error,
				 "Can't read FileBegin on tape\n");
			ERROR_EXIT(code);
		    }

		    continue;
		}

		ErrorLog(0, taskId, code, tapeInfoPtr->error,
			 "Can't read FileData on tape\n");
		ERROR_EXIT(code);
	    }
	}

	/* copy out data */
	transferBytes = (nbytes < requestedBytes) ? nbytes : requestedBytes;
	memcpy(buffer, tapeReadBufferPtr, transferBytes);
	tapeReadBufferPtr += transferBytes;
	buffer += transferBytes;
	nbytes -= transferBytes;
	requestedBytes -= transferBytes;
    }

  error_exit:
    return (code);
}
Exemplo n.º 14
0
int
restoreText(struct butm_tapeInfo *tapeInfo,
	    struct rstTapeInfo *rstTapeInfoPtr,
	    struct structDumpHeader *nextHeader)
{
    char filename[64];
    afs_int32 nbytes;
    char *readBuffer = 0;
    afs_int32 readBlockSize;
    afs_int32 transferSize;
    struct structDumpHeader netItemHeader;
    int fid = -1;
    afs_int32 code = 0;

    udbClientTextP ctPtr = 0;
    afs_int32 textType;

    ctPtr = (udbClientTextP) malloc(sizeof(*ctPtr));
    if (!ctPtr)
	ERROR_EXIT(TC_NOMEMORY);

    /* determine the type of text block */
    switch (nextHeader->type) {
    case SD_TEXT_DUMPSCHEDULE:
	textType = TB_DUMPSCHEDULE;
	break;

    case SD_TEXT_VOLUMESET:
	textType = TB_VOLUMESET;
	break;

    case SD_TEXT_TAPEHOSTS:
	textType = TB_TAPEHOSTS;
	break;

    default:
	ErrorLog(0, rstTapeInfoPtr->taskId, TC_INTERNALERROR, 0,
		 "Unknown text block\n");
	ERROR_EXIT(TC_INTERNALERROR);
	break;
    }

    /* open the text file */
    sprintf(filename, "%s/bu_XXXXXX", gettmpdir());
#if defined (HAVE_MKSTEMP)
    fid = mkstemp(filename);
#else
    fid = open(mktemp(filename), O_RDWR | O_CREAT | O_EXCL, 0600);
#endif
    if (fid < 0) {
	ErrorLog(0, rstTapeInfoPtr->taskId, errno, 0,
		 "Can't open temporary text file: %s\n", filename);
	ERROR_EXIT(errno);
    }

    /* allocate buffer for text */
    readBlockSize = BUTM_BLKSIZE;
    readBuffer = (char *)malloc(readBlockSize);
    if (!readBuffer)
	ERROR_EXIT(TC_NOMEMORY);

    /* read the text into the temporary file */
    nbytes = nextHeader->size;
    while (nbytes > 0) {
	transferSize = (readBlockSize < nbytes) ? readBlockSize : nbytes;

	/* read it from the tape */
	code =
	    getTapeData(tapeInfo, rstTapeInfoPtr, readBuffer, transferSize);
	if (code)
	    ERROR_EXIT(code);

	/* write to the file */
	if (write(fid, readBuffer, transferSize) != transferSize) {
	    ErrorLog(0, rstTapeInfoPtr->taskId, errno, 0,
		     "Can't write temporary text file: %s\n", filename);
	    ERROR_EXIT(errno);
	}

	nbytes -= transferSize;
    }

    close(fid);
    fid = -1;
    code = saveTextFile(rstTapeInfoPtr->taskId, textType, filename);
    if (code)
	ERROR_EXIT(code);
    unlink(filename);

    /* get the next item-header */
    memset(nextHeader, 0, sizeof(*nextHeader));
    code =
	getTapeData(tapeInfo, rstTapeInfoPtr, &netItemHeader,
		    sizeof(netItemHeader));
    if (code)
	ERROR_EXIT(code);
    structDumpHeader_ntoh(&netItemHeader, nextHeader);

  error_exit:
    if (ctPtr)
	free(ctPtr);
    if (readBuffer)
	free(readBuffer);
    if (fid != -1) {
	close(fid);
	unlink(filename);
    }
    return (code);
}
Exemplo n.º 15
0
int pi_master( char *rservers_ip_port , unsigned long max_x , int tasks_count )
{
	struct Dc4cApiEnv	*penv = NULL ;
	struct Dc4cBatchTask	*tasks_array = NULL ;
	int			workers_count ;
	unsigned long		dd_x ;
	unsigned long		start_x , end_x ;
	
	int			i ;
	struct Dc4cBatchTask	*p_task = NULL ;
	
	mpf_t			pi_incr ;
	mpf_t			pi ;
	
	char			output[ 1024 + 1 ] ;
	
	int			nret = 0 ;
	
	DC4CSetAppLogFile( "pi_master" );
	SetLogLevel( LOGLEVEL_INFO );
	
	InfoLog( __FILE__ , __LINE__ , "pi_master" );
	
	nret = DC4CInitEnv( & penv , rservers_ip_port ) ;
	if( nret )
	{
		ErrorLog( __FILE__ , __LINE__ , "DC4CInitEnv failed[%d]" , nret );
		return -1;
	}
	else
	{
		InfoLog( __FILE__ , __LINE__ , "DC4CInitEnv ok" );
	}
	
	DC4CSetOptions( penv , DC4C_OPTIONS_BIND_CPU );
	
	if( tasks_count == -2 )
	{
		nret = DC4CQueryWorkers( penv ) ;
		if( nret )
		{
			ErrorLog( __FILE__ , __LINE__ , "DC4CQueryWorkers failed[%d]" , nret );
			return -1;
		}
		
		tasks_count = DC4CGetUnusedWorkersCount( penv ) ;
		if( tasks_count <= 0 )
		{
			ErrorLog( __FILE__ , __LINE__ , "tasks_count[%d] invalid" , tasks_count );
			return -1;
		}
	}
	
	tasks_array = (struct Dc4cBatchTask *)malloc( sizeof(struct Dc4cBatchTask) * tasks_count ) ;
	if( tasks_array == NULL )
	{
		ErrorLog( __FILE__ , __LINE__ , "alloc failed , errno[%d]" , errno );
		return -1;
	}
	memset( tasks_array , 0x00 , sizeof(struct Dc4cBatchTask) * tasks_count );
	
	dd_x = ( max_x - tasks_count ) / tasks_count ;
	start_x = 1 ;
	for( i = 0 , p_task = tasks_array ; i < tasks_count ; i++ , p_task++ )
	{
		end_x = start_x + dd_x ;
		snprintf( p_task->program_and_params , sizeof(p_task->program_and_params) , "dc4c_test_worker_pi %lu %lu" , start_x , end_x );
		p_task->timeout = DC4CGetTimeout(penv) ;
		start_x = end_x + 2 ;
	}
	
	workers_count = tasks_count ;
	nret = DC4CDoBatchTasks( penv , workers_count , tasks_array , tasks_count ) ;
	free( tasks_array );
	if( nret )
	{
		ErrorLog( __FILE__ , __LINE__ , "DC4CDoBatchTasks failed[%d]" , nret );
		return -1;
	}
	else
	{
		InfoLog( __FILE__ , __LINE__ , "DC4CDoBatchTasks ok" );
	}
	
	mpf_init( pi_incr );
	mpf_init_set_d( pi , 0.00 );
	
	for( i = 0 ; i < tasks_count ; i++ )
	{
		mpf_set_str( pi_incr , DC4CGetBatchTasksInfo(penv,i) , 10 );
		mpf_add( pi , pi , pi_incr );
	}
	
	memset( output , 0x00 , sizeof(output) );
	gmp_snprintf( output , sizeof(output)-1 , "%.Ff" , pi );
	InfoLog( __FILE__ , __LINE__ , "pi_master() - max_x[%u] tasks_count[%d] - PI[%s]" , max_x , tasks_count , output );
	
	mpf_clear( pi_incr );
	mpf_clear( pi );
	
	DC4CCleanEnv( & penv );
	InfoLog( __FILE__ , __LINE__ , "DC4CCleanEnv ok" );
	
	return 0;
}
Exemplo n.º 16
0
static int AccessToken( char *project_name , int loop_flag )
{
	char				etc_pathfilename[ 256 + 1 ] ;
	char				*AppID = NULL ;
	char				*AppSecret = NULL ;
	
	CURL				*curl = NULL ;
	CURLcode			res ;
	char				url[ 1024 + 1 ] ;
	struct CurlResponseBuffer	buf ;
	accesstoken			at ;
	
	int				nret = 0 ;
	
	curl_global_init( CURL_GLOBAL_ALL );
	
	memset( & buf , 0x00 , sizeof(struct CurlResponseBuffer) );
	
	memset( & at , 0x00 , sizeof(accesstoken) );
	
	do
	{
		InfoLog( __FILE__ , __LINE__ , "sleep [%d]seconds ..." , at.expires_in / 2 );
		sleep( at.expires_in / 2 );
		InfoLog( __FILE__ , __LINE__ , "sleep [%d]seconds done" , at.expires_in / 2 );
		
		memset( etc_pathfilename , 0x00 , sizeof(etc_pathfilename) );
		SNPRINTF( etc_pathfilename , sizeof(etc_pathfilename)-1 , "%s/etc/%s/AppID" , getenv("HOME") , project_name );
		PUBReadEntireFileSafely( etc_pathfilename , "r" , & AppID , NULL );
		PUBStringNoEnter( AppID );
		InfoLog( __FILE__ , __LINE__ , "AppID[%s]" , AppID );
		
		memset( etc_pathfilename , 0x00 , sizeof(etc_pathfilename) );
		SNPRINTF( etc_pathfilename , sizeof(etc_pathfilename)-1 , "%s/etc/%s/AppSecret" , getenv("HOME") , project_name );
		PUBReadEntireFileSafely( etc_pathfilename , "r" , & AppSecret , NULL);
		PUBStringNoEnter( AppSecret );
		InfoLog( __FILE__ , __LINE__ , "AppSecret[%s]" , AppSecret );
		
		curl = curl_easy_init() ;
		if( curl == NULL )
		{
			ErrorLog( __FILE__ , __LINE__ , "curl_easy_init failed" );
			break;
		}
		
		memset( url , 0x00 , sizeof(url) );
		SNPRINTF( url , sizeof(url)-1 , "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" , AppID , AppSecret );
		curl_easy_setopt( curl , CURLOPT_URL , url );
		
		curl_easy_setopt( curl , CURLOPT_WRITEFUNCTION , & CurlResponseProc );
		if( buf.buf_size )
		{
			memset( buf.base , 0x00 , buf.buf_size );
			buf.str_len = 0 ;
		}
		curl_easy_setopt( curl , CURLOPT_WRITEDATA , (void*) & buf );
		
		InfoLog( __FILE__ , __LINE__ , "curl_easy_perform[%s] ..." , url );
		res = curl_easy_perform( curl );
		InfoLog( __FILE__ , __LINE__ , "curl_easy_perform[%s] return[%d]" , url , res );
		curl_easy_cleanup( curl );
		if( res == CURLE_OK )
		{
			memset( & at , 0x00 , sizeof(accesstoken) );
			nret = DSCDESERIALIZE_JSON_accesstoken( NULL , buf.base , & (buf.str_len) , & at ) ;
			if( nret )
			{
				ErrorLog( __FILE__ , __LINE__ , "DSCDESERIALIZE_JSON_accesstoken failed[%d] , json[%.*s]" , nret , buf.str_len , buf.base );
				break;
			}
			else
			{
				InfoLog( __FILE__ , __LINE__ , "DSCDESERIALIZE_JSON_accesstoken ok , json[%.*s]" , buf.str_len , buf.base );
			}
			
			memset( etc_pathfilename , 0x00 , sizeof(etc_pathfilename) );
			SNPRINTF( etc_pathfilename , sizeof(etc_pathfilename)-1 , "%s/etc/%s/AccessToken" , getenv("HOME") , project_name );
			PUBWriteEntireFile( etc_pathfilename , "w" , at.access_token , -1 );
			InfoLog( __FILE__ , __LINE__ , "write[%s] to file[%s]" , at.access_token , etc_pathfilename );
		}
		
		free( AppID ); AppID = NULL ;
		free( AppSecret ); AppSecret = NULL ;
	}
	while( loop_flag );
	
	curl_global_cleanup();
	
	if( AppID )
	{
		free( AppID ); AppID = NULL ;
	}
	if( AppSecret )
	{
		free( AppSecret );  AppSecret = NULL ;
	}
	
	if( buf.base )
	{
		free( buf.base ); buf.base = NULL ;
		buf.buf_size = 0 ;
		buf.str_len = 0 ;
	}
	
	return 0;
}
Exemplo n.º 17
0
/**
* @brief ����UART�˿�����
* @param port �˿ں�, 0~4
* @param databits ����λ, 5~8
* @param stopbits ֹͣλ, 1~2
* @param parity У��λ
*/
void UartSetParity(unsigned int port, int databits,int stopbits, char parity)
{ 
	struct termios options; 
	int fd;

	AssertLogReturnVoid(port>=UART_PORTNUM, "invalid port(%d)\n", port);
	fd = FidUart[port];
	AssertLogReturnVoid(-1 == fd, "invalid fid(%d)\n", fd);

	if(tcgetattr(fd, &options) != 0) {
		ErrorLog("tcgetattr fail\n");
		return;
	}

	options.c_iflag = 0;

	options.c_cflag &= ~CSIZE; 
	switch (databits) { /*设置数据位数*/
	case 5: options.c_cflag |= CS5; break;
	case 6: options.c_cflag |= CS6; break;	
	case 7:	options.c_cflag |= CS7; break;
	case 8: options.c_cflag |= CS8; break;   
	default: ErrorLog("invalid databits(%d)\n", databits); return;   
	}

	switch (parity) {
	case 'n':
	case 'N':    
		options.c_cflag &= ~PARENB;   /* Clear parity enable */
		options.c_iflag &= ~INPCK;     /* Enable parity checking */ 
		break;  
	case 'o':   
	case 'O':     
		options.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/  
		options.c_iflag |= INPCK;             /* Disnable parity checking */ 
		break;  
	case 'e':  
	case 'E':   
		options.c_cflag |= PARENB;     /* Enable parity */    
		options.c_cflag &= ~PARODD;   /* 转换为偶效验*/     
		options.c_iflag |= INPCK;       /* Disnable parity checking */
		break;
	case 'S': 
	case 's':  /*as no parity*/   
	    options.c_cflag &= ~PARENB;
		options.c_cflag &= ~CSTOPB;break;  
	default: ErrorLog("invalid parity(%d)\n", parity); return;
	}

	/* 设置停止位*/  
	switch (stopbits) {
	case 1: options.c_cflag &= ~CSTOPB; break;  
	case 2: options.c_cflag |= CSTOPB; break;
	default: ErrorLog("invalid stopbits(%d)\n", stopbits); return;
	}

	options.c_iflag  &= ~(INLCR|IGNCR|ICRNL|IUCLC);  //add 2007-10-19
	options.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/
	options.c_oflag  &= ~OPOST;   /*Output*/

	tcflush(fd, TCIFLUSH);
	options.c_cc[VTIME] = 0; /* 设置超时15 seconds*/   
	options.c_cc[VMIN] = 0; /* Update the options and do it NOW */

	if(tcsetattr(fd, TCSANOW, &options) != 0) {
		ErrorLog("tcsetattr fail\n");
		return;
	}
}
Exemplo n.º 18
0
VOID ShowErrorSend(DWORD dwErr)
{
	switch (dwErr)
	{
	case WSANOTINITIALISED:
		ErrorLog("A successful WSAStartup call must occur before using this function.");
		break;
	case WSAENETDOWN:
		ErrorLog("The network subsystem has failed.");
		break;
	case WSAEACCES:
		ErrorLog("The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST socket option to enable use of the broadcast address.");
		break;
	case WSAEINTR:
		ErrorLog("A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.");
		break;
	case WSAEINPROGRESS:
		ErrorLog("A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.");
		break;
	case WSAEFAULT:
		ErrorLog("The buf parameter is not completely contained in a valid part of the user address space.");
		break;
	case WSAENETRESET:
		ErrorLog("The connection has been broken due to the keep-alive activity detecting a failure while the operation was in progress."); 
		break;
	case WSAENOBUFS:
		ErrorLog("No buffer space is available.");
		break;
	case WSAENOTCONN:
		ErrorLog("The socket is not connected.");
		break;
	case WSAENOTSOCK:
		ErrorLog("The descriptor is not a socket.");
		break;
	case WSAEOPNOTSUPP:
		ErrorLog("MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations.");
		break;
	case WSAESHUTDOWN:
		ErrorLog("The socket has been shut down; it is not possible to send on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.");
		break;
	case WSAEWOULDBLOCK:
		ErrorLog("The socket is marked as nonblocking and the requested operation would block.");
		break;
	case WSAEMSGSIZE:
		ErrorLog("The socket is message oriented, and the message is larger than the maximum supported by the underlying transport.");
		break;
	case WSAEHOSTUNREACH:
		ErrorLog("The remote host cannot be reached from this host at this time.");
		break;
	case WSAEINVAL:
		ErrorLog("The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled.");
		break;
	case WSAECONNABORTED:
		ErrorLog("The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable.");
		break;
	case WSAECONNRESET:
		ErrorLog("The virtual circuit was reset by the remote side executing a hard or abortive close. For UDP sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a \"Port Unreachable\" ICMP packet. The application should close the socket as it is no longer usable.");
		break;
	case WSAETIMEDOUT:
		ErrorLog("The connection has been dropped, because of a network failure or because the system on the other end went down without notice.");
		break;
	default:
		ErrorLog("Cannot find Error Type");
		break;
	}
}
Exemplo n.º 19
0
bool LobbyServer::initialize(int workerThreadCount)
{
    log = new Log();
    if (log->Initialize(LOG_PATH) == false)
    {
        return false;
    }
    
    lobbyData = new LobbyData();
    if (!lobbyData->Initialize())
    {
        ErrorLog("lobbyData Initialize");
        return false;
    }
    
    WorkerThread** workerThreadArray = new WorkerThread*[workerThreadCount];
    
    for(int i = 0; i < workerThreadCount; i++)
    {
        workerThreadArray[i] = new IOManager();
    }
    
    
    network = new Network();
    if (network->Initialize(lobbyData->networkInfoList, lobbyData->networkInfoCount, workerThreadCount, workerThreadArray) == false)
    {
        ErrorLog("Network error");
        return false;
    }

	userMgr = new UserManager();
	if (!userMgr->initialize())
	{
		return false;
	}

    ChannelInfo channelInfo[3];
    for(int i = 1; i < 4; i++)
    {
        channelInfo[i-1].channelNo = i;
        channelInfo[i-1].channelNameLen = 8;
        sprintf(channelInfo[i-1].channelName, "channel%d", i);
    }
    
	channelMgr = new ChannelManager();
	if (!channelMgr->initialize(3, channelInfo))
	{
		return false;
	}
    
    roomMgr = new RoomManager();
    if(roomMgr->initialize() == false)
    {
        return false;
    }
    
    serverInfoMgr = new ServerInfoManager();
    if(serverInfoMgr->initialize() == false)
    {
        return false;
    }
    
    quickPlayMgr = new QuickPlayManager();
    if(quickPlayMgr->initialize() == false)
    {
        return false;
    }

	return true;
}
Exemplo n.º 20
0
static int cgimain( struct Weixin4cEnv *penv )
{
	char		*signature = NULL ;
	char		*timestamp = NULL ;
	char		*nonce = NULL ;
	char		*echostr = NULL ;
	
	char		*post_data = NULL ;
	int		post_data_len ;
	xml		req ;
	
	int		nret = 0 ;
	
	PUBSendContentTypeHtml();
	
	PUBDupUrlParam( "signature" , & signature );
	PUBDupUrlParam( "timestamp" , & timestamp );
	PUBDupUrlParam( "nonce" , & nonce );
	PUBDupUrlParam( "echostr" , & echostr );
	
	if( signature && timestamp && nonce && echostr )
	{
		SetLogFile( "%s/log/%s_VerifyServer.log" , penv->pconf->home , penv->pconf->project_name );
		nret = VerifyServer( penv , signature , timestamp , nonce , echostr ) ;
		SetLogFile( "%s/log/%s_weixin4c.log" , penv->pconf->home , penv->pconf->project_name );
		if( nret )
		{
			ErrorLog( __FILE__ , __LINE__ , "VerifyServer failed[%d]" , nret );
		}
		else
		{
			InfoLog( __FILE__ , __LINE__ , "VerifyServer ok" );
		}
	}
	else
	{
		nret = PUBReadPostBuffer() ;
		if( nret )
		{
			ErrorLog( __FILE__ , __LINE__ , "PUBReadPostBuffer failed[%d]" , nret );
		}
		else
		{
			InfoLog( __FILE__ , __LINE__ , "PUBReadPostBuffer ok" );
			
			post_data = PUBGetPostBufferPtr() ;
			post_data_len = PUBGetPostBufferLength() ;
			
			memset( & req , 0x00 , sizeof(xml) );
			nret = DSCDESERIALIZE_XML_xml( NULL , post_data , & post_data_len , & req ) ;
			if( nret )
			{
				ErrorLog( __FILE__ , __LINE__ , "DSCDESERIALIZE_XML_xml_MsgType failed[%d] , xml[%s]" , nret , post_data );
			}
			else
			{
				InfoLog( __FILE__ , __LINE__ , "DSCDESERIALIZE_XML_xml_MsgType ok , xml[%s]" , post_data );
				
				InfoLog( __FILE__ , __LINE__ , "req.MsgType[%s]" , req.MsgType );
				if( strcmp( req.MsgType , "<![CDATA[event]]>" ) == 0 )
				{
					nret = ReceiveEvent( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveEvent failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveEvent ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[text]]>" ) == 0 )
				{
					nret = ReceiveText( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveText failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveText ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[image]]>" ) == 0 )
				{
					nret = ReceiveImage( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveImage failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveImage ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[voice]]>" ) == 0 )
				{
					nret = ReceiveVoice( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveVoice failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveVoice ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[video]]>" ) == 0 )
				{
					nret = ReceiveVideo( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveVideo failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveVideo ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[shortvideo]]>" ) == 0 )
				{
					nret = ReceiveShortVideo( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveShortVideo failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveShortVideo ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[location]]>" ) == 0 )
				{
					nret = ReceiveLocation( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveLocation failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveLocation ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[link]]>" ) == 0 )
				{
					nret = ReceiveLink( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveLink failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveLink ok" );
					}
				}
				else
				{
					ErrorLog( __FILE__ , __LINE__ , "xml.MsgType[%s] invalid" , req.MsgType );
				}
			}
		}
	}
	
	if( signature )
		free( signature );
	if( timestamp )
		free( timestamp );
	if( nonce )
		free( nonce );
	if( echostr )
		free( echostr );
	
	return nret;
}
Exemplo n.º 21
0
// ustalenie numeru tekstury, wczytanie jeśli jeszcze takiej nie było
texture_handle
texture_manager::create( std::string Filename, bool const Loadnow ) {

    if( Filename.find( '|' ) != std::string::npos )
        Filename.erase( Filename.find( '|' ) ); // po | może być nazwa kolejnej tekstury

    std::pair<std::string, std::string> locator; // resource name, resource type
    std::string traits;

    // discern textures generated by a script
    // TBD: support file: for file resources?
    auto const isgenerated { Filename.find( "make:" ) == 0 };
    // process supplied resource name
    if( isgenerated ) {
        // generated resource
        // scheme:(user@)path?query

        // remove scheme indicator
        Filename.erase( 0, Filename.find( ':' ) + 1 );
        // TODO: extract traits specification from the query
        // clean up slashes
        erase_leading_slashes( Filename );
    }
    else {
        // regular file resource
        // (filepath/)(#)filename.extension(:traits)

        // extract trait specifications
        auto const traitpos = Filename.rfind( ':' );
        if( traitpos != std::string::npos ) {
            // po dwukropku mogą być podane dodatkowe informacje niebędące nazwą tekstury
            if( Filename.size() > traitpos + 1 ) {
                traits = Filename.substr( traitpos + 1 );
            }
            Filename.erase( traitpos );
        }
        // potentially trim file type indicator since we check for multiple types
        erase_extension( Filename );
        // clean up slashes
        erase_leading_slashes( Filename );
        // temporary code for legacy assets -- textures with names beginning with # are to be sharpened
        if( ( Filename[ 0 ] == '#' )
         || ( Filename.find( "/#" ) != std::string::npos ) ) {
            traits += '#';
        }
    }
    // try to locate requested texture in the databank
    // TBD, TODO: include trait specification in the resource id in the databank?
    auto const lookup { find_in_databank( Filename ) };
    if( lookup != npos ) {
        return lookup;
    }
    // if the lookup fails...
    if( isgenerated ) {
        // TODO: verify presence of the generator script
        locator.first = Filename;
        locator.second = "make:";
    }
    else {
        // ...for file resources check if it's on disk
        locator = find_on_disk( Filename );
        if( true == locator.first.empty() ) {
            // there's nothing matching in the databank nor on the disk, report failure
            ErrorLog( "Bad file: failed do locate texture file \"" + Filename + "\"", logtype::file );
            return npos;
        }
    }

    auto texture = new opengl_texture();
    texture->name = locator.first;
    texture->type = locator.second;
    texture->traits = traits;
    auto const textureindex = (texture_handle)m_textures.size();
    m_textures.emplace_back( texture, std::chrono::steady_clock::time_point() );
    m_texturemappings.emplace( locator.first, textureindex );

    WriteLog( "Created texture object for \"" + locator.first + "\"", logtype::texture );

    if( true == Loadnow ) {

        texture_manager::texture( textureindex ).load();
#ifndef EU07_DEFERRED_TEXTURE_UPLOAD
        texture_manager::texture( textureindex ).create();
        // texture creation binds a different texture, force a re-bind on next use
        m_activetexture = -1;
#endif
    }

    return textureindex;
};
Exemplo n.º 22
0
TSoundContainer::TSoundContainer(LPDIRECTSOUND pDS, char *Directory, char *strFileName,
                                 int NConcurrent)
{   // wczytanie pliku dŸwiêkowego
    int hr = 111;
    DSBuffer = NULL; // na pocz¹tek, gdyby uruchomiæ dŸwiêków siê nie uda³o

    Concurrent = NConcurrent;

    Oldest = 0;
    //    strcpy(Name, strFileName);

    strcpy(Name, Directory);
    strcat(Name, strFileName);

    CWaveSoundRead *pWaveSoundRead;

    // Create a new wave file class
    pWaveSoundRead = new CWaveSoundRead();

    // Load the wave file
    if (FAILED(pWaveSoundRead->Open(Name)))
        if (FAILED(pWaveSoundRead->Open(strFileName)))
        {
            //        SetFileUI( hDlg, TEXT("Bad wave file.") );
            return;
            ErrorLog("Missed sound: " + AnsiString(strFileName));
        }

    strcpy(Name, AnsiString(strFileName).LowerCase().c_str());

    // Set up the direct sound buffer, and only request the flags needed
    // since each requires some overhead and limits if the buffer can
    // be hardware accelerated
    DSBUFFERDESC dsbd;
    ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
    dsbd.dwSize = sizeof(DSBUFFERDESC);
    dsbd.dwFlags = DSBCAPS_STATIC | DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY;
    if (!Global::bInactivePause) // jeœli prze³¹czony w t³o ma nadal dzia³aæ
        dsbd.dwFlags |= DSBCAPS_GLOBALFOCUS; // to dŸwiêki maj¹ byæ równie¿ s³yszalne
    dsbd.dwBufferBytes = pWaveSoundRead->m_ckIn.cksize;
    dsbd.lpwfxFormat = pWaveSoundRead->m_pwfx;
    fSamplingRate = pWaveSoundRead->m_pwfx->nSamplesPerSec;
    iBitsPerSample = pWaveSoundRead->m_pwfx->wBitsPerSample;

    //    pDSBuffer= (LPDIRECTSOUNDBUFFER*) malloc(Concurrent*sizeof(LPDIRECTSOUNDBUFFER));
    //    for (int i=0; i<Concurrent; i++)
    //      pDSBuffer[i]= NULL;

    // Create the static DirectSound buffer
    if (FAILED(hr = pDS->CreateSoundBuffer(&dsbd, &(DSBuffer), NULL)))
        // if (FAILED(pDS->CreateSoundBuffer(&dsbd,&(DSBuffer),NULL)))
        return;

    // Remember how big the buffer is
    DWORD dwBufferBytes;

    dwBufferBytes = dsbd.dwBufferBytes;

    //----------------------------------------------------------

    BYTE *pbWavData; // Pointer to actual wav data
    UINT cbWavSize; // Size of data
    VOID *pbData = NULL;
    VOID *pbData2 = NULL;
    DWORD dwLength;
    DWORD dwLength2;

    // The size of wave data is in pWaveFileSound->m_ckIn
    INT nWaveFileSize = pWaveSoundRead->m_ckIn.cksize;

    // Allocate that buffer.
    pbWavData = new BYTE[nWaveFileSize];
    if (NULL == pbWavData)
        return; // E_OUTOFMEMORY;

    // if (FAILED(hr=pWaveSoundRead->Read( nWaveFileSize,pbWavData,&cbWavSize)))
    if (FAILED(hr = pWaveSoundRead->Read(nWaveFileSize, pbWavData, &cbWavSize)))
        return;

    // Reset the file to the beginning
    pWaveSoundRead->Reset();

    // Lock the buffer down
    // if (FAILED(hr=DSBuffer->Lock(0,dwBufferBytes,&pbData,&dwLength,&pbData2,&dwLength2,0)))
    if (FAILED(hr = DSBuffer->Lock(0, dwBufferBytes, &pbData, &dwLength, &pbData2, &dwLength2, 0L)))
        return;

    // Copy the memory to it.
    memcpy(pbData, pbWavData, dwBufferBytes);

    // Unlock the buffer, we don't need it anymore.
    DSBuffer->Unlock(pbData, dwBufferBytes, NULL, 0);
    pbData = NULL;

    // We dont need the wav file data buffer anymore, so delete it
    delete[] pbWavData;

    delete pWaveSoundRead;

    DSBuffers.push(DSBuffer);

    /*
        for (int i=1; i<Concurrent; i++)
        {
            if( FAILED( hr= pDS->DuplicateSoundBuffer(pDSBuffer[0],&(pDSBuffer[i]))))
            {
                Concurrent= i;
                break;
            };


        };*/
};
Exemplo n.º 23
0
// Class probe
IOService * 
VoodooPState::probe(IOService * provider,
				   SInt32 * score)
{
	Ready = false;

	// Probe the superclass
	if (IOService::probe(provider, score) != this) return NULL;
	
	// Read our own values from the property list
	OSDictionary * dictionary = OSDynamicCast(OSDictionary, getProperty(keyPowerControl));
	if (!dictionary) return NULL;
	UseEfiFsb			= getPlistValue(dictionary, keyUseEfiFsb);
	VoltageOverride		= getPlistValue(dictionary, keyVoltageOverride);
	VoltageProbe		= getPlistValue(dictionary, keyVoltageProbe);
	UserVoltageMax		= getPlistValue(dictionary, keyUserVoltageMax);
	UserVoltageMin		= getPlistValue(dictionary, keyUserVoltageMin);
	ColdStart			= getPlistValue(dictionary, keyColdStart);
	TimerInterval		= getPlistValue(dictionary, keyTimerInterval);
	UseACPI				= getPlistValue(dictionary, keyUseACPI);
	if(TimerInterval < 50){
		TimerInterval = 50;
	}
	
	// Get CPU's from I/O Kit
	CpuCount = getCpuCount();
	
	// No CPU's found -> bailout
	if (CpuCount == 0) return NULL;
	
	// Get FSB from /efi/platform
	CpuFSB = gPEClockFrequencyInfo.bus_frequency_max_hz >> 2;
	if (UseEfiFsb) {
		IORegistryEntry * entry = fromPath(keyEfiPlatform, gIODTPlane);
		if (entry) {
			OSObject * object = entry->getProperty(keyEfiFsbFrequency);
			if (object && (OSTypeIDInst(object) == OSTypeID(OSData))) {
				OSData * data = OSDynamicCast(OSData, object);
				if (data) {
					CpuFSB = * (UInt32 *) data->getBytesNoCopy();
					gPEClockFrequencyInfo.bus_frequency_max_hz = CpuFSB << 2;
				}
			}
		}		
	}
	CpuFSB = (CpuFSB+Mega/2) / Mega;	// Mega is enough

#if	SUPPORT_VOODOO_KERNEL
	{
		UInt64 magic;
		nanoseconds_to_absolutetime(~(0), &magic);
		VoodooKernel = (magic == 2);
	}
#endif
	// Enumerate CPU's
	CpuCoreTech = Unknown;
	{
		uint32_t data[4];

		do_cpuid(0, data);
		((uint32_t*)vendor)[0] = data[1];
		((uint32_t*)vendor)[1] = data[3];
		((uint32_t*)vendor)[2] = data[2];
		vendor[15] = 0;

		do_cpuid(1, data);
		CpuSignature = data[0];

		// Features
		((uint32_t*)&Features)[0] = data[3];
		((uint32_t*)&Features)[1] = data[2];

		for( int i = 0; i < 3; i++ ){
			do_cpuid(0x80000002+i, data);
			memcpy( &brand_string[i*16], data, 16 );
		}
		brand_string[16*3] = 0;
	}

	// Find core technology and cross core vendor specifics
	// Intel
	if (!strncmp(vendor, CPUID_VID_INTEL, sizeof(CPUID_VID_INTEL))) {
		if(!intel_probe(this)) return NULL;
	}
	// AMD
	else if (!strncmp(vendor, CPUID_VID_AMD, sizeof(CPUID_VID_AMD))) {
		if(!amd_probe(this)) return NULL;
	}
	// Unknown CPU or core technology
	else {
		ErrorLog("CPU: Core Technology Unknown - Signature %x (%s)(%s)",
				 (unsigned int)CpuSignature,
				 vendor,
				 brand_string);
		return NULL;
	}
	
	return this;
}
Exemplo n.º 24
0
bool ServiceUtil::startup(const tstring& name, const DWORD timeout_ms)
{
    InfoLog(TSTR("StartupService[%s] begin"), name.c_str());
    bool bReturn = false;

    do 
    {
        scoped_svc_handle hService(name, GENERIC_ALL, GENERIC_EXECUTE | GENERIC_READ);
        if (!hService.valid())
        {
            break;
        }

        SERVICE_STATUS status = {0};
        if (!QueryServiceStatus(hService.get(), &status))
        {
            ErrorLogLastErr(TSTR("QueryServiceStatus[%s] fail"), name.c_str());
            break;
        }

        if (SERVICE_RUNNING == status.dwCurrentState)
        {
            bReturn = true;
            break;
        }

        if (SERVICE_START_PENDING != status.dwCurrentState)
        {
            if (!StartService(hService.get(), 0, NULL))
            {
                CLastErrorFormat e;
                if (ERROR_SERVICE_ALREADY_RUNNING == e.code())
                {
                    DebugLog("service is already running");
                    bReturn = true;
                }
                else
                {
                    ErrorLogLastErrEx(e, TSTR("StartService[%s] fail"), name.c_str());
                }
                break;
            }
        }

        const DWORD interval_ms = 500;//ÿ500ºÁÃë¼ì²âÒ»´Î
        DWORD total_ms = timeout_ms > interval_ms ? timeout_ms : interval_ms;
        DWORD total_count = total_ms / interval_ms;
        for (DWORD index = 0; index != total_count; ++index)
        {
            if (!QueryServiceStatus(hService.get(), &status))
            {
                ErrorLogLastErr(TSTR("QueryServiceStatus[%s] fail"), name.c_str());
                break;
            }

            if (SERVICE_START_PENDING == status.dwCurrentState)
            {
                DebugLog("SERVICE_START_PENDING");
                Sleep(interval_ms);
            }
            else
            {
                break;
            }
        }

        if (SERVICE_RUNNING != status.dwCurrentState)
        {
            ErrorLog(TSTR("start service[%s] fail, current status: %lu, %s"),
                name.c_str(), status.dwCurrentState, service_status_str(status.dwCurrentState));
            break;
        }

        bReturn = true;

    } while (false);

    InfoLog(TSTR("StartupService[%s] end"), name.c_str());
    return bReturn;
}
Exemplo n.º 25
0
bool cmd_run_as(const tstring& command,
                const RUN_AS_TYPE& as_type,
                const bool show_window /*= true*/)
{
    InfoLog("begin exec");

    bool execute_success = false;
    const unsigned short sw_flag = show_window ? SW_SHOWNORMAL : SW_HIDE;

    std::vector<HANDLE> processes;

    switch (as_type)
    {
    case AS_LOCAL:
        {
            DWORD created_pid = 0;
            HANDLE hProcess = ProcessCreator::create_process_in_local_context(command,
                created_pid, CREATE_NEW_CONSOLE, TSTR(""), sw_flag);
            if (hProcess)
            {
                InfoLog("create_process_in_local_context success, pid=%lu", created_pid);
                processes.push_back(hProcess);
            }
            else
            {
                ErrorLog("create_process_in_local_context fail");
            }
        }
        break;

    case AS_LOGON_USER:
    case AS_ALL_LOGON_USERS:
        {
            std::vector<DWORD> pids;
            find_pids_by_path(TSTR("explorer.exe"), pids);
            if (pids.empty())
            {
                ErrorLog("can not find any explorer.exe");
            }
            else
            {
                for (std::vector<DWORD>::const_iterator iter_pid = pids.begin();
                    iter_pid != pids.end();
                    ++iter_pid)
                {
                    InfoLog("explorer.exe pid=%lu", *iter_pid);
                    DWORD created_pid = 0;
                    HANDLE hProcess = ProcessCreator::create_process_as_same_token(*iter_pid,
                        command, created_pid, CREATE_NEW_CONSOLE, TSTR(""), sw_flag);
                    if (hProcess)
                    {
                        InfoLog("create_process_as_same_token success, pid=%lu", created_pid);
                        processes.push_back(hProcess);
                        if (as_type == AS_LOGON_USER)
                        {
                            break;
                        }
                    }
                    else
                    {
                        ErrorLog(TSTR("create_process_as_same_token fail, pid=%lu, cmd=[%s]"),
                            *iter_pid, command.c_str());
                    }
                }
            }

            if (processes.empty())
            {
                ErrorLog("no new process in user context was created");
            }
        }
        break;

    default:
        ErrorLog("unknown run_as type: %d", as_type);
        break;
    }

    if (!processes.empty())
    {
        //最多伺候3秒,不必看结果,让守护进程去看
        WaitForMultipleObjects(processes.size(), &processes[0], TRUE, 3 * 1000);
        for (std::vector<HANDLE>::iterator iter_process = processes.begin();
            iter_process != processes.end();
            ++iter_process)
        {
            CloseHandle(*iter_process);
            *iter_process = NULL;
        }

        execute_success = true;
    }
    else
    {
        execute_success = false;
    }

    InfoLog("end exec with %s", execute_success ? "success" : "fail");
    return execute_success;
}
Exemplo n.º 26
0
bool ServiceUtil::stop(const tstring& name, const DWORD timeout_ms)
{
    InfoLog(TSTR("StopService[%s] begin"), name.c_str());
    bool bReturn = false;

    do 
    {
        scoped_svc_handle hService(name, GENERIC_ALL, GENERIC_EXECUTE | GENERIC_READ);
        if (!hService.valid())
        {
            break;
        }

        SERVICE_STATUS status = {0};
        if (!QueryServiceStatus(hService.get(), &status))
        {
            ErrorLogLastErr(TSTR("QueryServiceStatus[%s] fail"), name.c_str());
            break;
        }

        if (SERVICE_STOPPED == status.dwCurrentState)
        {
            bReturn = true;
            break;
        }

        if (SERVICE_STOP_PENDING != status.dwCurrentState)
        {
            if (!ControlService(hService.get(), SERVICE_CONTROL_STOP, &status))
            {
                ErrorLogLastErr(TSTR("ControlService[%s] for stopping fail"), name.c_str());
                break;
            }
        }

        const DWORD interval_ms = 500;//ÿ500ºÁÃë¼ì²âÒ»´Î
        DWORD total_ms = timeout_ms > interval_ms ? timeout_ms : interval_ms;
        DWORD total_count = total_ms / interval_ms;
        for (DWORD index = 0; index != total_count; ++index)
        {
            if (!QueryServiceStatus(hService.get(), &status))
            {
                ErrorLogLastErr(TSTR("QueryServiceStatus[%s] fail"), name.c_str());
                break;
            }

            if (SERVICE_RUNNING == status.dwCurrentState)
            {
                DebugLog("SERVICE_RUNNING");
                Sleep(interval_ms);
            }
            else if (SERVICE_STOP_PENDING == status.dwCurrentState)
            {
                DebugLog("SERVICE_STOP_PENDING");
                Sleep(interval_ms);
            }
            else
            {
                break;
            }
        }

        if (SERVICE_STOPPED != status.dwCurrentState)
        {
            ErrorLog(TSTR("stop service[%s] fail, current status: %lu, %s"),
                name.c_str(), status.dwCurrentState, service_status_str(status.dwCurrentState));
            break;
        }

        bReturn = true;

    } while (false);

    InfoLog(TSTR("StopService[%s] end"), name.c_str());
    return bReturn;
}
Exemplo n.º 27
0
bool GameDBChannel::InitUserInMemory(ClanManager* clanMgr, UserManager* userMgr)
{
    char query[1024] = { 0, };
    sprintf(query,
            SELECT_ALL_CLAN_QUERY);
    
    MYSQL_RES* resultSet = NULL;
    _dbConn.ProcessResultQuery(query, &resultSet);
    
    
    
    if (resultSet)
    {
        MYSQL_ROW row;
        
        ClanInfo clanInfo;
        
        while ((row = mysql_fetch_row(resultSet)) != NULL)
        {
            mysql_field_seek(resultSet, 0);
            
            if (mysql_num_fields(resultSet) != CLAN_FIELD_COUNT)
            {
                ErrorLog("the retrieved field is incorrect, fields:%d", mysql_num_fields(resultSet));
                mysql_free_result(resultSet);
                return false;
            }
            
            memset(&clanInfo, 0, sizeof(ClanInfo));
            
            if (row[CLAN_CLAN_NO]) clanInfo.clanNo = atoi(row[CLAN_CLAN_NO]);
            if (row[CLAN_CLAN_NAME])
            {
                strcpy(clanInfo.clanName, row[CLAN_CLAN_NAME]);
                clanInfo.clanNameLen = strlen(row[CLAN_CLAN_NAME]);
            }
            if (row[CLAN_WIN]) clanInfo.win = atoi(row[CLAN_WIN]);
            if (row[CLAN_LOSE]) clanInfo.lose = atoi(row[CLAN_LOSE]);
            if (row[CLAN_POINT]) clanInfo.point = atoi(row[CLAN_POINT]);

            if (clanMgr->addClan(&clanInfo) != SUCCESS)
            {
                ErrorLog("AddClan error");
                mysql_free_result(resultSet);
                return false;
            }
        }
        
        mysql_free_result(resultSet);
    }
    
    char query1[1024] = { 0, };
    sprintf(query1,
            SELECT_ALL_USER_QUERY);

    resultSet = NULL;
    _dbConn.ProcessResultQuery(query1, &resultSet);

    if (resultSet)
    {
        MYSQL_ROW row;

		UserInfo userInfo;
        
        while ((row = mysql_fetch_row(resultSet)) != NULL)
        {
            mysql_field_seek(resultSet, 0);

            if (mysql_num_fields(resultSet) != USER_FIELD_COUNT)
            {
                ErrorLog("the retrieved field is incorrect, fields:%d", mysql_num_fields(resultSet));
                mysql_free_result(resultSet);
                return false;
            }

            memset(&userInfo, 0, sizeof(UserInfo));
            
            if (row[USER_USER_NO]) userInfo.userNo = atoll(row[USER_USER_NO]);
            if (row[USER_NICK_NAME])
            {
                strcpy(userInfo.nickName, row[USER_NICK_NAME]);
                userInfo.nickNameLen = strlen(row[USER_NICK_NAME]);
            }
            if (row[USER_COMMON_WIN]) userInfo.commonWin = atoi(row[USER_COMMON_WIN]);
            if (row[USER_COMMON_LOSE]) userInfo.commonLose = atoi(row[USER_COMMON_LOSE]);
            if (row[USER_COMMON_DISS]) userInfo.commonDiss = atoi(row[USER_COMMON_DISS]);
            if (row[USER_RANK_WIN]) userInfo.rankWin = atoi(row[USER_RANK_WIN]);
            if (row[USER_RANK_LOSE]) userInfo.rankLose = atoi(row[USER_RANK_LOSE]);
            if (row[USER_RANK_DISS]) userInfo.rankDiss = atoi(row[USER_RANK_DISS]);
            if (row[USER_GRADE]) userInfo.grade = atoi(row[USER_GRADE]);
            if (row[USER_GRADE_REACHED_COUNT]) userInfo.gradeReachedCount = atoi(row[USER_GRADE_REACHED_COUNT]);
            if (row[USER_POINT]) userInfo.point = atoi(row[USER_POINT]);
            if (row[USER_COIN]) userInfo.coin = atoi(row[USER_COIN]);
            if (row[USER_CLAN_NO]) userInfo.clanNo = atoi(row[USER_CLAN_NO]);
            if (row[USER_CLAN_CLASS]) userInfo.clanClass = atoi(row[USER_CLAN_CLASS]);

            if (userMgr->addUser(std::string(row[USER_USER_ID], strlen(row[USER_USER_ID])), &userInfo) != SUCCESS)
            {
                ErrorLog("AddUser error");
                mysql_free_result(resultSet);
                return false;
            }

            char userId[100] = {0, };
            strcpy(userId, row[USER_USER_ID]);
            
            User* user = userMgr->getUserByUserId(std::string(row[USER_USER_ID], strlen(row[USER_USER_ID])));

            if (user == NULL)
            {
                ErrorLog("user is null ");
                mysql_free_result(resultSet);
                return false;
            }
            if(userInfo.clanNo != 0)
            {
                Clan* clan = clanMgr->getClanByClanNo(userInfo.clanNo);
                
                if(clan == NULL)
                {
                    ErrorLog("clan is null");
                    mysql_free_result(resultSet);
                    return false;
                }
                if(clan->addUser(user) != SUCCESS)
                {
                    ErrorLog("adduser error");
                    mysql_free_result(resultSet);
                    return false;
                }
            }
        }

        mysql_free_result(resultSet);
    }
    
    char query2[1024] = { 0, };
    sprintf(query2,
            SELECT_ALL_FRIEND_QUERY);
    
    resultSet = NULL;
    _dbConn.ProcessResultQuery(query2, &resultSet);
    
    if (resultSet)
    {
        MYSQL_ROW row;
        
        User* user1 = NULL;
        User* user2 = NULL;

        while ((row = mysql_fetch_row(resultSet)) != NULL)
        {
            mysql_field_seek(resultSet, 0);
            
            if (mysql_num_fields(resultSet) != FRIEND_FIELD_COUNT)
            {
                ErrorLog("the retrieved field is incorrect, fields:%d", mysql_num_fields(resultSet));
                mysql_free_result(resultSet);
                return false;
            }
            
            if (row[FRIEND_F1])
            {
                user1 = userMgr->getUserByUserNo(atoll(row[FRIEND_F1]));
                if(user1 == NULL)
                {
                    ErrorLog("getUserByUserNo error");
                    mysql_free_result(resultSet);
                    return false;
                }
            }
            
            if (row[FRIEND_F2])
            {
                user2 = userMgr->getUserByUserNo(atoll(row[FRIEND_F2]));
                if(user2 == NULL)
                {
                    ErrorLog("getUserByUserNo error");
                    mysql_free_result(resultSet);
                    return false;
                }
            }
            
            if(userMgr->setFriend(user1, user2) == false)
            {
                ErrorLog("setFriend error");
                mysql_free_result(resultSet);
                return false;
            }
        }
        
        mysql_free_result(resultSet);
    }


    return true;
}
Exemplo n.º 28
0
void CProcNonExistTask::worker_func()
{
    exception_catcher::set_thread_exception_handlers();
    InfoLog("proc non exist task worker thread func begin");

    while (true)
    {
        std::vector<DWORD> pids;
        //todo: is exactly_match=false correct ?????
        find_pids_by_path(m_proc_path, pids, true, false);

        if (pids.empty())//non exist
        {
            InfoLog(TSTR("can not find process[%s], try to execute function if has"), m_proc_path.c_str());
            if (m_f)
            {
                try
                {
                    m_f();
                }
                catch (...)
                {
                    ErrorLog("execute proc non exist task function exception");
                }
            }

            //sleep some while if function has done something which will effect later on
            const DWORD wait_result = WaitForSingleObject(m_exit_event.get_ref(), 1000);
            if (WAIT_OBJECT_0 == wait_result)
            {
                InfoLog("got exit notify");
                break;
            }
        }
        else//exist
        {
            const DWORD pid = pids.at(0);
            scoped_handle<> hProcess(OpenProcess(SYNCHRONIZE, FALSE, pid));
            if (!hProcess.valid())
            {
                ErrorLogLastErr("OpenProcess[%lu] fail", pid);

                const DWORD wait_result = WaitForSingleObject(m_exit_event.get_ref(), m_interval_seconds * 1000);
                if (WAIT_OBJECT_0 == wait_result)
                {
                    InfoLog("got exit notify");
                    break;
                }
            }
            else
            {
                bool should_break = false;

                HANDLE pHandles[2] = {m_exit_event.get_ref(), hProcess.get_ref()};
                const DWORD wait_result = WaitForMultipleObjects(sizeof(pHandles) / sizeof(pHandles[0]),
                    pHandles, FALSE, INFINITE);
                switch (wait_result)
                {
                case WAIT_OBJECT_0:
                    InfoLog("got exit notify");
                    should_break = true;
                    break;

                case WAIT_OBJECT_0 + 1:
                    InfoLog(TSTR("process[%s] exited"), m_proc_path.c_str());
                    break;

                default:
                    ErrorLogLastErr("WaitForMultipleObjects fail, return code: %lu", wait_result);
                    //sleep some while for recover from error state
                    if (WAIT_OBJECT_0 == WaitForSingleObject(m_exit_event.get_ref(), 1000))
                    {
                        InfoLog("got exit notify");
                        should_break = true;
                    }
                    break;
                }

                if (should_break)
                {
                    break;
                }
            }
        }
    }

    InfoLog("proc non exist task worker thread func end");
}
Exemplo n.º 29
0
void CDriveBoard::LoadState(CBlockFile *SaveState)
{
	if (SaveState->FindBlock("DriveBoard") != OKAY)
	{
		ErrorLog("Unable to load drive board state. Save state file is corrupt.");
		return;
	}
	
	// Check that board was attached in saved state
	bool wasAttached;
	SaveState->Read(&wasAttached, sizeof(wasAttached));
	if (wasAttached)
	{
		// Check that board configuration exactly matches current configuration
		bool wasSimulated;
		SaveState->Read(&wasSimulated, sizeof(wasSimulated));
		if (wasAttached == m_attached && wasSimulated == m_simulated)
		{
			// Check if board was simulated
			if (wasSimulated)
			{
				// TODO - load board simulation state
			}
			else
			{
				// Load DIP switches and digit displays
				SaveState->Read(&m_dip1, sizeof(m_dip1));
				SaveState->Read(&m_dip2, sizeof(m_dip2));
				//SaveState->Read(&m_seg1Digit1, sizeof(m_seg1Digit1));
				//SaveState->Read(&m_seg1Digit2, sizeof(m_seg1Digit2));
				//SaveState->Read(&m_seg2Digit1, sizeof(m_seg2Digit1));
				//SaveState->Read(&m_seg2Digit2, sizeof(m_seg2Digit2));

				// Load RAM state
				SaveState->Read(m_ram, RAM_SIZE);
				
				// Load interrupt and input/output state
				SaveState->Read(&m_initialized, sizeof(m_initialized));
				SaveState->Read(&m_allowInterrupts, sizeof(m_allowInterrupts));
				SaveState->Read(&m_dataSent, sizeof(m_dataSent));
				SaveState->Read(&m_dataReceived, sizeof(m_dataReceived));
				SaveState->Read(&m_adcPortRead, sizeof(m_adcPortRead));
				SaveState->Read(&m_adcPortBit, sizeof(m_adcPortBit));
				SaveState->Read(&m_uncenterVal1, sizeof(m_uncenterVal1));
				SaveState->Read(&m_uncenterVal2, sizeof(m_uncenterVal2));
			
				// Load CPU state
				m_z80.LoadState(SaveState, "DriveBoard Z80");
			}

			// Enable board
			m_tmpDisabled = false;
		}
		else
		{
			// Otherwise, disable board as it can't be used with a mismatching configuratin
			m_tmpDisabled = true;
		}
	}
	else
		// Disable board if it was not attached
		m_tmpDisabled = true;

	if (m_attached)
	{
		if (m_tmpDisabled)
			printf("Disabled drive board due to incompatible save state.\n");

		SendStopAll();
	}
}
Exemplo n.º 30
0
void *
restoreDbFromTape(void *param)
{
    afs_uint32 taskId = (intptr_t) param;
    afs_int32 code = 0;
    afs_int32 i;
    struct butm_tapeInfo tapeInfo;
    struct rstTapeInfo rstTapeInfo;
    struct budb_dumpEntry dumpEntry;

    extern struct tapeConfig globalTapeConfig;
    extern struct deviceSyncNode *deviceLatch;

    setStatus(taskId, DRIVE_WAIT);
    EnterDeviceQueue(deviceLatch);	/* lock tape device */
    clearStatus(taskId, DRIVE_WAIT);

    printf("\n\n");
    TLog(taskId, "RestoreDb\n");

    tapeInfo.structVersion = BUTM_MAJORVERSION;
    code = butm_file_Instantiate(&tapeInfo, &globalTapeConfig);
    if (code) {
	ErrorLog(0, taskId, code, tapeInfo.error,
		 "Can't initialize tape module\n");
	ERROR_EXIT(code);
    }

    listEntryHead = NULL;

    rstTapeInfo.taskId = taskId;
    rstTapeInfo.tapeSeq = 1;
    rstTapeInfo.dumpid = 0;

    code = readDbTape(&tapeInfo, &rstTapeInfo, autoQuery);
    if (code)
	ERROR_EXIT(code);

    code = restoreDbEntries(&tapeInfo, &rstTapeInfo);
    if (code)
	ERROR_EXIT(code);

  error_exit:
    /* Now put this dump into the database */
    /* Make a dump entry from first tape   */
    listEntryPtr = listEntryHead;
    if (listEntryPtr) {
	makeDbDumpEntry(tapeEntryPtr, &dumpEntry);
	if (dumpEntry.id != 0) {
	    i = bcdb_CreateDump(&dumpEntry);
	    if (i) {
		if (i == BUDB_DUMPIDEXISTS)
		    fprintf(stderr,
			    "Dump id %d not added to database - already exists\n",
			    dumpEntry.id);
		else
		    TapeLog(0, taskId, i, 0,
			    "Dump id %d not added to database\n",
			    dumpEntry.id);
	    } else {
		i = addTapesToDb(taskId);
		if (!code)
		    code = i;

		i = bcdb_FinishDump(&dumpEntry);
		if (!code)
		    code = i;
	    }
	}
	freeTapeList();
    }

    unmountTape(taskId, &tapeInfo);
    waitDbWatcher();

    if (code == TC_ABORTEDBYREQUEST) {
	TLog(taskId, "RestoreDb: Aborted by request\n");
	clearStatus(taskId, ABORT_REQUEST);
	setStatus(taskId, ABORT_DONE);
    } else if (code) {
	TapeLog(0, taskId, code, 0, "RestoreDb: Finished with errors\n");
	setStatus(taskId, TASK_ERROR);
    } else {
	TLog(taskId, "RestoreDb: Finished\n");
    }

    LeaveDeviceQueue(deviceLatch);
    setStatus(taskId, TASK_DONE);

    return (void *)(intptr_t)(code);
}