Example #1
0
void HttpBase::Post(IHttpHandler * handler, const char * url, const char * field) {
	SafeSprintf(_url, sizeof(_url), "%s", url);
	SafeSprintf(_field, sizeof(_field), "%s", field);
	_type = HT_POST;
	handler->SetBase(this);
	_handler = handler;
}
Example #2
0
void Redis::Append(CommandBuff& buf, float val) {
	char temp[32] = { 0 };
	SafeSprintf(temp, sizeof(temp), "%.2f", val);

	SafeSprintf(buf.data + buf.size, sizeof(buf.data) - buf.size, "$%d\r\n%s\r\n", (s32)strlen(temp), temp);
	buf.size += (s32)strlen(buf.data + buf.size);
}
Example #3
0
//初始化 
bool __cdecl CTableFrameSink::InitTableFrameSink(IUnknownEx * pIUnknownEx)
{
	//查询接口
	ASSERT(pIUnknownEx!=NULL);
	m_pITableFrame=QUERY_OBJECT_PTR_INTERFACE(pIUnknownEx,ITableFrame);
	if (m_pITableFrame==NULL) return false;

	//控制接口 
	m_pITableFrameControl=QUERY_OBJECT_PTR_INTERFACE(pIUnknownEx,ITableFrameControl);
	if (m_pITableFrameControl==NULL) return false;

	m_pITableFrameManager=QUERY_OBJECT_PTR_INTERFACE(pIUnknownEx,ITableFrameManager);
	if (m_pITableFrameControl==NULL) return false;
	//获取参数
	m_pGameServiceOption=m_pITableFrame->GetGameServiceOption();
	ASSERT(m_pGameServiceOption!=NULL);
	

	char szLogFileName[1024] = {0};
	SafeSprintf(szLogFileName,"%02d-桌子",(m_pITableFrame->GetTableID()+1));
	char szLogDir[128]={0};
	SafeSprintf(szLogDir,"%d[%s]",m_pGameServiceOption->wServerID,m_pGameServiceOption->szGameRoomName);
	m_lCellScore = m_pGameServiceOption->lCellScore;
	m_oLog.Init("Ratiox",szLogDir,szLogFileName);
	m_oLog.Log("==日志启动完毕==");

	ReadIniCfg();
	m_pITableFrame->SetGameTimer(IDI_TIME_READCFG , 5*60*1000 , -1 , 0);
	m_oContral.Init(m_pITableFrame , &m_oLog , m_pGameServiceOption->lCellScore , m_pGameServiceOption->wRevenue);
	srand((unsigned)time(NULL));
	UpdateTask();
	return true;
}
Example #4
0
HXBOOL CHXGUID::Get(char* pBuffer, INT32 bufLen)
{
#if !defined(HELIX_FEATURE_FULLGUID)
    HXBOOL bRet = FALSE;

    if (pBuffer && strlen(pBuffer) > 8)
    {
        // GUID is an enum
        SafeSprintf(pBuffer, bufLen,"%.8lX",m_guid);
    }

    return bRet;
#else /* #if defined(_STATICALLY_LINKED) && !defined(HELIX_FEATURE_FULLGUID) */
    if (bufLen < sizeof(GUID) * 2 + 4)
	return(FALSE);

    // Write out the first 3 Data fields seperated by dashes and then move to the end of the buffer
    SafeSprintf(pBuffer, bufLen,"%.8lX-%.4hX-%.4hX-",m_guid.Data1,m_guid.Data2,m_guid.Data3);
    bufLen -= strlen(pBuffer); pBuffer += strlen(pBuffer);

    // Loop through the characters in the 4th data field printing them into the buffer
    for (int i=0; i < CHARS_FOR_GUID_DATA4; i++)
    {
	SafeSprintf(pBuffer, bufLen,"%.2lX",(UINT32)m_guid.Data4[i]);
	pBuffer += 2;
        bufLen -= 2;
    }

    return(TRUE);
#endif /* #if defined(_STATICALLY_LINKED) && !defined(HELIX_FEATURE_FULLGUID) #else */
}
Example #5
0
void Redis::Append(CommandBuff& buf, const void * val, const s32 size) {
	SafeSprintf(buf.data + buf.size, sizeof(buf.data) - buf.size, "$%d\r\n", size);
	buf.size += (s32)strlen(buf.data + buf.size);

	SafeMemcpy(buf.data + buf.size, sizeof(buf.data) - buf.size, val, size);
	buf.size += size;
	SafeSprintf(buf.data + buf.size, sizeof(buf.data) - buf.size, "\r\n");
	buf.size += (s32)strlen(buf.data + buf.size);
}
Example #6
0
	void ListFileInDirection(const char * path, const char * extension, const std::function<void(const char *, const char *)> &f) {
#ifdef WIN32
		WIN32_FIND_DATA finder;

		char tmp[512] = { 0 };
		SafeSprintf(tmp, sizeof(tmp), "%s/*.*", path);

		HANDLE handle = FindFirstFile(path, &finder);
		if (INVALID_HANDLE_VALUE == handle)
			return;

		while (FindNextFile(handle, &finder)) {
			if (strcmp(finder.cFileName, ".") == 0 || strcmp(finder.cFileName, "..") == 0)
				continue;

			SafeSprintf(tmp, sizeof(tmp), "%s/%s", path, finder.cFileName);
			if (finder.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				ListFileInDirection(tmp, extension, f);
			else {
				if (0 == strcmp(extension, PathFindExtension(finder.cFileName))) {
					PathRemoveExtension(finder.cFileName);
					f(finder.cFileName, tmp);
				}
			}
		}
#else
		DIR * dp = opendir(path);
		if (dp == nullptr)
			return;

		struct dirent * dirp;
		while ((dirp = readdir(dp)) != nullptr) {
			if (dirp->d_name[0] == '.')
				continue;

			char tmp[256] = { 0 };
			SafeSprintf(tmp, sizeof(tmp), "%s/%s", path, dirp->d_name);

			struct stat st;
			if (stat(tmp, &st) == -1)
				continue;

			if (S_ISDIR(st.st_mode))
				ListFileInDirection(tmp, extension, f);
			else {
				if (0 == strcmp(extension, GetFileExt(dirp->d_name))) {
					char name[256];
					SafeSprintf(name, sizeof(name), "%s", dirp->d_name);
					char * dot = strrchr(name, '.');
					if (dot != nullptr)
						*dot = 0;
					f(name, tmp);
				}
			}
		}
#endif
	}
Example #7
0
const char*
SMPTETimeCode::toString()
{
    char strBuf[12]; /* Flawfinder: ignore */
    SafeSprintf(strBuf, sizeof(strBuf), "%02d:%02d:%02d",
                m_hour, m_minute, m_second);
    if(m_frame > 0)
        SafeSprintf(&strBuf[8], sizeof(strBuf)-8, ".%02d", m_frame);
    m_asString = strBuf;
    return m_asString;
}
Example #8
0
void Slave::StartNode(IKernel * kernel, const char * cmd) {
	char process[MAX_CMD_LEN];
#ifdef WIN32
	SafeSprintf(process, sizeof(process), "%s/%s.exe", tools::GetAppPath(), EXECUTE_NAME);

	STARTUPINFO si = { sizeof(si) };
	si.dwFlags = STARTF_USESHOWWINDOW;
	si.wShowWindow = TRUE;
	si.lpTitle = (char*)cmd;

	PROCESS_INFORMATION pi;
	BOOL ret = CreateProcess(process, (char*)cmd, nullptr, nullptr, false, CREATE_NEW_CONSOLE, nullptr, nullptr, &si, &pi);
	OASSERT(ret, "create process failed");
	::CloseHandle(pi.hThread);
	::CloseHandle(pi.hProcess);
#else
	SafeSprintf(process, sizeof(process), "%s/%s", tools::GetAppPath(), EXECUTE_NAME);

	char args[MAX_CMD_LEN];
	SafeSprintf(args, sizeof(args), cmd);

	char * p[MAX_CMD_ARGS_COUNT];
	SafeMemset(p, sizeof(p), 0, sizeof(p));
	p[0] = EXECUTE_NAME;
	s32 idx = 1;
	char * checkPtr = args;
	char * innderPtr = nullptr;
	while ((p[idx] = strtok_r(checkPtr, " ", &innderPtr)) != nullptr) {
		++idx;
		checkPtr = nullptr;
	}

	pid_t pid;
	pid = fork();
	if (pid < 0) {
		OASSERT(false, "start process failed");
	}
	else if (pid == 0) {
		pid = fork();
		if (pid == 0)
			execv(process, p);
		else
			exit(0);
	}
	else {
		s32 status;
		waitpid(pid, &status, 0);
	}
#endif
}
Example #9
0
void Battle::requestpve() {
    g_pEventEngine->BundlerCall(BUND_ID_PLANE_HOLD_FIRE, this, sizeof(this));
    char szUrl[256] = {0};
    SafeSprintf(szUrl, sizeof(szUrl), SERVER::countpve_url, g_uid.c_str(), g_token.c_str(), 10);
    g_pHttpEngine->HGetRequest(HTTP_REQUEST_ID_COUNT_PVE, szUrl, this, NULL, 0);
    unschedule(schedule_selector(Battle::collidtion));
}
Example #10
0
void
HSPErrorSink::ConvertErrorToString(const ULONG32 ulHXCode, char* pszBuffer, UINT32 ulBufLen)
{
    IHXErrorMessages* pErrMsg = NULL;

    if( !pszBuffer)
        return;
    
    pszBuffer[0]='\0';


    HX_ASSERT(m_pPlayer);
    if( m_pPlayer)
    {
        m_pPlayer->QueryInterface(IID_IHXErrorMessages, (void**)&pErrMsg);
        if( pErrMsg )
        {
            IHXBuffer* pMessage = pErrMsg->GetErrorText(ulHXCode);
            if( pMessage )
            {
                SafeStrCpy( pszBuffer, (const char*)pMessage->GetBuffer(), (int)ulBufLen);
                pMessage->Release();
            }
        }
    }
 
    HX_RELEASE(pErrMsg);
 
    if( strlen(pszBuffer)==0 )
    {
        SafeSprintf( pszBuffer, (int) ulBufLen, "Can't convert error code %p - please find corresponding HXR code in common/include/hxresult.h", ulHXCode );
    }

}
Example #11
0
void CNet::DealAcceptEvent(struct iocp_event * pEvent) {
    ASSERT(m_szCallAddress[CALL_REMOTE_CONNECTED]);
    if (m_szCallAddress[CALL_REMOTE_CONNECTED] != NULL) {
        if (ERROR_SUCCESS == pEvent->nerron) {
            s32 nConnectID = m_ConnectPool.CreateID();

            m_ConnectPool[nConnectID]->s = pEvent->s;
            SafeSprintf(m_ConnectPool[nConnectID]->szIP, sizeof(m_ConnectPool[nConnectID]->szIP),
                "%s", inet_ntoa(pEvent->remote.sin_addr));
            m_ConnectPool[nConnectID]->nPort = ntohs(pEvent->remote.sin_port);

            m_szCallAddress[CALL_REMOTE_CONNECTED](nConnectID, pEvent->p, 0);

            pEvent->event = EVENT_ASYNC_RECV;
            pEvent->wbuf.buf = pEvent->buff;
            pEvent->wbuf.len = sizeof(pEvent->buff);
            m_ConnectPool[nConnectID]->pContext = pEvent->p;
            pEvent->p = m_ConnectPool[nConnectID];
            s32 err;
            if (ERROR_NO_ERROR != async_recv(pEvent, &err, pEvent->p)) {
                NET_ERROR("async_recv error %d code %d", err, pEvent->nerron);
                SafeShutdwon(pEvent, CSD_BOTH);
                return;
            }
        } else {
            safe_close(pEvent);
        }
    }
}
Example #12
0
int
Windows_dir_list::is_empty()
{
    int isEmpty = 1;
    char		new_path[_MAX_PATH+10]; /* Flawfinder: ignore */
    HANDLE		f_handle = INVALID_HANDLE_VALUE;

    WIN32_FIND_DATA 	f_info;

    SafeSprintf(new_path, _MAX_PATH+10, "%s/*.*", _path);

    f_handle = FindFirstFile(OS_STRING(new_path), &f_info);

    if (f_handle == INVALID_HANDLE_VALUE)
    {
	do
	{
	    if (valid_file_name(OS_STRING(f_info.cFileName)))
		isEmpty = 0;
	}
	while (isEmpty && (FindNextFile(f_handle, &f_info) != 0));
	
    }
    else
	_error = EINVAL;

    FindClose(f_handle);

    return isEmpty;
}
BOOL TimeDriver::DateTimeToString( const INT64& time, LPSTR& buf, size_t& len )
{
    SYSTEMTIME st;

    ToSystemTime( time, &st );

    return SafeSprintf( buf, len, "%4d/%02d/%02d %02d:%02d:%02d.%03d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds );
}
Example #14
0
const char*
NPTime::toString()
{
    char strBuf[80]; /* Flawfinder: ignore */

    if(m_lMicroSecond > 0)
    {
        HX_ASSERT(m_lMicroSecond < USECS_PER_SEC);
        SafeSprintf(strBuf, sizeof(strBuf), "%ld.%06d", m_lSecond, m_lMicroSecond);
    }
    else
    {
	SafeSprintf(strBuf, sizeof(strBuf), "%ld", m_lSecond);
    }
    m_asString = strBuf;
    return m_asString;
}
Example #15
0
extern void sprintsym( SYMBOL sym, char s[], int sBufLen)
{
    char ctype[80]; /* Flawfinder: ignore */
    
    sprinttype( sym.type, ctype, 80);
    SafeSprintf(s, sBufLen, "%s =%4d", ctype, sym.value);
    return;
}
Example #16
0
void Gate::BuildToken(char * token, s32 size, const TokenData& data) {
	char checkBuf[1024];
	SafeMemcpy(checkBuf, sizeof(checkBuf), &data, sizeof(TokenData));
	SafeSprintf(checkBuf + sizeof(TokenData), sizeof(checkBuf) - sizeof(TokenData), "%s", _tokenKey.GetString());

	MD5 md5;
	md5.update(checkBuf, sizeof(TokenData) + _tokenKey.Length());
	std::string sign = md5.toString();

	char buf[1024];
	SafeMemcpy(buf, sizeof(buf), &data, sizeof(TokenData));
	SafeSprintf(buf + sizeof(TokenData), sizeof(buf) - sizeof(TokenData), "%s", sign.c_str());

	u32 outSize = size;
	s32 ret = Base64Encode((u8*)buf, (u32)(sizeof(TokenData) + sign.size()), token, &outSize);
	OASSERT(ret == BASE64_OK, "wtf");
	token[outSize] = 0;
}
Example #17
0
bool ObjectMgr::Initialize(IKernel * kernel) {
	_kernel = kernel;
	_nextTypeId = 1;

	char path[512] = { 0 };
	SafeSprintf(path, sizeof(path), "%s/config/object.xml", tools::GetAppPath());
	olib::XmlReader conf;
	if (!conf.LoadXml(path)) {
		OASSERT(false, "load object.xml failed");
		return false;
	}

	if (conf.Root().IsExist("prop")) {
		const olib::IXmlObject& props = conf.Root()["prop"];
		for (s32 i = 0; i < props.Count(); ++i)
			_defines[props[i].GetAttributeString("name")] = (1 << i);
	}

	if (conf.Root().IsExist("table")) {
		const olib::IXmlObject& tables = conf.Root()["table"];
		for (s32 i = 0; i < tables.Count(); ++i) {
			TableDescriptor * tableModel = NEW TableDescriptor();
			const char * name = tables[i].GetAttributeString("name");
			if (!tableModel->LoadFrom(tables[i]))
				return false;

			_tableModels[tools::CalcStringUniqueId(name)] = tableModel;
		}
	}
    
    SafeSprintf(path, sizeof(path), "%s/config/dccenter/", tools::GetAppPath());
	tools::ListFileInDirection(path, ".xml", [this](const char * name, const char * path) {
		if (_namePathMap.end() != _namePathMap.find(name)) {
			OASSERT(false, "prop xml name repeated");
			return;
		}
		_namePathMap.insert(std::make_pair(name, path));
	});

	for (auto itr = _namePathMap.begin(); itr != _namePathMap.end(); ++itr)
		CreateTemplate(kernel, itr->first.GetString());

    return true;
}
Example #18
0
  STRING ceefit_call_spec FIXTURE::RUNTIME::d(fitINT64 scale) const
  {
    fitINT64 report = elapsed / scale;
    elapsed -= report * scale;

    STRING out;
    SafeSprintf(out, L"%lld", report);

    return out;
  }
Example #19
0
//  Parse bitstring "vlc", return length in "bits" and value in "codeword"
static int parse_bits(  char vlc[],     /* String with bit pattern */
                        int strmax,     /* Max characters in "vlc" excluding terminating null */
                        int maxbits,    /* Max # bits in codeword */
                        int * bits,     /* Returns # bits; 0 < bits < maxbits+1 */
                        int * codeword, /* Returns codeword */
                        int minBits     // Min # bits in codeword
)
{
    int j, c;
    char msg[120]; /* Flawfinder: ignore */
    
    *bits = 0, j = 0, *codeword = 0;
    c = vlc[j];
    while (c != 0) {
        if (c == '0'  ||  c == '1') {
            *codeword <<= 1;
            ++(*bits);
            if (c == '1') {
                ++(*codeword);
            }
        } else if (isspace(c) == 0) {   /* Found illegal character */
            SafeSprintf(msg, 120, "parse_bits - Illegal string: %s", vlc);
            H261ErrMsg( msg );
            return( H261_ERROR );
        }
        c = vlc[++j];
    }
    if (j > strmax) {
        SafeSprintf(msg, 120, "Too long string: %s", vlc);
        H261ErrMsg( msg );
        return( H261_ERROR );
    }
    if (*bits > maxbits  ||  *bits < minBits) {
        SafeSprintf(msg, 120, "Illegal string: %s", vlc);
        H261ErrMsg( msg );
        return( H261_ERROR );
    }
    return (OK);
}
Example #20
0
void Harbor::AddNodeListener(INodeListener * listener, const char * debug) {
#ifdef _DEBUG
    auto itr = std::find_if(_listeners.begin(), _listeners.end(), [listener](const NodeListenerUnit& unit) -> bool {
        return unit.listener == listener;
    });
    OASSERT(itr == _listeners.end(), "node listener is already add");
#endif
    NodeListenerUnit unit;
    unit.listener = listener;
    SafeSprintf(unit.debug, sizeof(unit.debug), debug);

    _listeners.push_back(unit);
}
Example #21
0
void Slave::StartNewNode(IKernel * kernel, const char * name, const char * cmd, const s32 nodeType, const s32 nodeId) {
	std::string tmp(cmd);
	std::string::size_type pos = tmp.find(EXECUTE_CMD_PORT);
	while (pos != std::string::npos) {
		OASSERT(_startPort < _endPort, "port is not enough");

		char portStr[64];
		SafeSprintf(portStr, sizeof(portStr), "%d", _startPort++);
		tmp.replace(pos, EXECUTE_CMD_PORT_SIZE, portStr);
	
		pos = tmp.find(EXECUTE_CMD_PORT);
	}

	pos = tmp.find(EXECUTE_CMD_OUT_PORT);
	while (pos != std::string::npos) {
		OASSERT(_startOutPort < _endOutPort, "out port is not enough");

		char portStr[64];
		SafeSprintf(portStr, sizeof(portStr), "%d", _startOutPort++);
		tmp.replace(pos, EXECUTE_CMD_OUT_PORT_SIZE, portStr);

		pos = tmp.find(EXECUTE_CMD_OUT_PORT);
	}

	pos = tmp.find(EXECUTE_CMD_ID);
	if (pos != std::string::npos) {
		char idStr[64];
		SafeSprintf(idStr, sizeof(idStr), "%d", nodeId);
		tmp.replace(pos, EXECUTE_CMD_ID_SIZE, idStr);
	}

	s64 node = (((s64)nodeType) << 32) | nodeId;
	SafeSprintf(_cmds[node].cmd, MAX_CMD_LEN, tmp.c_str());

	StartNode(kernel, _cmds[node].cmd);
}
Example #22
0
Windows_dir_list::Windows_dir_list(const char* path) :
    _file_handle(INVALID_HANDLE_VALUE),
    _cur_filename(0),
    _next_error(0),
    _path(new_string(path))
{
    char new_path[_MAX_PATH+10]; /* Flawfinder: ignore */

    SafeSprintf(new_path, _MAX_PATH+10, "%s\\*.*", _path);
    
    _file_handle = FindFirstFile(OS_STRING(new_path), &_file_info);

    if (_file_handle == INVALID_HANDLE_VALUE)
	_error = EINVAL;
}
BOOL TimeDriver::TimeSpanToString( const INT64& ticks, LPSTR& buf, size_t& len )
{
    UINT64 ticksAbs;
    UINT64 rest;

    if(ticks < 0)
    {
        ticksAbs = -ticks;

        Utility_SafeSprintf( buf, len, "-" );
    }
    else
    {
        ticksAbs = ticks;
    }

    rest      = ticksAbs % ( 1000 * TIME_CONVERSION__TICKUNITS);
    ticksAbs  = ticksAbs / ( 1000 * TIME_CONVERSION__TICKUNITS);  // Convert to seconds.

    if(ticksAbs > TIME_CONVERSION__ONEDAY) // More than one day.
    {
        Utility_SafeSprintf( buf, len, "%d.", (INT32)(ticksAbs / TIME_CONVERSION__ONEDAY) ); ticksAbs %= TIME_CONVERSION__ONEDAY;
    }

    SafeSprintf( buf, len, "%02d:", (INT32)(ticksAbs / TIME_CONVERSION__ONEHOUR)  ); ticksAbs %= TIME_CONVERSION__ONEHOUR  ;
    SafeSprintf( buf, len, "%02d:", (INT32)(ticksAbs / TIME_CONVERSION__ONEMINUTE)); ticksAbs %= TIME_CONVERSION__ONEMINUTE;
    SafeSprintf( buf, len, "%02d" , (INT32)(ticksAbs / TIME_CONVERSION__ONESECOND)); ticksAbs %= TIME_CONVERSION__ONESECOND;

    ticksAbs = (UINT32)rest;
    if(ticksAbs)
    {
        SafeSprintf( buf, len, ".%07d", (UINT32)ticksAbs );
    }

    return len != 0;
}
Example #24
0
    void CSelectModel::CConnect(const char * pStrIP, const s32 nPort, const void * pContext, const s32 nSize) {
        CSEvent * pEvent = m_EventPool.Create();
        ASSERT(pEvent);

        pEvent->nEventType = NET_EVENT_CONNECT;
        RemoteInfo info;
        SafeSprintf(info.szIP, sizeof(info.szIP), "%s", pStrIP);
        info.nPort = nPort;

        pEvent->stream.in(&info, sizeof(info));
        pEvent->stream.in(&nSize, sizeof(nSize));
        if (nSize != 0) {
            pEvent->stream.in(pContext, nSize);
        }

        m_Queue[QUEUE_TYPE_IN].add(pEvent);
    }
Example #25
0
//	Workhorse construction method
HXBOOL CAsyncNetThread::Create()
{
	char szClassName[MAX_WND_CLASS_LENGTH]; /* Flawfinder: ignore */

    SafeSprintf(szClassName, MAX_WND_CLASS_LENGTH, OS_STRING("%s%d"), 
	     WND_CLASS_BASE, &zm_bClassRegistered);

	if (!zm_bClassRegistered)
    {
	WNDCLASS internalClass;
    OS_STRING_TYPE osstrClassName(szClassName);

	//	First register our window class                                  
	internalClass.style 		= 0;
	internalClass.lpfnWndProc 	= CAsyncNetThread::AsyncNotifyProc;
	internalClass.cbClsExtra	= 0;
	internalClass.cbWndExtra	= sizeof(this);
	internalClass.hInstance		= m_hInst; // Use app's instance
	internalClass.hIcon		= 0;
	internalClass.hCursor		= 0;
	internalClass.hbrBackground	= 0;
	internalClass.lpszMenuName	= NULL;
	internalClass.lpszClassName	= osstrClassName;
	
	zm_bClassRegistered = RegisterClass(&internalClass);
	
	if(!zm_bClassRegistered)
	{
	    UnregisterClass(OS_STRING(szClassName), m_hInst);
	    zm_bClassRegistered = RegisterClass(&internalClass);
	}
    }

    //	Now create an instance of the window	
    m_hWnd = ::CreateWindow(OS_STRING(szClassName), OS_STRING("RealMedia Internal Messages"), 
		WS_OVERLAPPED, 0, 0, 0, 0, NULL, NULL, m_hInst, this);
 
    if (!m_hWnd)
    {
	return (FALSE);
    }

    return (TRUE);
}
Example #26
0
bool Gate::CheckToken(const char * token, TokenData& data, bool login) {
	u8 buf[1024];
	u32 size = 1023;
	if (BASE64_OK != Base64Decode(token, (u32)strlen(token), buf, &size))
		return false;
	buf[size] = 0;

	data = *(TokenData*)buf;
	const char * sign = (const char *)(buf + sizeof(TokenData));

	char checkBuf[1024];
	SafeMemcpy(checkBuf, sizeof(checkBuf), buf, sizeof(TokenData));
	SafeSprintf(checkBuf + sizeof(TokenData), sizeof(checkBuf) - sizeof(TokenData), "%s", login ? _loginKey.GetString() : _tokenKey.GetString());
	MD5 md5;
	md5.update(checkBuf, sizeof(TokenData) + login ? _loginKey.Length() : _tokenKey.Length());
	if (strcmp(md5.toString().c_str(), sign) != 0)
		return false;

	return true;
}
Example #27
0
bool Redis::Call(const s64 id, const char* proc, const s32 keyCount, const OArgs& args, const std::function<bool(IKernel *, const IRedisResult *)>& f) {
	if (s_contexts.empty())
		return false;

	Ping(s_kernel, id);

	if (!LoadScript(s_kernel, id, proc))
		return false;

	CommandBuff buf;
	buf.size = 0;

	const char * scriptId = s_contexts[id % s_contexts.size()].scriptIds[proc].GetString();
	s32 len = (s32)strlen(scriptId);
	SafeSprintf(buf.data + buf.size, sizeof(buf.data) - buf.size, "*%d\r\n$7\r\nEVALSHA\r\n$%d\r\n%s\r\n", args.Count() + 2, len, scriptId);
	buf.size += (s32)strlen(buf.data + buf.size);

	Append(buf, args);

	s_contexts[id % s_contexts.size()].ctx->obuf = buf.data;
	redisReply * reply = NULL;
	redisGetReply(s_contexts[id % s_contexts.size()].ctx, (void**)&reply);
	if (NULL == reply) {
		return false;
	}

	if (REDIS_REPLY_ERROR == reply->type || REDIS_REPLY_NIL == reply->type) {
		freeReplyObject(reply);
		return false;
	}

	bool ret = true;
	if (f) {
		RedisCallResult rst(reply);
		ret = f(s_kernel, &rst);
	}

	freeReplyObject(reply);
	return ret;
}
Example #28
0
bool Redis::Exec(const s64 id, const char* command, const OArgs& args, const std::function<bool(IKernel *, const IRedisResult *)>& f) {
	if (s_contexts.empty())
		return false;

	Ping(s_kernel, id);

	CommandBuff buf;
	buf.size = 0;

	SafeSprintf(buf.data + buf.size, sizeof(buf.data) - buf.size, "*%d\r\n$%d\r\n%s\r\n", args.Count() + 1, strlen(command), command);
	buf.size += (s32)strlen(buf.data + buf.size);

	Append(buf, args);

	s_contexts[id % s_contexts.size()].ctx->obuf = buf.data;
	redisReply * reply = NULL;
	redisGetReply(s_contexts[id % s_contexts.size()].ctx, (void**)&reply);
	if (NULL == reply) {
		return false;
	}

	if (REDIS_REPLY_ERROR == reply->type || REDIS_REPLY_NIL == reply->type) {
		freeReplyObject(reply);
		return false;
	}

	bool ret = true;
	if (f) {
		RedisCallResult rst(reply);
		ret = f(s_kernel, &rst);
	}

	freeReplyObject(reply);
	return ret;

}
Example #29
0
HXASMStream::HXASMStream(HXStream* pStream, HXSource* pSource)
    : m_bTimeStampDeliveryMode(FALSE)
    , m_bInitialSubscribe(TRUE)
    , m_bHasExpression(FALSE)
    , m_bEndOneRuleEndAll(FALSE)
    , m_ulLastLimitBandwidth(0xffffffff)
    , m_lRefCount(0)
    , m_nNumRules(0)
    , m_pAtomicRuleChange(0)
    , m_pRuleBook(0)
    , m_pLossCB(0)
    , m_ulLossCBHandle(0)
    , m_ulBandwidthAllocation(0)
    , m_ulFixedBandwidth(0)
    , m_pSubInfo(0)
    , m_ulRuleBw(0)
    , m_ulRulePreData(0)
    , m_ulCurrentPreData(0)
    , m_ulCurrentBandwidth(0)
    , m_ulLastBandwidth(0)
    , m_bRuleTimeStampDelivery(0)
    , m_ulSubscribedBw(0)
    , m_lBias(0)
    , m_bStartRecalc(FALSE)
    , m_pSubList(0)
    , m_pSubscriptionVariables(0)
    , m_pRuleSubscribeStatus(NULL)
    , m_pASMRuleState(NULL)
    , m_pRuleEnableState(NULL)
    , m_bSubsLocked(FALSE)
#ifndef GOLD
    , m_pEM(0)
#endif
{
    m_pStreamSinkMap = new CHXMapPtrToPtr;
    
    UINT32  ulStreamID;
    IHXPlayer* pPlayer;

    pStream->GetID(ulStreamID);
    m_pSource = pSource;
    m_pSource->AddRef();
    m_pHeader = pStream->GetHeader();
    m_uStreamNumber = pStream->GetStreamNumber();

    /* Hold onto some useful interfaces */

    m_pSource->GetPlayer(pPlayer);
    pPlayer->QueryInterface(IID_IHXRegistry,  (void **)&m_pRegistry);
    pPlayer->QueryInterface(IID_IHXScheduler,   (void **)&m_pScheduler);
    pPlayer->QueryInterface(IID_IHXCommonClassFactory,   (void **)&m_pCCF);
    pPlayer->Release();

    /*
     * WARNING!  You must update all interfaces queried off the source
     * in ResetASMSource().
     */
    m_pSource->QueryInterface(IID_IHXASMSource, (void **)&m_pASMSource);
    m_pSource->QueryInterface(IID_IHXAtomicRuleChange,
	(void **)&m_pAtomicRuleChange);

#ifndef GOLD
    pPlayer->QueryInterface(IID_IHXErrorMessages, (void **)&m_pEM);
#endif

    UINT32 ulEndOneruleEndAll = 0;
    if (m_pHeader->GetPropertyULONG32("EndOneRuleEndAll", ulEndOneruleEndAll) == HXR_OK)
    {
	m_bEndOneRuleEndAll = (ulEndOneruleEndAll == 1);
    }
    /* temporary hack to properly shut down RA and RV streams with end time */
    else
    {	
	IHXBuffer* pMimeType = NULL;
	m_pHeader->GetPropertyCString("MimeType", pMimeType);

	if (pMimeType && 
	    ((::strcasecmp((const char*) pMimeType->GetBuffer(), REALAUDIO_MIME_TYPE) == 0) ||
	     (::strcasecmp((const char*) pMimeType->GetBuffer(), REALAUDIO_MULTIRATE_MIME_TYPE) == 0) ||
	     (::strcasecmp((const char*) pMimeType->GetBuffer(), REALVIDEO_MIME_TYPE) == 0) ||
	     (::strcasecmp((const char*) pMimeType->GetBuffer(), REALVIDEO_MULTIRATE_MIME_TYPE) == 0)))
	{
	    m_bEndOneRuleEndAll = TRUE;
	}

	HX_RELEASE(pMimeType);
    }

    /* Extract RuleBook from the stream header */

    IHXBuffer* pRuleBook = NULL;
    m_pHeader->GetPropertyCString("ASMRuleBook", pRuleBook);
    if (pRuleBook)
    {
        m_pRuleBook = new ASMRuleBook (m_pCCF, (const char *)pRuleBook->GetBuffer());

	m_nNumRules = m_pRuleBook->GetNumRules();
	m_ulRuleBw = new UINT32[m_nNumRules];
	m_ulRulePreData = new UINT32[m_nNumRules];
	m_bRuleTimeStampDelivery = new HXBOOL[m_nNumRules];
	m_pSubInfo = new HXBOOL[m_nNumRules];
	m_pRuleSubscribeStatus = new HXBOOL[m_nNumRules];
        m_pRuleEnableState = new RuleEnableState[m_nNumRules];

        for (UINT16 i = 0; i < m_nNumRules; i++)
        {
	    IHXValues*	pValues;
	    IHXBuffer* pBuffer;

	    m_pRuleBook->GetProperties(i, pValues);

	    m_ulRuleBw[i] = 0;
	    m_ulRulePreData[i] = 0;
	    m_bRuleTimeStampDelivery[i] = FALSE;
            m_pRuleEnableState[i] = resEnabled;

	    if (HXR_OK == pValues->GetPropertyCString("PreData",
		pBuffer))
	    {
		m_ulRulePreData[i] = atoi((char*)pBuffer->GetBuffer());
		pBuffer->Release();
	    }

	    if (HXR_OK == pValues->GetPropertyCString("AverageBandwidth",
		pBuffer))
	    {
		m_ulRuleBw[i] = atoi((char*)pBuffer->GetBuffer());
		pBuffer->Release();
	    }
	    else if (HXR_OK == pValues->GetPropertyCString("TimeStampDelivery",
		pBuffer))
	    {
		if ((pBuffer->GetBuffer()[0] == 'T') ||
		    (pBuffer->GetBuffer()[0] == 't'))
		{
		    // Handle TimeStamp Delivery (i.e. assume significant bandwidth)
		    m_ulRuleBw[i] = 0;
		    m_bRuleTimeStampDelivery[i] = TRUE;
		}
		pBuffer->Release();
	    }
	    else
	    {
		/* XXXSMP Temporary hack for invalid rulebooks */
		if (i == 0)
		{
		    IHXValues* pHeader = 0;

		    HX_VERIFY(pHeader = pStream->GetHeader());
		    pHeader->GetPropertyULONG32("AvgBitRate",m_ulRuleBw[i]);
		    pHeader->Release();
		}
		else
		{
		    m_ulRuleBw[i] = 0;
		}
	    }
	    pValues->Release();

            m_pSubInfo[i] = 0;
	    m_pRuleSubscribeStatus[i] = FALSE;
        }

	HXBOOL bFixed = TRUE;

	m_bHasExpression = m_pRuleBook->HasExpression();
	if (m_bHasExpression == FALSE)
	{
	    UINT16 i;
	    for (i = 0; i < m_nNumRules; i++)
	    {
		if (m_bRuleTimeStampDelivery[i] == FALSE)
		{
		    bFixed = FALSE;
		    break;
		}
	    }

	    if (bFixed)
	    {
		m_ulFixedBandwidth = 1;
	    }
	    else
	    {
		m_ulCurrentBandwidth = 0;
		for (i = 0; i < m_nNumRules; i++)
		{
		    m_ulCurrentBandwidth += m_ulRuleBw[i];
		}

		m_ulFixedBandwidth = m_ulCurrentBandwidth;
	    }
	}
    }
    else
    {
	IHXValues* pHeader = 0;

	HX_VERIFY(pHeader = pStream->GetHeader());
	HX_VERIFY(HXR_OK == pHeader->GetPropertyULONG32("AvgBitRate",
	    m_ulFixedBandwidth));
	
	m_ulCurrentBandwidth = m_ulFixedBandwidth; 

	pHeader->Release();
    }

    /* Get Registry ID's for interesting properties */
    IHXBuffer* pPropName = 0;

    // init. 
    memset(m_szRecv, 0, MAX_DISPLAY_NAME);
    memset(m_szLost, 0, MAX_DISPLAY_NAME);
    memset(m_szClipBandwidth, 0, MAX_DISPLAY_NAME);

    if( m_pRegistry )
	{
	    m_pRegistry->GetPropName(ulStreamID, pPropName);
	}
    
    if (pPropName)
    {
	SafeSprintf(m_szRecv, MAX_DISPLAY_NAME, "%s.received", pPropName->GetBuffer());
	m_ulIDRecv = m_pRegistry->GetId(m_szRecv);

	SafeSprintf(m_szLost, MAX_DISPLAY_NAME, "%s.lost", pPropName->GetBuffer());
	m_ulIDLost = m_pRegistry->GetId(m_szLost);

	SafeSprintf(m_szClipBandwidth, MAX_DISPLAY_NAME, "%s.ClipBandwidth", pPropName->GetBuffer());
	m_ulIDClipBandwidth = m_pRegistry->GetId(m_szClipBandwidth);
	pPropName->Release();
    }

    /* 
     * We consider Local source as a Network source IFF someone uses core
     * for simulated network playback (used for Preview mode in the Encoder)
     */
    if (pSource->IsLocalSource() && !pSource->IsSimulatedNetworkPlayback())
    {
	/* Some large bandwidth */
	m_ulBandwidthAllocation = 0x7FFFFFFF;
	HXBOOL b;
	SetBandwidthUsage(m_ulBandwidthAllocation, b);
    }
    else if (pSource->IsPNAProtocol())
    {
	IHXBuffer* pMimeType = NULL;
	m_pHeader->GetPropertyCString("MimeTYpe", pMimeType);

	if (pMimeType && 
	    ::strcasecmp((const char*) pMimeType->GetBuffer(), "audio/x-pn-realaudio") == 0)
	{
	    /* Some large bandwidth */
	    m_ulBandwidthAllocation = 0x7FFFFFFF;
	    HXBOOL b;
	    SetBandwidthUsage(m_ulBandwidthAllocation, b);
	}
	HX_RELEASE(pMimeType);
    }
    else if (pRuleBook)
    {
	m_pLossCB = new LossCheckCallback(this);
	m_pLossCB->AddRef();
	m_ulLossCBHandle = m_pScheduler->RelativeEnter(m_pLossCB, 1000);
    }
    
    HX_RELEASE(pRuleBook);
}
Example #30
0
void
QueueFileSize(CBigByteGrowingQueue* pQ, UINT32 ulFileSize)
{
    char buf[14]; /* Flawfinder: ignore */

    if ( ulFileSize )
    {
	pQ->EnQueue(z_pFileSize);
	UINT32 num;
	HXBOOL first = TRUE;
	// billions.
	num = (ulFileSize / 1000000000);
	if ( num )
	{
	    SafeSprintf(buf, sizeof(buf), "%u", num);
	    pQ->EnQueue(buf);
	    pQ->EnQueue(",");
	    first = FALSE;
	}
	ulFileSize %= 1000000000;
	// millions
	num = (ulFileSize / 1000000);
	if ( (num) || !first )
	{
	    if ( first )
	    {
		SafeSprintf(buf, sizeof(buf), "%u", num);
		first = FALSE;
	    }
	    else
	    {
		SafeSprintf(buf, sizeof(buf), "%03u", num);
	    }
	    pQ->EnQueue(buf);
	    pQ->EnQueue(",");
	}
	ulFileSize %= 1000000;
	// thousands
	num = (ulFileSize / 1000);
	if ( (num) || !first )
	{
	    if ( first )
	    {
		SafeSprintf(buf, sizeof(buf), "%u", num);
		first = FALSE;
	    }
	    else
	    {
		SafeSprintf(buf, sizeof(buf), "%03u", num);
	    }
	    pQ->EnQueue(buf);
	    pQ->EnQueue(",");
	}
	// whats left...
	ulFileSize %= 1000;
	if ( first )
	{
	    SafeSprintf(buf, sizeof(buf), "%u", ulFileSize);
	    first = FALSE;
	}
	else
	{
	    SafeSprintf(buf, sizeof(buf), "%03u", ulFileSize);
	}
	pQ->EnQueue(buf);
	pQ->EnQueue(" Bytes");
	pQ->EnQueue(z_pEndLine);
    }
}