Beispiel #1
0
void ShowPopupUtf(const char* line1, const char* line2, int timeout, const MCONTACT hContact) {
	wchar_t* l1 = (line1) ? mir_utf8decodeW(line1) : nullptr;
	wchar_t* l2 = (line2) ? mir_utf8decodeW(line2) : nullptr;
	ShowPopup(l1, l2, timeout, hContact);
	if (l1) mir_free(l1);
	if (l2) mir_free(l2);
}
Beispiel #2
0
static int lua_AddSound(lua_State *L)
{
	ptrA name(mir_utf8decodeA(luaL_checkstring(L, 1)));
	ptrW description(mir_utf8decodeW(luaL_checkstring(L, 2)));
	ptrW section(mir_utf8decodeW(luaL_optstring(L, 3, MODULENAME)));
	ptrW filePath(mir_utf8decodeW(lua_tostring(L, 4)));

	int res = 1;
	CMPluginBase *pPlugin = CMLuaEnvironment::GetEnvironment(L);
	if (pPlugin != nullptr)
		res = pPlugin->addSound(name, section, description, filePath);
	lua_pushboolean(L, res == 0);

	return 1;
}
Beispiel #3
0
INT_PTR CAimProto::GetMyAwayMsg(WPARAM wParam, LPARAM lParam)
{
	char** msgptr = get_status_msg_loc(wParam ? wParam : m_iStatus);
	if (msgptr == NULL)	return 0;

	return (lParam & SGMA_UNICODE) ? (INT_PTR)mir_utf8decodeW(*msgptr) : (INT_PTR)mir_utf8decodeA(*msgptr);
}
Beispiel #4
0
TCHAR* ReqGetText(DBEVENTINFO* dbei)
{
	if ( !dbei->pBlob )
		return 0;

	char * ptr=(char *)&dbei->pBlob[sizeof(DWORD)*2];
	int len=dbei->cbBlob-sizeof(DWORD)*2;
	int i=0;

	while(len && (i<4))
	{
		if(!ptr[0]) i++;
		ptr++;
		len--;
	};

	if(len)
	{
		char * tstr=(char *)mir_alloc(len+1);
		memcpy(tstr, ptr, len);
		tstr[len]=0;
		WCHAR* msg = NULL;
		msg=(dbei->flags&DBEF_UTF)?mir_utf8decodeW(tstr):mir_a2u(tstr);
		mir_free(tstr);
		return (TCHAR *)msg;
	};
	return 0;
}
Beispiel #5
0
static int OnFastDump(WPARAM wParam,LPARAM lParam)
{
	if ( pActive )
	{
		LOGMSG *logMsg = (LOGMSG*)lParam;
		DWORD headlen = (DWORD)strlen(logMsg->pszHead);
		DWORD msglen = (DWORD)strlen(logMsg->pszMsg);
		DWORD len = (headlen + msglen + 1) * sizeof(TCHAR) + sizeof(DUMPMSG);
		DUMPMSG *dumpMsg = (DUMPMSG*)mir_alloc( len );
		TCHAR *str = dumpMsg->szMsg;

		char *szModule = (wParam) ? ((NETLIBUSER*)wParam)->szDescriptiveName : "[Core]";
		strncpy_s(dumpMsg->szModule, SIZEOF(dumpMsg->szModule), szModule, _TRUNCATE);

		wchar_t *ucs2 = mir_a2u(logMsg->pszHead);
		wcscpy(str, ucs2);
		mir_free(ucs2);

		// try to detect utf8
		ucs2 = mir_utf8decodeW(logMsg->pszMsg);
		if ( !ucs2 )
			ucs2 = mir_a2u(logMsg->pszMsg);

		wcscat(str, ucs2);
		mir_free(ucs2);

		InMsgs++;
		PostMessage(hwndConsole, HM_DUMP, 0, (LPARAM)dumpMsg);
	}
	return 0;
}
Beispiel #6
0
static size_t utf8toutf16(char* str, wchar_t* res)
{
	wchar_t *dec = mir_utf8decodeW(str);
	if (dec == NULL) dec = mir_a2u(str);
	wcscpy(res, dec);
	mir_free(dec);
	return wcslen(res);
}
Beispiel #7
0
static int lua_PlayFile(lua_State *L)
{
	ptrW filePath(mir_utf8decodeW(luaL_checkstring(L, 1)));

	INT_PTR res = Skin_PlaySoundFile(filePath);
	lua_pushboolean(L, res == 0);

	return 1;
}
Beispiel #8
0
INT_PTR __cdecl CYahooProto::GetMyAwayMsg(WPARAM wParam, LPARAM lParam)
{
	if (!m_bLoggedIn || ! m_startMsg)
		return 0;

	if (lParam & SGMA_UNICODE)  {
		return (INT_PTR) mir_utf8decodeW(m_startMsg);
	} else {
		return (INT_PTR) mir_utf8decodeA(m_startMsg);
	}
}
static TCHAR* JSetStringCrypt(LPCSTR szModule, HANDLE hContact, char *valueName)
{
	DBVARIANT dbv;
	if (db_get_s(hContact, szModule, valueName, &dbv))
		return NULL;

	sttCryptString(dbv.pszVal);
	WCHAR *res = mir_utf8decodeW(dbv.pszVal);
	db_free(&dbv);
	return res;
}
Beispiel #10
0
int luaM_toucs2(lua_State *L)
{
	const char* value = luaL_checkstring(L, 1);

	ptrW unicode(mir_utf8decodeW(value));
	size_t length = mir_wstrlen(unicode) * sizeof(wchar_t);

	ptrA string((char*)mir_calloc(length + 1));
	memcpy(string, unicode, length);

	lua_pushlstring(L, string, length + 1);

	return 1;
}
Beispiel #11
0
TCHAR * GetSendBufferMsg(MessageSendQueueItem *item)
{
	TCHAR *szMsg = NULL;
	size_t len = strlen(item->sendBuffer);

	if (item->flags & PREF_UTF)
		szMsg = mir_utf8decodeW(item->sendBuffer);
	else {
		szMsg = (TCHAR *)mir_alloc(item->sendBufferSize - len - 1);
		memcpy(szMsg, item->sendBuffer + len + 1, item->sendBufferSize - len - 1);
	}

	return szMsg;
}
Beispiel #12
0
INT_PTR CMraProto::MraSendSMS(WPARAM wParam, LPARAM lParam)
{
	if (!m_bLoggedIn || !wParam || !lParam)
		return 0;

	ptrW lpwszMessageXMLEncoded( mir_utf8decodeW((LPSTR)lParam));
	if (lpwszMessageXMLEncoded) {
		CMStringW decoded = DecodeXML( CMStringW(lpwszMessageXMLEncoded));
		if (decoded.GetLength())
			MraSMSW(NULL, CMStringA((LPSTR)wParam), decoded);
	}

	return 0;
}
BYTE CExImContactBase::compareUID(DBVARIANT *dbv)
{
	DWORD hash = 0;
	switch (dbv->type) {
		case DBVT_BYTE:
			if (dbv->bVal == _dbvUID.bVal) {
				_dbvUID.type = dbv->type;
				return TRUE;
			}
			break;
		case DBVT_WORD:
			if (dbv->wVal == _dbvUID.wVal) {
				_dbvUID.type = dbv->type;
				return TRUE;
			}
			break;
		case DBVT_DWORD:
			if (dbv->dVal == _dbvUID.dVal) {
				_dbvUID.type = dbv->type;
				return TRUE;
			}
			break;
		case DBVT_ASCIIZ:
			hash = hashSetting_M2(dbv->pszVal);
		case DBVT_WCHAR:
			if (!hash) hash = hashSettingW_M2((const char *)dbv->pwszVal);
		case DBVT_UTF8:
			if (!hash) {
				LPWSTR tmp = mir_utf8decodeW(dbv->pszVal);
				hash = hashSettingW_M2((const char *)tmp);
				mir_free(tmp);
			}
			if (hash == _dbvUIDHash) return TRUE;
			break;
		case DBVT_BLOB:		//'n' cpbVal and pbVal are valid
			if (_dbvUID.type == dbv->type && 
				_dbvUID.cpbVal == dbv->cpbVal &&
				memcmp(_dbvUID.pbVal, dbv->pbVal, dbv->cpbVal) == 0) {
				return TRUE;
			}
			break;
		default:
			return FALSE;
	}
	return FALSE;
}
Beispiel #14
0
bool parse_clientlogin_response(NETLIBHTTPREQUEST *nlhr, NETLIBHTTPHEADER *my_headers, CMStringA &token, CMStringA &secret, time_t &hosttime)
{
	//TODO: validate response
	//TODO: return false on errors
	//TODO: extract token, secret, hosttime from response

	int datalen = 0;
	for (int i = 0; i < nlhr->headersCount; i++) {
		if (!mir_strcmp(nlhr->headers[i].szName, "Set-Cookie")) {
			my_headers[0].szName = "Cookie";
			my_headers[0].szValue = mir_strdup(nlhr->headers[i].szValue);
		}
	}

	ptrW buf_w(mir_utf8decodeW(nlhr->pData));
	HXML root = xmlParseString(buf_w, &datalen, _T(""));
	if (!root)
		return false;

	HXML status = xmlGetChildByPath(root, _T("response/statusCode"), 0);
	if (!status)
		return false;

	LPCTSTR status_text = xmlGetText(status);
	// TODO: check other than 200 codes and print some debug info on errors
	if (wcscmp(status_text, L"200"))
		return false;

	HXML secret_node = xmlGetChildByPath(root, _T("response/data/sessionSecret"), 0);
	HXML hosttime_node = xmlGetChildByPath(root, _T("response/data/hostTime"), 0);
	if (!secret_node || !hosttime_node)
		return false;

	HXML token_node = xmlGetChildByPath(root, _T("response/data/token/a"), 0);
	if (!token_node)
		return false;

	LPCTSTR secret_w = xmlGetText(secret_node), token_w = xmlGetText(token_node), hosttime_w = xmlGetText(hosttime_node);
	if (!secret_w || !token_w || !hosttime_w)
		return false;

	secret = _T2A(secret_w);
	token = _T2A(token_w);
	hosttime = strtol(_T2A(hosttime_w), NULL, 10);
	return true;
}
Beispiel #15
0
bool parse_start_socar_session_response(const char *response, CMStringA &bos_host, unsigned short &bos_port, CMStringA &cookie, CMStringA &tls_cert_name, bool encryption = true)
{
	//TODO: extract bos_host, bos_port, cookie, tls_cert_name

	int datalen = 0;
	ptrW buf_w(mir_utf8decodeW(response));
	HXML root = xmlParseString(buf_w, &datalen, _T(""));
	if (!root)
		return false;

	HXML status = xmlGetChildByPath(root, _T("response/statusCode"), 0);
	if (!status)
		return false;

	LPCTSTR status_text = xmlGetText(status);
	//TODO: check other than 200 codes and print some debug info on errors
	if (wcscmp(status_text, L"200"))
		return false;

	HXML host_node = xmlGetChildByPath(root, _T("response/data/host"), 0);
	HXML port_node = xmlGetChildByPath(root, _T("response/data/port"), 0);
	HXML cookie_node = xmlGetChildByPath(root, _T("response/data/cookie"), 0);
	if (!host_node || !port_node || !cookie_node)
		return false;

	LPCTSTR host_w = xmlGetText(host_node), port_w = xmlGetText(port_node), cookie_w = xmlGetText(cookie_node);
	if (!host_w || !port_w || !cookie_w)
		return false;

	bos_host = _T2A(host_w);
	bos_port = atoi(_T2A(port_w));
	cookie = _T2A(cookie_w);

	if (encryption) {
		HXML tls_node = xmlGetChildByPath(root, _T("response/data/tlsCertName"), 0); //tls is optional, so this is not fatal error
		if (tls_node) {
			LPCTSTR certname_w = xmlGetText(tls_node);
			if (certname_w)
				tls_cert_name = _T2A(certname_w);
		}
	}

	return true;
}
Beispiel #16
0
TCHAR* CJabberProto::JGetStringCrypt( HANDLE hContact, char* valueName )
{
	DBVARIANT dbv;

	if (DBGetContactSettingString( hContact, m_szModuleName, valueName, &dbv ))
		return NULL;

	sttCryptString(dbv.pszVal);

#ifdef UNICODE
	WCHAR *res = mir_utf8decodeW(dbv.pszVal);
#else
	mir_utf8decode(dbv.pszVal, NULL);
	char *res = mir_strdup(dbv.pszVal);
#endif

	DBFreeVariant(&dbv);
	return res;
}
Beispiel #17
0
int GetValueW(MCONTACT hContact, const char *module, const char *setting, WCHAR *value, int length)
{
	DBVARIANT dbv = { 0 };

	if (!module || !setting || !value)
		return 0;

	if (length >= 10 && !db_get_s(hContact, module, setting, &dbv, 0)) {
		switch (dbv.type) {

		case DBVT_ASCIIZ:
			mir_wstrncpy(value, ptrW(mir_a2u(dbv.pszVal)), length);
			break;

		case DBVT_DWORD:
		case DBVT_WORD:
		case DBVT_BYTE:
			_ultow(getNumericValue(&dbv), value, 10);
			break;

		case DBVT_WCHAR:
			mir_wstrncpy(value, dbv.pwszVal, length);
			break;

		case DBVT_UTF8:
			mir_wstrncpy(value, ptrW(mir_utf8decodeW(dbv.pszVal)), length);
			break;

		case DBVT_DELETED:
			value[0] = 0;
			return 0;
		}

		int type = dbv.type;
		db_free(&dbv);
		return type;
	}

	value[0] = 0;
	return 0;
}
Beispiel #18
0
TCHAR* DoRtfToTags( char* pszText, SESSION_INFO* si)
{
	char *p1;
	int*  pIndex;
	int i, iRemoveChars, cp = CP_ACP;
	char InsertThis[50];
	BOOL bJustRemovedRTF = TRUE;
	BOOL bTextHasStarted = FALSE;
	int iUcMode = 0;

	if ( !pszText )
		return FALSE;

	// create an index of colors in the module and map them to
	// corresponding colors in the RTF color table
	pIndex = mir_alloc(sizeof(int) * MM_FindModule(si->pszModule)->nColorCount);
	for(i = 0; i < MM_FindModule(si->pszModule)->nColorCount ; i++)
		pIndex[i] = -1;

	CreateColorMap( pszText, pIndex, si );

	// scan the file for rtf commands and remove or parse them
	p1 = strstr( pszText, "\\pard" );
	if ( p1 == NULL ) {
		mir_free(pIndex);
		return FALSE;
	}

	p1 += 5;

	memmove(pszText, p1, strlen(p1) + 1);
	p1 = pszText;

	// iterate through all characters, if rtf control character found then take action
	while ( *p1 != '\0' ) {
		InsertThis[0] = 0;
		iRemoveChars = 0;

		switch (*p1) {
		case '\\':
			if ( !memcmp(p1, "\\cf", 3 )) { // foreground color
				int iCol, iInd;
				iRemoveChars = 3 + ReadInteger(p1+3, &iCol);
				iInd = RTFColorToIndex(pIndex, iCol, si);
				bJustRemovedRTF = TRUE;

				if (bTextHasStarted || iInd >= 0)
					mir_snprintf( InsertThis, SIZEOF(InsertThis), ( iInd >= 0 ) ? "%%c%02u" : "%%C", iInd);
			}
			else if ( !memcmp(p1, "\\highlight", 10 )) { //background color
				int iCol, iInd;
				iRemoveChars = 10 + ReadInteger(p1+10, &iCol);
				iInd = RTFColorToIndex(pIndex, iCol, si);
				bJustRemovedRTF = TRUE;

				if (bTextHasStarted || iInd >= 0)
					mir_snprintf( InsertThis, SIZEOF(InsertThis), ( iInd >= 0 ) ? "%%f%02u" : "%%F", iInd);
			}
			else if ( !memcmp(p1, "\\lang", 5 )) { // language id
				bTextHasStarted = bJustRemovedRTF = TRUE;
				iRemoveChars = 5 + ReadInteger( p1+5, NULL );
			}
			else if ( !memcmp(p1, "\\par", 4 )) { // newline
				bTextHasStarted = bJustRemovedRTF = TRUE;
				iRemoveChars = 4;
				strcpy(InsertThis, "\n" );
			}
			else if ( !memcmp(p1, "\\line", 5 )) { // newline
				bTextHasStarted = bJustRemovedRTF = TRUE;
				iRemoveChars = 5;
				strcpy(InsertThis, "\n" );
			}
			else if (!memcmp(p1, "\\bullet", 7)) {
				bTextHasStarted = TRUE;
				bJustRemovedRTF = TRUE;
				iRemoveChars = 7;
#if defined(_UNICODE)
				strcpy(InsertThis, "\xE2\x80\xA2");
#else
				strcpy(InsertThis, "\x95");
#endif
			}
			else if ( !memcmp(p1, "\\b", 2 )) { //bold
				bTextHasStarted = bJustRemovedRTF = TRUE;
				iRemoveChars = (p1[2] != '0')?2:3;
				mir_snprintf(InsertThis, SIZEOF(InsertThis), (p1[2] != '0') ? "%%b": "%%B" );
			}
			else if ( !memcmp(p1, "\\i", 2 )) { // italics
				bTextHasStarted = bJustRemovedRTF = TRUE;
				iRemoveChars = (p1[2] != '0')?2:3;
				mir_snprintf(InsertThis, SIZEOF(InsertThis), (p1[2] != '0') ? "%%i" : "%%I" );
			}
			else if ( !memcmp(p1, "\\uc", 3 )) { // number of Unicode chars
				bTextHasStarted = bJustRemovedRTF = TRUE;
				iUcMode = p1[3] - '0';
				iRemoveChars = 4;
			}
			else if ( !memcmp(p1, "\\ul", 3 )) { // underlined
				bTextHasStarted = bJustRemovedRTF = TRUE;
				if (p1[3] == 'n')
					iRemoveChars = 7;
				else if (p1[3] == '0')
					iRemoveChars = 4;
				else
					iRemoveChars = 3;
				mir_snprintf(InsertThis, SIZEOF(InsertThis), (p1[3] != '0' && p1[3] != 'n') ? "%%u" : "%%U" );
			}
			else if ( p1[1] == 'f' && isdigit( p1[2] )) { // unicode char
				bTextHasStarted = bJustRemovedRTF = TRUE;
				iRemoveChars = 2 + ReadInteger( p1+2, NULL );
			}
			else if ( !memcmp(p1, "\\tab", 4 )) { // tab
				bTextHasStarted = TRUE;
				bJustRemovedRTF = TRUE;
				iRemoveChars = 4;
				strcpy(InsertThis, " " );
			}
			else if (!memcmp(p1, "\\endash", 7)) {
				bTextHasStarted = TRUE;
				bJustRemovedRTF = TRUE;
				iRemoveChars = 7;
#if defined(_UNICODE)
				strcpy(InsertThis, "\xE2\x80\x93");
#else
				strcpy(InsertThis, "\x96");
#endif
			}
			else if (!memcmp(p1, "\\emdash", 7)) {
				bTextHasStarted = TRUE;
				bJustRemovedRTF = TRUE;
				iRemoveChars = 7;
#if defined(_UNICODE)
				strcpy(InsertThis, "\xE2\x80\x94");
#else
				strcpy(InsertThis, "\x97");
#endif
			} 
			else if (!memcmp(p1, "\\lquote",7)) {
				bTextHasStarted = TRUE;
				bJustRemovedRTF = TRUE;
				iRemoveChars = 7;
#if defined(_UNICODE)
				strcpy(InsertThis, "\xE2\x80\x98");
#else
				strcpy(InsertThis, "\x91");
#endif
			}
			else if (!memcmp(p1, "\\rquote",7)) {
				bTextHasStarted = TRUE;
				bJustRemovedRTF = TRUE;
				iRemoveChars = 7;
#if defined(_UNICODE)
				strcpy(InsertThis, "\xE2\x80\x99");
#else
				strcpy(InsertThis, "\x92");
#endif
			}
			else if (!memcmp(p1, "\\ldblquote",10)) {
				bTextHasStarted = TRUE;
				bJustRemovedRTF = TRUE;
				iRemoveChars = 10;
#if defined(_UNICODE)
				strcpy(InsertThis, "\xe2\x80\x9c");
#else
				strcpy(InsertThis, "\"");
#endif
			}
			else if (!memcmp(p1, "\\rdblquote",10)) {
				bTextHasStarted = TRUE;
				bJustRemovedRTF = TRUE;
				iRemoveChars = 10;
#if defined(_UNICODE)
				strcpy(InsertThis, "\xe2\x80\x9d");
#else
				strcpy(InsertThis, "\"");
#endif
			}
			else if ( p1[1] == '\\' ||  p1[1] == '{' || p1[1] == '}' ) { // escaped characters
				bTextHasStarted = TRUE;
				bJustRemovedRTF = FALSE;
				iRemoveChars = 2;
				mir_snprintf(InsertThis, SIZEOF(InsertThis), "%c", p1[1]);
			}
			else if ( p1[1] == '~' ) { // non-breaking space
				bTextHasStarted = TRUE;
				bJustRemovedRTF = FALSE;
				iRemoveChars = 2;
#if defined(_UNICODE)
				strcpy(InsertThis, "\xC2\xA0");
#else
				strcpy(InsertThis, "\xA0");
#endif
			}
			else if ( p1[1] == '\'' ) { // special character
				char tmp[4], *p3 = tmp;
				bTextHasStarted = TRUE;
				bJustRemovedRTF = FALSE;
				if (p1[2] != ' ' && p1[2] != '\\') {
					*p3++ = p1[2];
					iRemoveChars = 3;
					if ( p1[3] != ' ' && p1[3] != '\\') {
						*p3++ = p1[3];
						iRemoveChars++;
					}
					*p3 = 0;
					sscanf( tmp, "%x", InsertThis );

					InsertThis[1] = 0;
				}
				else iRemoveChars = 2;
			}
			else if ( bJustRemovedRTF ) { // remove unknown RTF command
				int j = 1;
				bJustRemovedRTF = TRUE;
				while(p1[j] != ' ' && p1[j] != '\\' && p1[j] != '\0')
					j++;
				iRemoveChars = j;
			}
			break;

		case '{': // other RTF control characters
		case '}':
			iRemoveChars = 1;
			break;

		case '\r': case '\n':
			bTextHasStarted = TRUE;
			bJustRemovedRTF = FALSE;
			iRemoveChars = 1;
			break;

		case '%': // escape chat -> protocol control character
			bTextHasStarted = TRUE;
			bJustRemovedRTF = FALSE;
			iRemoveChars = 1;
			strcpy(InsertThis, "%%");
			break;
		case ' ': // remove spaces following a RTF command
			if (bJustRemovedRTF)
				iRemoveChars = 1;
			bJustRemovedRTF = FALSE;
			bTextHasStarted = TRUE;
			break;

		default: // other text that should not be touched
			bTextHasStarted = TRUE;
			bJustRemovedRTF = FALSE;
			break;
		}

		// move the memory and paste in new commands instead of the old RTF
		if (InsertThis[0] || iRemoveChars) 
		{
			size_t len = strlen(InsertThis);
			memmove(p1 + len , p1 + iRemoveChars, strlen(p1) - iRemoveChars + 1);
			memcpy(p1, InsertThis, len);
			p1 += len;
		}
		else p1++;
	}

	mir_free(pIndex);

	#if !defined( _UNICODE )
		return pszText;
	#else
		return mir_utf8decodeW(pszText);
	#endif
}
STDMETHODIMP_(BOOL) CDataBase::WriteContactSetting(HANDLE hContact, DBCONTACTWRITESETTING *dbcws)
{
	char namebuf[512];
	namebuf[0] = 0;
	if (dbcws->szModule)
		strcpy_s(namebuf, dbcws->szModule);
	strcat_s(namebuf, "/");
	if (dbcws->szSetting)
		strcat_s(namebuf, dbcws->szSetting);

	TDBTSettingDescriptor desc = {0,0,0,0,0,0,0,0};
	TDBTSetting set = {0,0,0,0};
	desc.cbSize = sizeof(desc);
	desc.Entity = (WPARAM)hContact;
	desc.pszSettingName = namebuf;

	set.cbSize = sizeof(set);
	set.Descriptor = &desc;

	switch (dbcws->value.type) {
	case DBVT_ASCIIZ:
		set.Type = DBT_ST_ANSI;
		set.Value.pAnsi = dbcws->value.pszVal;
		if (isEncrypted(dbcws->szModule, dbcws->szSetting))
			EncodeString(dbcws->value.pszVal);
		break;
	case DBVT_UTF8:
		if (isEncrypted(dbcws->szModule, dbcws->szSetting))
			EncodeString(dbcws->value.pszVal);
		{
			wchar_t * tmp = mir_utf8decodeW(dbcws->value.pszVal);
			if (tmp == 0) {
				if (IsDebuggerPresent())
				{
					DebugBreak();
#ifdef _DEBUG
				}
				else {
					LOG(logWARNING, _T("Trying to write malformed UTF8 setting \"%hs\" in module \"%hs\""), dbcws->szSetting, dbcws->szModule);
					CLogger::Instance().ShowMessage();
#endif
				}
				return -1;
			}
			else mir_free(tmp);
		}

		set.Type = DBT_ST_UTF8;
		set.Value.pUTF8 = dbcws->value.pszVal;
		break;
	case DBVT_WCHAR:
		set.Type = DBT_ST_WCHAR;
		set.Value.pWide = dbcws->value.pwszVal;
		break;
	case DBVT_BLOB:
		set.Type = DBT_ST_BLOB;
		set.Value.pBlob = dbcws->value.pbVal;
		set.Value.Length = dbcws->value.cpbVal;
		break;
	case DBVT_BYTE:
		set.Type = DBT_ST_BYTE;
		set.Value.Byte = dbcws->value.bVal;
		break;
	case DBVT_WORD:
		set.Type = DBT_ST_WORD;
		set.Value.Word = dbcws->value.wVal;
		break;
	case DBVT_DWORD:
		set.Type = DBT_ST_DWORD;
		set.Value.DWord = dbcws->value.dVal;
		break;
	default:
		return -1;
	}

	if (DBSettingWrite(reinterpret_cast<WPARAM>(&set), 0) == DBT_INVALIDPARAM)
		return -1;

	if (dbcws->value.type == DBVT_WCHAR) {
		dbcws->value.type = DBVT_UTF8;
		wchar_t * tmp = dbcws->value.pwszVal;
		dbcws->value.pszVal = mir_utf8encodeW(dbcws->value.pwszVal);
		NotifyEventHooks(hSettingChangeEvent, (WPARAM)hContact, (LPARAM)dbcws);
		mir_free(dbcws->value.pszVal);
		dbcws->value.type = DBVT_WCHAR;
		dbcws->value.pwszVal = tmp;		
	}
	else NotifyEventHooks(hSettingChangeEvent, (WPARAM)hContact, (LPARAM)dbcws);

	return 0;
}
Beispiel #20
0
void IEView::write(const char *text)
{
	write(ptrW(mir_utf8decodeW(text)));
}
Beispiel #21
0
MIRANDA_HOOK_EVENT(ME_DB_EVENT_FILTER_ADD, w, l)
{
	MCONTACT hContact = (MCONTACT)w;
	DBEVENTINFO *dbei = (DBEVENTINFO*)l;
	if (dbei == NULL) //fix potential DEP crash
		return 0;

	// if event is in protocol that is not despammed
	if (plSets->ProtoDisabled(dbei->szModule))
		// ...let the event go its way
		return 0;

	// if event is not a message, or if the message has been read or sent...
	if (dbei->flags & DBEF_SENT || dbei->flags & DBEF_READ || dbei->eventType != EVENTTYPE_MESSAGE)
		// ...let the event go its way
		return 0;

	// if message is from known or marked Answered contact
	if (db_get_b(hContact, pluginName, answeredSetting, 0))
		// ...let the event go its way
		return 0;

	// checking if message from self-added contact
	//Contact in Not in list icq group
	if (!db_get_b(hContact, "CList", "NotOnList", 0) && db_get_w(hContact, dbei->szModule, "SrvGroupId", -1) != 1)
		return 0;

	//if I sent message to this contact
	if (IsExistMyMessage(hContact))
		return 0;

	// if message is corrupted or empty it cannot be an answer.
	if (!dbei->cbBlob || !dbei->pBlob)
		// reject processing of the event
		return 1;

	tstring message;

	if (dbei->flags & DBEF_UTF){
		WCHAR* msg_u = mir_utf8decodeW((char*)dbei->pBlob);
		message = msg_u;
		mir_free(msg_u);
	}
	else {
		WCHAR* msg_u = mir_a2u((char*)(dbei->pBlob));
		message = msg_u;
		mir_free(msg_u);
	}

	// if message equal right answer...
	tstring answers = variables_parse(plSets->Answer.Get(), hContact);
	answers.append(plSets->AnswSplitString.Get());
	tstring::size_type pos = 0;
	tstring::size_type prev_pos = 0;
	while ((pos = answers.find(plSets->AnswSplitString.Get(), pos)) != tstring::npos) {
		// get one of answers and trim witespace chars
		tstring answer = trim(answers.substr(prev_pos, pos - prev_pos));
		// if answer not empty
		if (answer.length() > 0) {
			// if message equal right answer...
			if (plSets->AnswNotCaseSens.Get() ? !mir_tstrcmpi(message.c_str(), answer.c_str()) : !mir_tstrcmp(message.c_str(), answer.c_str())) {
				// unhide contact
				db_unset(hContact, "CList", "Hidden");

				// mark contact as Answered
				db_set_b(hContact, pluginName, answeredSetting, 1);

				//add contact permanently
				if (plSets->AddPermanent.Get())
					db_unset(hContact, "CList", "NotOnList");

				// send congratulation

				char * buf = mir_utf8encodeW(variables_parse(plSets->Congratulation.Get(), hContact).c_str());
				CallContactService(hContact, PSS_MESSAGE, 0, (LPARAM)buf);
				mir_free(buf);

				// process the event
				return 1;
			}
		}
		prev_pos = ++pos;
	}

	// if message message does not contain infintite talk protection prefix
	// and question count for this contact is less then maximum
	if ((!plSets->InfTalkProtection.Get() || tstring::npos == message.find(infTalkProtPrefix))
		&& (!plSets->MaxQuestCount.Get() || db_get_dw(hContact, pluginName, questCountSetting, 0) < plSets->MaxQuestCount.Get()))
	{
		// send question
		tstring q = infTalkProtPrefix + variables_parse((tstring)(plSets->Question), hContact);


		char * buf = mir_utf8encodeW(q.c_str());
		CallContactService(hContact, PSS_MESSAGE, 0, (LPARAM)buf);
		mir_free(buf);


		// increment question count
		DWORD questCount = db_get_dw(hContact, pluginName, questCountSetting, 0);
		db_set_dw(hContact, pluginName, questCountSetting, questCount + 1);
	}

	// hide contact from contact list
	db_set_b(hContact, "CList", "NotOnList", 1);
	db_set_b(hContact, "CList", "Hidden", 1);

	// save message from contact
	dbei->flags |= DBEF_READ;
	db_event_add(hContact, dbei);

	// reject processing of the event
	return 1;
}
Beispiel #22
0
TCHAR* GetSendBufferMsg(MessageSendQueueItem *item)
{
	return mir_utf8decodeW(item->sendBuffer);
}
Beispiel #23
0
inline wchar_t* toCString(const json_string & str)
{
	return mir_utf8decodeW( str.c_str());
}
Beispiel #24
0
int OnDBEventFilterAdd(WPARAM wParam, LPARAM lParam)
{
	HANDLE hContact = (HANDLE)wParam;
	DBEVENTINFO *dbei = (DBEVENTINFO *)lParam;
	char *msgblob;
	POPUPDATA ppdp = {0};
	DBTIMETOSTRING tts = {0};
	char protoOption[256] = {0};
	char *response, *tmp, *challenge;
	int buflen = MAX_BUFFER_LENGTH;
	TCHAR buf[MAX_BUFFER_LENGTH];
	TCHAR *message = NULL, *challengeW = NULL, *tmpW = NULL;
	TCHAR *whitelist = NULL, *ptok;
	TCHAR mexpr[64];
	int maxmsglen = 0, a, b, i;
	BOOL bayesEnabled = _getOptB("BayesEnabled", defaultBayesEnabled);
	BOOL bCorrectResponse = FALSE;

	// get hContact from DBEVENTINFO as icq_proto.c doesn't pass hContact the usual way for some reason.
	if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
		hContact = *((PHANDLE)(dbei->pBlob+sizeof(DWORD)));

	// get maximum length of the message a protocol supports
	maxmsglen = CallProtoService(dbei->szModule, PS_GETCAPS, PFLAG_MAXLENOFMESSAGE, (LPARAM)hContact);

	
	/*** Dequeue and learn messages ***/
	
	if (bayesEnabled && _getOptB("BayesAutolearnNotApproved", defaultBayesAutolearnNotApproved))
		if (time(NULL) - last_queue_check > 4*3600) { // dequeue every 4 hours
			dequeue_messages();
			last_queue_check = time(NULL);
		}


	/*** Check for conditional and unconditional approval ***/

	// Pass-through if protocol is not enabled
	strcat(protoOption, "proto_");
	strcat(protoOption, dbei->szModule);
	if (_getOptB(protoOption, 0) == 0) // Protocol is not handled by Spam-o-tron
		return 0;

	// Pass-through if the event is not of type EVENTTYPE_MESSAGE or EVENTTYPE_AUTHREQUEST
	if (dbei->eventType != EVENTTYPE_MESSAGE && dbei->eventType != EVENTTYPE_AUTHREQUEST)
		return 0;

	// Pass-through if contact is already verified.
	if (_getCOptB(hContact, "Verified", 0) == 1)
		return 0;

	// Pass-through if the event is already read.
	if (dbei->flags & DBEF_READ)
		return 0;

	// Pass-through if event is from a contact that is already in the list. 
	if (db_get_b(hContact, "CList", "NotOnList", 1) == 0) // Already in the list
		return 0;

	// Pass-through if event is from a contact that is already in the server-side contact list
	if (db_get_w(hContact, dbei->szModule, "ServerId", 0))
		return 0;

	// Pass-through if contact is a MetaContact
	if (db_get_dw(hContact, "MetaContacts", "NumContacts", 0))
		return 0;

	// Pass-through and approve if outgoing event.
	if (dbei->flags & DBEF_SENT) {
		if (_getOptB("ApproveOnMsgOut", 0)) {
			_setCOptB(hContact, "Verified", 1);
			if (_getOptB("AddPermanently", defaultAddPermanently))
				db_unset(hContact, "CList", "NotOnList");
			db_unset(hContact, "CList", "Delete");
		}
		return 0;
	}

	// Hide the contact until verified if option set.
	if (_getOptB("HideUnverified", defaultHideUnverified))
		db_set_b(hContact, "CList", "Hidden", 1);

	// Fetch the incoming message body
	if (dbei->eventType == EVENTTYPE_MESSAGE) {
		msgblob = (char *)dbei->pBlob;
	} else if (dbei->eventType == EVENTTYPE_AUTHREQUEST) {
		msgblob = (char *)(dbei->pBlob + sizeof(DWORD) + sizeof(HANDLE));
		for(a=4;a>0;a--)
			msgblob += strlen(msgblob)+1;
	}

	if (dbei->flags & DBEF_UTF)
		message = mir_utf8decodeW(msgblob);
	else
		message = mir_a2u(msgblob);

	
	/*** Check for words in white-list ***/

	if (_getOptB("ApproveOnMsgIn", defaultApproveOnMsgIn)) {
		whitelist = (TCHAR*)malloc(2048 * sizeof(TCHAR));
		if (whitelist != NULL) {
			_getOptS(whitelist, 2048, "ApproveOnMsgInWordlist", defaultApproveOnMsgInWordlist);
			if (_isregex(whitelist)) {
				if (_regmatch(message, whitelist))
					bCorrectResponse = TRUE;
			} else {
				ptok = _tcstok(whitelist, L" ");
				while (ptok != NULL) {
					if (_tcsstr(message, ptok)) {
						bCorrectResponse = TRUE;
						break;
					}
					ptok = _tcstok(NULL, L" ");
				}
			}
			free(whitelist);

			if (bCorrectResponse) {
				_setCOptB(hContact, "Verified", 1);
				if (_getOptB("HideUnverified", defaultHideUnverified))
					db_unset(hContact, "CList", "Hidden");
				if (_getOptB("AddPermanently", defaultAddPermanently))
					db_unset(hContact, "CList", "NotOnList");
				db_unset(hContact, "CList", "Delete");
				if (_getOptB("ReplyOnSuccess", defaultReplyOnSuccess) && (_getCOptB(hContact, "MsgSent", 0))) {
					tmp = mir_u2a(_getOptS(buf, buflen, "SuccessResponse", defaultSuccessResponse));
					response = mir_utf8encode(tmp);
					mir_free(tmp);
					CallContactService(hContact, PSS_MESSAGE, PREF_UTF,	(LPARAM)response);
					mir_free(response);
				}
				return 0;
			}
		}
	}


	/*** Check for correct answer ***/
	
	switch (_getOptB("Mode", defaultMode))
	{
		case SPAMOTRON_MODE_ROTATE:
		case SPAMOTRON_MODE_RANDOM:
			get_response(buf, buflen, _getCOptD(hContact, "ResponseNum", 0));
			if (_isregex(buf)) {
				if (_regmatch(message, buf))
					bCorrectResponse = TRUE;
			} else {
				if (_tcsstr_cc(message, buf, _getOptB("ResponseCC", defaultResponseCC)) &&
					(_tcslen(message) == _tcslen(buf)))
					bCorrectResponse = TRUE;
			}
			break;
		
		case SPAMOTRON_MODE_PLAIN:
			_getOptS(buf, buflen, "Response", defaultResponse);
			i = get_response_num(buf);
			while (i-- > 0) {
				get_response(buf, buflen, i-1);
				if (_isregex(buf)) {
					if (_regmatch(message, buf)) {
						bCorrectResponse = TRUE;
						break;
					}
				} else {
					if (_tcsstr_cc(message, buf, _getOptB("ResponseCC", defaultResponseCC)) &&
						(_tcslen(message) == _tcslen(buf))) {
						bCorrectResponse = TRUE;
						break;
					}
				}
			}
			break;

		case SPAMOTRON_MODE_MATH:
			if (message == NULL)
				break;
			_itot(_getCOptD(hContact, "ResponseMath", -1), buf, 10);
			if (_tcsstr(message, buf) && (_tcslen(buf) == _tcslen(message))) {
				bCorrectResponse = TRUE;
			}
			break;
	}

	if (bCorrectResponse)
	{
		_setCOptB(hContact, "Verified", 1);
		if (_getOptB("HideUnverified", defaultHideUnverified))
			db_unset(hContact, "CList", "Hidden");
		if (_getOptB("AddPermanently", defaultAddPermanently))
			db_unset(hContact, "CList", "NotOnList");
		db_unset(hContact, "CList", "Delete");
		db_unset(hContact, "CList", "ResponseNum");
		if (_getOptB("ReplyOnSuccess", defaultReplyOnSuccess)) {
			tmp = mir_u2a(_getOptS(buf, buflen, "SuccessResponse", defaultSuccessResponse));
			response = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF,	(LPARAM)response);
			mir_free(response);
		}
		_notify(hContact, POPUP_APPROVED, TranslateT("Contact %s approved."), NULL);

		// Resubmit pending authorization request
		if (_getCOptB(hContact, "AuthEventPending", FALSE)) {
			DBVARIANT _dbv;
			TCHAR AuthEventModule[100];
			char* szAuthEventModule;
			if (db_get(hContact, PLUGIN_NAME, "AuthEvent", &_dbv) == 0) {
				DBEVENTINFO *_dbei = (DBEVENTINFO *)malloc(sizeof(DBEVENTINFO));
				if (_dbei != NULL) {
					memcpy(&_dbei->cbBlob, _dbv.pbVal, sizeof(DWORD));
					_dbei->eventType = EVENTTYPE_AUTHREQUEST;
					_getCOptS(AuthEventModule, 100, hContact, "AuthEventModule", _T("ICQ"));
					szAuthEventModule = mir_u2a(AuthEventModule);
					_dbei->szModule = szAuthEventModule;
					_dbei->timestamp = dbei->timestamp;
					_dbei->flags = 0;
					_dbei->cbSize = sizeof(DBEVENTINFO);
					_dbei->pBlob = _dbv.pbVal + sizeof(DWORD);
					db_event_add(hContact,_dbei);
					db_unset(hContact, PLUGIN_NAME, "AuthEvent");
					db_unset(hContact, PLUGIN_NAME, "AuthEventPending");
					db_unset(hContact, PLUGIN_NAME, "AuthEventModule");
					mir_free(szAuthEventModule);
					free(_dbei);
				}
				db_free(&_dbv);
			}
		}

		// User approved, learn from previous messages
		if (bayesEnabled && _getOptB("BayesAutolearnApproved", defaultBayesAutolearnApproved))
			bayes_approve_contact(hContact);

		// Mark previous messages unread if option set
		if (_getOptB("KeepBlockedMsg", defaultKeepBlockedMsg) && 
			_getOptB("MarkMsgUnreadOnApproval", defaultMarkMsgUnreadOnApproval) &&
			hContact != NULL) {
			// We will mark unread all blocked messages for the most recent day
			MarkUnread(hContact);
		}

		return 1;
	}


	
	/*** Check for rejection ***/

	// Completely reject if challenge was already sent today for MaxMsgContactCountPerDay times
	// and the option is turned on.
	if (isOneDay(dbei->timestamp, _getCOptD(hContact, "MsgSentTime", 0)) &&
		_getOptD("MaxMsgContactCountPerDay", defaultMaxMsgContactCountPerDay) > 0 &&
		_getCOptD(hContact, "MsgSent", 0) >= _getOptD("MaxMsgContactCountPerDay", defaultMaxMsgContactCountPerDay)) {
			_notify(hContact, POPUP_BLOCKED, TranslateT("Message from %s rejected because it reached a maximum for challenge requests per day."), message);
			if (bayesEnabled)
				queue_message(hContact, dbei->timestamp, message);
			return 1;
	}

	// Completely reject if duplicate incoming message found
	if (_getOptD("MaxSameMsgCountPerDay", defaultMaxSameMsgCountPerDay) > 0 &&
		_getCOptD(hContact, "SameMsgCount", 0) >= _getOptD("MaxSameMsgCountPerDay", defaultMaxSameMsgCountPerDay) &&
		_tcscmp(message, _getCOptS(buf, buflen, hContact, "LastInMsg", _T(""))) == 0) {
			_notify(hContact, POPUP_BLOCKED, TranslateT("Message from %s rejected because it reached a maximum for same responses per day."), message);
			if (bayesEnabled)
				queue_message(hContact, dbei->timestamp, message);
			return 1;
	}

	// Completely reject if incoming message contains any word from DontReplyMsgWordlist option
	if (_getOptB("DontReplyMsg", defaultDontReplyMsg) &&
		Contains(message, _getOptS(buf, buflen, "DontReplyMsgWordlist", defaultDontReplyMsgWordlist))) {
		_notify(hContact, POPUP_BLOCKED, TranslateT("Message from %s dropped because it has a word from black list."), message);
		return 1;
	}

	
	/*** Bayes checks ***/

	// Drop if score > spam score
	if (bayesEnabled && _getOptB("BayesBlockMsg", defaultBayesBlockMsg))
		if (get_msg_score(message) >= (double)_getOptD("BayesSpamScore", defaultBayesSpamScore) * SCORE_C) {
			_notify(hContact, POPUP_BLOCKED, TranslateT("Message from %s dropped because of high spam score."), message);
			if (bayesEnabled && _getOptB("BayesAutolearnNotApproved", defaultBayesAutolearnNotApproved))
				queue_message(hContact, dbei->timestamp, message);
			return 1;
		}

	// Accept if score < ham score
	if (bayesEnabled && _getOptB("BayesAutoApprove", defaultBayesAutoApprove)) 
		if (get_msg_score(message) <= (double)_getOptD("BayesHamScore", defaultBayesHamScore) * SCORE_C) {
			_notify(hContact, POPUP_APPROVED, TranslateT("Contact %s approved."), message);
			_setCOptB(hContact, "Verified", 1);
			if (_getOptB("HideUnverified", defaultHideUnverified))
				db_unset(hContact, "CList", "Hidden");
			if (_getOptB("AddPermanently", defaultAddPermanently))
				db_unset(hContact, "CList", "NotOnList");
			db_unset(hContact, "CList", "Delete");
			if (bayesEnabled && 
				_getOptB("BayesAutolearnApproved", defaultBayesAutolearnApproved) &&
				_getOptB("BayesAutolearnAutoApproved", defaultBayesAutolearnAutoApproved)) {
				queue_message(hContact, dbei->timestamp, message);
				bayes_approve_contact(hContact);
			}
			return 0;
		}

	// Accept if event is EVENTTYPE_AUTHREQUEST and ReplyOnAuth is NOT set
		if (dbei->eventType == EVENTTYPE_AUTHREQUEST && !_getOptB("ReplyOnAuth", defaultReplyOnAuth))
			return 0;
	// Accept if event is EVENTTYPE_MESSAGE and ReplyOnMsg is NOT set
		if (dbei->eventType == EVENTTYPE_MESSAGE && !_getOptB("ReplyOnMsg", defaultReplyOnMsg))
			return 0;
		
	/*** Send Challenge ***/

	challengeW = (TCHAR *)malloc(maxmsglen*sizeof(TCHAR));
	tmpW = (TCHAR *)malloc(maxmsglen*sizeof(TCHAR));
	switch (_getOptB("Mode", defaultMode))
	{
		case SPAMOTRON_MODE_PLAIN:
			if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
				_getOptS(challengeW, maxmsglen, "AuthChallenge", defaultAuthChallenge);
			else
				_getOptS(challengeW, maxmsglen, "Challenge", defaultChallenge);
			ReplaceVars(challengeW, maxmsglen);
			tmp = mir_u2a(challengeW);
			challenge = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF, (LPARAM)challenge);
			mir_free(challenge);
			_notify(hContact, POPUP_CHALLENGE, TranslateT("Sending plain challenge to %s."), message);
			break;
		
		case SPAMOTRON_MODE_ROTATE:
			if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
				_getOptS(challengeW, maxmsglen, "AuthChallenge", defaultAuthChallenge);
			else
				_getOptS(challengeW, maxmsglen, "Challenge", defaultChallenge);
			_getOptS(buf, buflen, "Response", defaultResponse);
			if (_getCOptD(hContact, "ResponseNum", 0) >= (unsigned int)(get_response_num(buf)-1)) {
				_setCOptD(hContact, "ResponseNum", -1);
			}
			_setCOptD(hContact, "ResponseNum", _getCOptD(hContact, "ResponseNum", -1) + 1);
			ReplaceVarsNum(challengeW, maxmsglen, _getCOptD(hContact, "ResponseNum", 0));

			tmp = mir_u2a(challengeW);
			challenge = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF, (LPARAM)challenge);
			mir_free(challenge);
			_notify(hContact, POPUP_CHALLENGE, TranslateT("Sending round-robin challenge to %s."), message);
			break;

		case SPAMOTRON_MODE_RANDOM:
			if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
				_getOptS(challengeW, maxmsglen, "AuthChallenge", defaultAuthChallenge);
			else
				_getOptS(challengeW, maxmsglen, "Challenge", defaultChallenge);
			_getOptS(buf, buflen, "Response", defaultResponse);
			srand(time(NULL));
			_setCOptD(hContact, "ResponseNum", rand() % get_response_num(buf));
			ReplaceVarsNum(challengeW, maxmsglen, _getCOptD(hContact, "ResponseNum", 0));
			tmp = mir_u2a(challengeW);
			challenge = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF, (LPARAM)challenge);
			mir_free(challenge);
			_notify(hContact, POPUP_CHALLENGE, TranslateT("Sending random challenge to %s."), message);
			break;

		case SPAMOTRON_MODE_MATH:
			a = (rand() % 10) + 1;
			b = (rand() % 10) + 1;
			mir_sntprintf(mexpr, sizeof(mexpr), _T("%d + %d"), a, b);
			if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
				_getOptS(challengeW, maxmsglen, "AuthChallengeMath", defaultAuthChallengeMath);
			else
				_getOptS(challengeW, maxmsglen, "ChallengeMath", defaultChallengeMath);
			ReplaceVar(challengeW, maxmsglen, _T("%mathexpr%"), mexpr);
			_setCOptD(hContact, "ResponseMath", a + b);
			tmp = mir_u2a(challengeW);
			challenge = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF, (LPARAM)challenge);
			mir_free(challenge);
			_notify(hContact, POPUP_CHALLENGE, TranslateT("Sending math expression challenge to %s."), message);
			break;
	}
	free(challengeW);
	free(tmpW);

	// As a workaround for temporary NotOnList contact not being deleted from server-side list
	// (which was added by the ICQ server itself upon first outgoing challenge request message)
	// we need to set Delete setting, so that contacts gets deleted on next restart/connect.
	db_set_b(hContact, "CList", "Delete", 1);

	// Queue user message in Bayes db
	if (bayesEnabled && message != NULL)
		queue_message(hContact, dbei->timestamp, message);


	/*** Do any post-send procedures we need to do ***/

	// Increment MsgSent if it was sent the same day. Otherwise set it to 1.
	if (isOneDay(dbei->timestamp, _getCOptD(hContact, "MsgSentTime",0)))
		_setCOptD(hContact, "MsgSent", _getCOptD(hContact, "MsgSent", 0)+1);
	else 
		_setCOptD(hContact, "MsgSent", 1);
	_setCOptD(hContact, "MsgSentTime", dbei->timestamp);

	// Save Last Msg and update SameMsgCount
	if (message != NULL) {
		if (_tcscmp(_getCOptS(buf, buflen, hContact, "LastInMsg", _T("")), message) == 0)
			_setCOptD(hContact, "SameMsgCount", 1+_getCOptD(hContact, "SameMsgCount", 0));
		else 
			_setCOptD(hContact, "SameMsgCount", 1);
		_setCOptTS(hContact, "LastInMsg", message);
	}

	if (message != NULL)
		mir_free(message);

	// Finally silently save the message to contact history if corresponding option is set
	if (_getOptB("KeepBlockedMsg", defaultKeepBlockedMsg)) {
		if (dbei->eventType == EVENTTYPE_AUTHREQUEST) {
			// Save the request to database so that it can be automatically submitted on user approval
			PBYTE eventdata = (PBYTE)malloc(sizeof(DWORD) + dbei->cbBlob);
			if (eventdata != NULL && dbei->cbBlob > 0) {
				memcpy(eventdata, &dbei->cbBlob, sizeof(DWORD));
				memcpy(eventdata + sizeof(DWORD), dbei->pBlob, dbei->cbBlob);
				db_set_blob(hContact, PLUGIN_NAME, "AuthEvent", eventdata, sizeof(DWORD) + dbei->cbBlob);
				_setCOptS(hContact, "AuthEventModule", dbei->szModule);
				_setCOptB(hContact, "AuthEventPending", TRUE);
				free(eventdata);
			}
		} else {
			if (_getOptB("MarkMsgUnreadOnApproval", defaultMarkMsgUnreadOnApproval)) {
				DBVARIANT _dbv;
				DWORD dbei_size = 3*sizeof(DWORD) + sizeof(WORD) + dbei->cbBlob + (DWORD)strlen(dbei->szModule)+1;
				PBYTE eventdata = (PBYTE)malloc(dbei_size);
				PBYTE pos = eventdata;
				if (eventdata != NULL && dbei->cbBlob > 0) {
					if (db_get(hContact, PLUGIN_NAME, "LastMsgEvents", &_dbv) == 0) {
						eventdata = (PBYTE)realloc(eventdata, dbei_size + _dbv.cpbVal);
						pos = eventdata;
						memcpy(eventdata, _dbv.pbVal, _dbv.cpbVal);
						pos += _dbv.cpbVal;
						db_free(&_dbv);
					}
					memcpy(pos, &dbei->eventType, sizeof(WORD));
					memcpy(pos+sizeof(WORD), &dbei->flags, sizeof(DWORD));
					memcpy(pos+sizeof(WORD)+sizeof(DWORD), &dbei->timestamp, sizeof(DWORD));
					memcpy(pos+sizeof(WORD)+sizeof(DWORD)*2, dbei->szModule, strlen(dbei->szModule)+1);
					memcpy(pos+sizeof(WORD)+sizeof(DWORD)*2+strlen(dbei->szModule)+1, &dbei->cbBlob, sizeof(DWORD));
					memcpy(pos+sizeof(WORD)+sizeof(DWORD)*3+strlen(dbei->szModule)+1, dbei->pBlob, dbei->cbBlob);
					db_set_blob(hContact, PLUGIN_NAME, "LastMsgEvents", eventdata, (pos - eventdata) + dbei_size);
					free(eventdata);
				}
				
			} else {
				dbei->flags |= DBEF_READ;
				db_event_add(hContact, dbei);
			}
		}
	}
	return 1;
}
Beispiel #25
0
int CMraProto::MraDbSettingChanged(WPARAM hContact, LPARAM lParam)
{
	if (!m_bLoggedIn || !lParam || !hContact)
		return 0;

	DBCONTACTWRITESETTING *cws = (DBCONTACTWRITESETTING*)lParam;

	// это наш контакт, он не временный (есть в списке на сервере) и его обновление разрешено
	if (IsContactMra(hContact) && !db_get_b(hContact, "CList", "NotOnList", 0) && getDword(hContact, "HooksLocked", FALSE) == FALSE) {
		if (!strcmp(cws->szModule, "CList")) {
			// MyHandle setting
			if (!strcmp(cws->szSetting, "MyHandle")) {
				// always store custom nick
				CMStringW wszNick;
				if (cws->value.type == DBVT_DELETED) {
					wszNick = GetContactNameW(hContact);
					db_set_ws(hContact, "CList", "MyHandle", wszNick);
				}
				else if (cws->value.pszVal) {
					switch (cws->value.type) {
					case DBVT_WCHAR:
						wszNick = cws->value.pwszVal;
						break;
					case DBVT_UTF8:
						wszNick = ptrW(mir_utf8decodeW(cws->value.pszVal));
						break;
					case DBVT_ASCIIZ:
						wszNick = ptrW(mir_a2u_cp(cws->value.pszVal, MRA_CODE_PAGE));
						break;
					}
					if (wszNick.GetLength())
						MraModifyContact(hContact, 0, 0, 0, 0, &wszNick);
				}
			}
			// Group setting
			else if (!strcmp(cws->szSetting, "Group")) {
				CMStringW wszGroup;
				// manage group on server
				switch (cws->value.type) {
				case DBVT_WCHAR:
					wszGroup = cws->value.pwszVal;
					break;
				case DBVT_UTF8:
					wszGroup = ptrW(mir_utf8decodeW(cws->value.pszVal));
					break;
				case DBVT_ASCIIZ:
					wszGroup = ptrW(mir_a2u_cp(cws->value.pszVal, MRA_CODE_PAGE));
					break;
				}
				if (wszGroup.GetLength()) {
					DWORD dwGroupID = getDword(hContact, "GroupID", -1);
					if (dwGroupID != -1)
						MraMoveContactToGroup(hContact, dwGroupID, wszGroup);
				}
			}
			// NotOnList setting. Has a temporary contact just been added permanently?
			else if (!strcmp(cws->szSetting, "NotOnList")) {
				if (cws->value.type == DBVT_DELETED || (cws->value.type == DBVT_BYTE && cws->value.bVal == 0)) {
					CMStringW wszAuthMessage;
					if (!mraGetStringW(NULL, "AuthMessage", wszAuthMessage))
						wszAuthMessage = TranslateT(MRA_DEFAULT_AUTH_MESSAGE);

					db_unset(hContact, "CList", "Hidden");

					CMStringA szEmail, szPhones;
					CMStringW wszNick;
					DWORD dwGroupID, dwContactFlag;
					GetContactBasicInfoW(hContact, NULL, &dwGroupID, &dwContactFlag, NULL, NULL, &szEmail, &wszNick, &szPhones);
					MraAddContact(hContact, dwContactFlag, dwGroupID, szEmail, wszNick, &szPhones, &wszAuthMessage);
				}
			}
			// Hidden setting
			else if (!strcmp(cws->szSetting, "Hidden")) {
				DWORD dwContactFlag = GetContactFlags(hContact);
				if (cws->value.type == DBVT_DELETED || (cws->value.type == DBVT_BYTE && cws->value.bVal == 0))
					dwContactFlag &= ~CONTACT_FLAG_SHADOW;
				else
					dwContactFlag |= CONTACT_FLAG_SHADOW;

				MraModifyContact(hContact, 0, &dwContactFlag);
			}
		}
		// Ignore section
		else if (!strcmp(cws->szModule, "Ignore")) {
			if (!strcmp(cws->szSetting, "Mask1")) {
				DWORD dwContactFlag = GetContactFlags(hContact);
				if (cws->value.type == DBVT_DELETED || (cws->value.type == DBVT_DWORD && cws->value.dVal&IGNOREEVENT_MESSAGE) == 0)
					dwContactFlag &= ~CONTACT_FLAG_IGNORE;
				else
					dwContactFlag |= CONTACT_FLAG_IGNORE;

				MraModifyContact(hContact, 0, &dwContactFlag);
			}
		}
		// User info section
		else if (!strcmp(cws->szModule, "UserInfo")) {
			if (!strcmp(cws->szSetting, "MyPhone0") || !strcmp(cws->szSetting, "MyPhone1") || !strcmp(cws->szSetting, "MyPhone2"))
				MraModifyContact(hContact);
		}
	}
	return 0;
}
Beispiel #26
0
void __cdecl FindSettings(LPVOID param)
{
	FindInfo* fi = (FindInfo*)param;
	HWND hwndParent = GetParent(fi->hwnd);

	ModuleSettingLL ModuleList, SettingList;
	ModSetLinkLinkItem *module, *setting;

	MCONTACT hContact;
	DBVARIANT dbv = { 0 };

	int foundCount = 0, replaceCount = 0, deleteCount = 0;

	DWORD numsearch = 0, numreplace = 0;
	int NULLContactDone = 0;

	if (!fi->search || !EnumModules(&ModuleList)) {
		fi_free(fi);
		return;
	}

	_T2A search(fi->search);
	_T2A replace(fi->replace);

	// skip modules and setting names on unicode search or replace
	if (IsRealUnicode(fi->search) || IsRealUnicode(fi->replace)) {
		fi->options &= ~(F_SETNAME | F_MODNAME);
		fi->options |= F_UNICODE;
	}

	if (!(fi->options & F_UNICODE) && (fi->options & F_SETVAL)) {
		char val[16];
		numsearch = strtoul(search, nullptr, 10);
		_ultoa(numsearch, val, 10);
		if (!mir_strcmp(search, val)) {
			fi->options |= F_NUMSRCH;
			// replace numeric values only entirely
			if (replace && (fi->options & F_ENTIRE)) {
				numreplace = strtoul(replace, nullptr, 10);
				_ultoa(numreplace, val, 10);
				if (!replace[0] || !mir_strcmp(replace, val))
					fi->options |= F_NUMREPL;
			}
		}
	}

	SendDlgItemMessage(hwndParent, IDC_SBAR, SB_SETTEXT, 0, (LPARAM)TranslateT("Searching..."));

	hContact = 0;

	while (GetWindowLongPtr(GetDlgItem(hwndParent, IDC_SEARCH), GWLP_USERDATA)) {

		if (!hContact) {
			if (NULLContactDone)
				break;
			else {
				NULLContactDone = 1;
				hContact = db_find_first();
			}
		}
		else hContact = db_find_next(hContact);

		for (module = ModuleList.first; module; module = module->next) {

			if (IsModuleEmpty(hContact, module->name))
				continue;

			if (fi->options & (F_SETVAL | F_SETNAME)) {

				if (!EnumSettings(hContact, module->name, &SettingList)) {
					fi_free(fi);
					FreeModuleSettingLL(&ModuleList);
					return;
				}

				for (setting = SettingList.first; setting; setting = setting->next) {

					dbv.type = 0;
					if (db_get_s(hContact, module->name, setting->name, &dbv, 0))
						continue;

					// check in settings value				
					if (fi->options & F_SETVAL) {

						wchar_t *value = nullptr;

						switch (dbv.type) {

						case DBVT_BYTE:
						case DBVT_WORD:
						case DBVT_DWORD:
							if ((fi->options & F_NUMSRCH) && numsearch == getNumericValue(&dbv)) {
								wchar_t *val = fi->search;
								int flag = F_SETVAL;

								if (fi->options & F_NUMREPL) {
									if (replace[0]) {
										db_unset(hContact, module->name, setting->name);
										flag |= F_DELETED;
										deleteCount++;
									}
									else
										if (setNumericValue(hContact, module->name, setting->name, numreplace, dbv.type)) {
											val = fi->replace;
											flag |= F_REPLACED;
											replaceCount++;
										}
								}

								ItemFound(fi->hwnd, hContact, module->name, setting->name, val, flag);
							}
							break;

						case DBVT_WCHAR:
							if (!value) value = mir_wstrdup(dbv.pwszVal);
						case DBVT_UTF8:
							if (!value) value = mir_utf8decodeW(dbv.pszVal);
						case DBVT_ASCIIZ:
							if (!value) value = mir_a2u(dbv.pszVal);

							if (FindMatchT(value, fi->search, fi->options)) {
								foundCount++;
								ptrW ptr;
								wchar_t *newValue = value;
								int flag = F_SETVAL;

								if (fi->replace) {
									newValue = (fi->options & F_ENTIRE) ? fi->replace : ptr = multiReplaceT(value, fi->search, fi->replace, fi->options & F_CASE);
									// !!!! delete or make empty ?
									if (!newValue[0]) {
										db_unset(hContact, module->name, setting->name);
										flag |= F_DELETED;
										newValue = value;
										deleteCount++;
									}
									else {
#ifdef _UNICODE
										// save as unicode if needed
										if (dbv.type != DBVT_ASCIIZ || IsRealUnicode(newValue))
											db_set_ws(hContact, module->name, setting->name, newValue);
										else
#endif
											db_set_s(hContact, module->name, setting->name, _T2A(newValue));
										flag |= F_REPLACED;
										replaceCount++;
									}
								}

								ItemFound(fi->hwnd, hContact, module->name, setting->name, newValue, flag);
							}
							mir_free(value);
							break;
						} // switch
					}

					// check in setting name
					if ((fi->options & F_SETNAME) && FindMatchA(setting->name, search, fi->options)) {
						foundCount++;
						ptrA ptr;
						char *newSetting = setting->name;
						int flag = F_SETNAME;

						if (replace) {
							newSetting = (fi->options & F_ENTIRE) ? replace : ptr = multiReplaceA(setting->name, search, replace, fi->options & F_CASE);

							if (!newSetting[0]) {
								db_unset(hContact, module->name, setting->name);
								flag |= F_DELETED;
								newSetting = setting->name;
								deleteCount++;
							}
							else {
								DBVARIANT dbv2;
								// skip if exist
								if (!db_get_s(hContact, module->name, newSetting, &dbv2, 0))
									db_free(&dbv2);
								else if (!db_set(hContact, module->name, newSetting, &dbv)) {
									db_unset(hContact, module->name, setting->name);
									flag |= F_REPLACED;
									replaceCount++;
								}
							}
						}

						ItemFound(fi->hwnd, hContact, module->name, newSetting, nullptr, flag);
					}

					db_free(&dbv);

				} // for(setting)

				FreeModuleSettingLL(&SettingList);
			}

			// check in module name
			if ((fi->options & F_MODNAME) && FindMatchA(module->name, search, fi->options)) {
				foundCount++;
				char *newModule = module->name;
				int flag = F_MODNAME;
				ptrA ptr;

				if (replace) {
					newModule = (fi->options & F_ENTIRE) ? replace : ptr = multiReplaceA(module->name, search, replace, fi->options & F_CASE);

					if (!newModule[0]) {
						deleteModule(hContact, module->name, 0);
						replaceTreeItem(hContact, module->name, nullptr);
						flag |= F_DELETED;
						newModule = module->name;
						deleteCount++;
					}
					else if (renameModule(hContact, module->name, newModule)) {
						replaceTreeItem(hContact, module->name, nullptr);
						flag |= F_REPLACED;
						replaceCount++;
					}
				}

				ItemFound(fi->hwnd, hContact, newModule, nullptr, nullptr, flag);
			}

		} // for(module)
	}

	wchar_t msg[MSG_SIZE];
	mir_snwprintf(msg, TranslateT("Finished. Items found: %d / replaced: %d / deleted: %d"), foundCount, replaceCount, deleteCount);
	SendDlgItemMessage(hwndParent, IDC_SBAR, SB_SETTEXT, 0, (LPARAM)msg);

	if (fi->replace) {
		EnableWindow(GetDlgItem(hwndParent, IDC_SEARCH), 1);
		SetDlgItemText(hwndParent, IDOK, TranslateT("&Replace"));
	}
	else {
		SetDlgItemText(hwndParent, IDC_SEARCH, TranslateT("&Search"));
		EnableWindow(GetDlgItem(hwndParent, IDOK), 1);
	}

	fi_free(fi);
	FreeModuleSettingLL(&ModuleList);

	SetWindowLongPtr(GetDlgItem(hwndParent, IDC_SEARCH), GWLP_USERDATA, 0);
	EnableWindow(GetDlgItem(hwndParent, IDCANCEL), 1);
}
unsigned int CSettings::ReadSetting(TDBTSetting & Setting, TDBTSettingHandle hSetting)
{
	CBlockManager * file = &m_BlockManagerPri;

	if (hSetting & cSettingsFileFlag)
	{
		file = &m_BlockManagerSet;
		hSetting = hSetting & ~cSettingsFileFlag;
	}

	uint32_t sig = cSettingSignature;
	uint32_t size = 0;

	if (hSetting == 0)
		return DBT_INVALIDPARAM;

	CBlockManager::ReadTransaction trans(*file);

	TSetting * setting = file->ReadBlock<TSetting>(hSetting, size, sig);

	if (!setting)
		return DBT_INVALIDPARAM;
	
	uint8_t* str = reinterpret_cast<uint8_t*>(setting + 1) + setting->NameLength + 1;

	if (Setting.Type == 0)
	{
		Setting.Type = setting->Type;
		if (setting->Type & DBT_STF_VariableLength)
		{
			Setting.Value.Length = setting->BlobLength;
			switch (setting->Type)
			{
				case DBT_ST_WCHAR:
				{
					Setting.Value.Length = setting->BlobLength / sizeof(wchar_t);
					Setting.Value.pWide = (wchar_t*) mir_realloc(Setting.Value.pWide, sizeof(wchar_t) * Setting.Value.Length);
					memcpy(Setting.Value.pWide, str, setting->BlobLength);
					Setting.Value.pWide[Setting.Value.Length - 1] = 0;

				} break;
				case DBT_ST_ANSI: case DBT_ST_UTF8:
				{
					Setting.Value.Length = setting->BlobLength;
					Setting.Value.pAnsi = (char *) mir_realloc(Setting.Value.pAnsi, setting->BlobLength);
					memcpy(Setting.Value.pAnsi, str, setting->BlobLength);
					Setting.Value.pAnsi[Setting.Value.Length - 1] = 0;

				} break;
				default:
				{
					Setting.Value.Length = setting->BlobLength;
					Setting.Value.pBlob = (uint8_t *) mir_realloc(Setting.Value.pBlob, setting->BlobLength);
					memcpy(Setting.Value.pBlob, str, setting->BlobLength);
				} break;
			}
		} else {
			Setting.Value.QWord = setting->Value.QWord;
		}
	} else {
		switch (setting->Type)
		{
			case DBT_ST_BYTE: case DBT_ST_WORD: case DBT_ST_DWORD: case DBT_ST_QWORD:
				{
					switch (Setting.Type)
					{
						case DBT_ST_BYTE:  Setting.Value.Byte  = (uint8_t)   setting->Value.QWord; break;
						case DBT_ST_WORD:  Setting.Value.Word  = (uint16_t)  setting->Value.QWord; break;
						case DBT_ST_DWORD: Setting.Value.DWord = (uint32_t)  setting->Value.QWord; break;
						case DBT_ST_QWORD: Setting.Value.QWord = (uint64_t)  setting->Value.QWord; break;
						case DBT_ST_CHAR:  Setting.Value.Char  = ( int8_t)   setting->Value.QWord; break;
						case DBT_ST_SHORT: Setting.Value.Short = ( int16_t)  setting->Value.QWord; break;
						case DBT_ST_INT:   Setting.Value.Int   = ( int32_t)  setting->Value.QWord; break;
						case DBT_ST_INT64: Setting.Value.Int64 = ( int64_t)  setting->Value.QWord; break;
						case DBT_ST_BOOL:  Setting.Value.Bool  = setting->Value.QWord != 0; break;

						case DBT_ST_ANSI: case DBT_ST_UTF8:
							{
								char buffer[24];
								buffer[0] = 0;
								Setting.Value.Length = 1 + sprintf_s(buffer, "%llu", setting->Value.QWord);
								Setting.Value.pAnsi = (char *) mir_realloc(Setting.Value.pAnsi, Setting.Value.Length);
								memcpy(Setting.Value.pAnsi, buffer, Setting.Value.Length);

							} break;
						case DBT_ST_WCHAR:
							{
								wchar_t buffer[24];
								buffer[0] = 0;
								Setting.Value.Length = 1 + swprintf_s(buffer, L"%llu", setting->Value.QWord);
								Setting.Value.pWide = (wchar_t *) mir_realloc(Setting.Value.pWide, Setting.Value.Length * sizeof(wchar_t));
								memcpy(Setting.Value.pWide, buffer, Setting.Value.Length * sizeof(wchar_t));

							} break;
						case DBT_ST_BLOB:
							{
								Setting.Value.Length = 0;
								switch (setting->Type)
								{
									case DBT_ST_BYTE:  Setting.Value.Length = 1; break;
									case DBT_ST_WORD:  Setting.Value.Length = 2; break;
									case DBT_ST_DWORD: Setting.Value.Length = 4; break;
									case DBT_ST_QWORD: Setting.Value.Length = 8; break;
								}

								Setting.Value.pBlob = (uint8_t *) mir_realloc(Setting.Value.pBlob, Setting.Value.Length);
								memcpy(Setting.Value.pBlob, &setting->Value, Setting.Value.Length);


							} break;
					}

				} break;
			case DBT_ST_CHAR: case DBT_ST_SHORT: case DBT_ST_INT: case DBT_ST_INT64:
				{
					int64_t val = 0;
					switch (setting->Type)
					{
						case DBT_ST_CHAR:  val = setting->Value.Char;  break;
						case DBT_ST_SHORT: val = setting->Value.Short; break;
						case DBT_ST_INT:   val = setting->Value.Int;   break;
						case DBT_ST_INT64: val = setting->Value.Int64; break;
					}
					switch (Setting.Type)
					{
						case DBT_ST_BYTE:  Setting.Value.Byte  = (uint8_t)   val; break;
						case DBT_ST_WORD:  Setting.Value.Word  = (uint16_t)  val; break;
						case DBT_ST_DWORD: Setting.Value.DWord = (uint32_t)  val; break;
						case DBT_ST_QWORD: Setting.Value.QWord = (uint64_t)  val; break;
						case DBT_ST_CHAR:  Setting.Value.Char  = ( int8_t)   val; break;
						case DBT_ST_SHORT: Setting.Value.Short = ( int16_t)  val; break;
						case DBT_ST_INT:   Setting.Value.Int   = ( int32_t)  val; break;
						case DBT_ST_INT64: Setting.Value.Int64 = ( int64_t)  val; break;
						case DBT_ST_BOOL:  Setting.Value.Bool  = val != 0; break;

						case DBT_ST_ANSI: case DBT_ST_UTF8:
							{
								char buffer[24];
								buffer[0] = 0;
								Setting.Value.Length = 1 + sprintf_s(buffer, "%lli", val);
								Setting.Value.pAnsi = (char *) mir_realloc(Setting.Value.pAnsi, Setting.Value.Length);
								memcpy(Setting.Value.pAnsi, buffer, Setting.Value.Length);

							} break;
						case DBT_ST_WCHAR:
							{
								wchar_t buffer[24];
								buffer[0] = 0;
								Setting.Value.Length = 1 + swprintf_s(buffer, L"%lli", val);
								Setting.Value.pWide = (wchar_t *) mir_realloc(Setting.Value.pWide, Setting.Value.Length * sizeof(wchar_t));
								memcpy(Setting.Value.pWide, buffer, Setting.Value.Length * sizeof(wchar_t));

							} break;
						case DBT_ST_BLOB:
							{
								Setting.Value.Length = 0;
								switch (setting->Type)
								{
									case DBT_ST_CHAR:  Setting.Value.Length = 1; break;
									case DBT_ST_SHORT: Setting.Value.Length = 2; break;
									case DBT_ST_INT:   Setting.Value.Length = 4; break;
									case DBT_ST_INT64: Setting.Value.Length = 8; break;
								}

								Setting.Value.pBlob = (unsigned char *) mir_realloc(Setting.Value.pBlob, Setting.Value.Length);
								memcpy(Setting.Value.pBlob, &setting->Value, Setting.Value.Length);

							} break;
					}

				} break;
			case DBT_ST_FLOAT: case DBT_ST_DOUBLE:
				{
					double val = 0;
					if (setting->Type == DBT_ST_DOUBLE)
						val = setting->Value.Double;
					else
						val = setting->Value.Float;

					switch (Setting.Type)
					{
						case DBT_ST_BYTE:  Setting.Value.Byte  = (uint8_t)   floor(val); break;
						case DBT_ST_WORD:  Setting.Value.Word  = (uint16_t)  floor(val); break;
						case DBT_ST_DWORD: Setting.Value.DWord = (uint32_t)  floor(val); break;
						case DBT_ST_QWORD: Setting.Value.QWord = (uint64_t)  floor(val); break;
						case DBT_ST_CHAR:  Setting.Value.Char  = ( int8_t)   floor(val); break;
						case DBT_ST_SHORT: Setting.Value.Short = ( int16_t)  floor(val); break;
						case DBT_ST_INT:   Setting.Value.Int   = ( int32_t)  floor(val); break;
						case DBT_ST_INT64: Setting.Value.Int64 = ( int64_t)  floor(val); break;
						case DBT_ST_BOOL:  Setting.Value.Bool  = val != 0; break;

						case DBT_ST_ANSI: case DBT_ST_UTF8:
							{
								char buffer[128];
								buffer[0] = 0;
								Setting.Value.Length = 1 + sprintf_s(buffer, "%lf", setting->Value.QWord);
								Setting.Value.pAnsi = (char *) mir_realloc(Setting.Value.pAnsi, Setting.Value.Length);
								memcpy(Setting.Value.pAnsi, buffer, Setting.Value.Length);
							} break;
						case DBT_ST_WCHAR:
							{
								wchar_t buffer[128];
								buffer[0] = 0;
								Setting.Value.Length = 1 + swprintf_s(buffer, L"%lf", setting->Value.QWord);
								Setting.Value.pWide = (wchar_t *) mir_realloc(Setting.Value.pWide, Setting.Value.Length * sizeof(wchar_t));
								memcpy(Setting.Value.pWide, buffer, Setting.Value.Length * sizeof(wchar_t));
							} break;
						case DBT_ST_BLOB:
							{
								Setting.Value.Length = 4;
								if (setting->Type == DBT_ST_DOUBLE)
									Setting.Value.Length = 8;

								Setting.Value.pBlob = (uint8_t*) mir_realloc(Setting.Value.pBlob, Setting.Value.Length);
								memcpy(Setting.Value.pBlob, &setting->Value, Setting.Value.Length);

							} break;
					}

				} break;
			case DBT_ST_BOOL:
				{
					switch (Setting.Type)
					{
						case DBT_ST_BYTE: case DBT_ST_WORD: case DBT_ST_DWORD: case DBT_ST_QWORD:
						case DBT_ST_CHAR: case DBT_ST_SHORT: case DBT_ST_INT: case DBT_ST_INT64:
							{
								if (setting->Value.Bool)
									Setting.Value.QWord = 1;
								else
									Setting.Value.QWord = 0;
							} break;
						case DBT_ST_FLOAT:
							{
								if (setting->Value.Bool)
									Setting.Value.Float = 1;
								else
									Setting.Value.Float = 0;
							} break;
						case DBT_ST_DOUBLE:
							{
								if (setting->Value.Bool)
									Setting.Value.Double = 1;
								else
									Setting.Value.Double = 0;
							} break;
						case DBT_ST_ANSI: case DBT_ST_UTF8:
							{
								char * buffer = "false";
								Setting.Value.Length = 5;
								if (setting->Value.Bool)
								{
									buffer = "true";
									Setting.Value.Length = 4;
								}

								Setting.Value.pAnsi = (char *) mir_realloc(Setting.Value.pAnsi, Setting.Value.Length);
								memcpy(Setting.Value.pAnsi, buffer, Setting.Value.Length);
							} break;
						case DBT_ST_WCHAR:
							{
								wchar_t * buffer = L"false";
								Setting.Value.Length = 5;
								if (setting->Value.Bool)
								{
									buffer = L"true";
									Setting.Value.Length = 4;
								}

								Setting.Value.pWide = (wchar_t *) mir_realloc(Setting.Value.pWide, Setting.Value.Length * sizeof(wchar_t));
								memcpy(Setting.Value.pWide, buffer, Setting.Value.Length * sizeof(wchar_t));
							} break;
						case DBT_ST_BLOB:
							{
								Setting.Value.pBlob = (uint8_t*) mir_realloc(Setting.Value.pBlob, sizeof(bool));
								(*((bool*)Setting.Value.pBlob)) = setting->Value.Bool;
								Setting.Value.Length = sizeof(bool);
							} break;
					}
				} break;
			case DBT_ST_ANSI:
				{
					str[setting->BlobLength - 1] = 0;

					switch (Setting.Type)
					{
						case DBT_ST_BYTE: case DBT_ST_WORD: case DBT_ST_DWORD: case DBT_ST_QWORD: case DBT_ST_BOOL:
						case DBT_ST_CHAR: case DBT_ST_SHORT: case DBT_ST_INT: case DBT_ST_INT64:
							{
								Setting.Value.QWord = 0;
							} break;
						case DBT_ST_ANSI:
							{
								Setting.Value.Length = setting->BlobLength;
								Setting.Value.pAnsi = (char *) mir_realloc(Setting.Value.pAnsi, setting->BlobLength);
								memcpy(Setting.Value.pAnsi, str, setting->BlobLength);
							} break;
						case DBT_ST_UTF8:
							{
								Setting.Value.pUTF8 = mir_utf8encode((char*)str);
								Setting.Value.Length = static_cast<uint32_t>(strlen(Setting.Value.pUTF8) + 1);
							} break;
						case DBT_ST_WCHAR:
							{
								Setting.Value.pWide = mir_a2u((char*)str);
								Setting.Value.Length = static_cast<uint32_t>(wcslen(Setting.Value.pWide) + 1);
							} break;
						case DBT_ST_BLOB:
							{
								Setting.Value.Length = setting->BlobLength;
								Setting.Value.pBlob = (uint8_t *) mir_realloc(Setting.Value.pBlob, setting->BlobLength);
								memcpy(Setting.Value.pBlob, str, setting->BlobLength);
							} break;
					}
				} break;
			case DBT_ST_UTF8:
				{
					str[setting->BlobLength - 1] = 0;

					switch (Setting.Type)
					{
						case DBT_ST_BYTE: case DBT_ST_WORD: case DBT_ST_DWORD: case DBT_ST_QWORD: case DBT_ST_BOOL:
						case DBT_ST_CHAR: case DBT_ST_SHORT: case DBT_ST_INT: case DBT_ST_INT64:
							{
								Setting.Value.QWord = 0;
							} break;
						case DBT_ST_ANSI:
							{
								mir_utf8decode((char*)str, NULL);
								Setting.Value.Length = static_cast<uint32_t>(strlen((char*)str) + 1);
								Setting.Value.pAnsi = (char *) mir_realloc(Setting.Value.pAnsi, Setting.Value.Length);
								memcpy(Setting.Value.pAnsi, str, Setting.Value.Length);
							} break;
						case DBT_ST_UTF8:
							{
								Setting.Value.Length = setting->BlobLength;
								Setting.Value.pUTF8 = (char *) mir_realloc(Setting.Value.pUTF8, setting->BlobLength);
								memcpy(Setting.Value.pUTF8, str, setting->BlobLength);
							} break;
						case DBT_ST_WCHAR:
							{
								Setting.Value.pWide = mir_utf8decodeW((char*)str);
								if (Setting.Value.pWide)
								{
									Setting.Value.Length = static_cast<uint32_t>(wcslen(Setting.Value.pWide) + 1);
								} else {
									Setting.Value.Length = 0;
									Setting.Type = 0;
								}
							} break;
						case DBT_ST_BLOB:
							{
								Setting.Value.pBlob = (uint8_t *) mir_realloc(Setting.Value.pBlob, setting->BlobLength);
								memcpy(Setting.Value.pBlob, str, setting->BlobLength);
								Setting.Value.Length = setting->BlobLength;
							} break;
					}
				} break;
			case DBT_ST_WCHAR:
				{
					((wchar_t*)str)[setting->BlobLength / sizeof(wchar_t) - 1] = 0;

					switch (Setting.Type)
					{
						case DBT_ST_BYTE: case DBT_ST_WORD: case DBT_ST_DWORD: case DBT_ST_QWORD: case DBT_ST_BOOL:
						case DBT_ST_CHAR: case DBT_ST_SHORT: case DBT_ST_INT: case DBT_ST_INT64:
							{
								Setting.Value.QWord = 0;
							} break;
						case DBT_ST_ANSI:
							{
								Setting.Value.pAnsi = mir_u2a((wchar_t*)str);
								Setting.Value.Length = static_cast<uint32_t>(strlen(Setting.Value.pAnsi) + 1);
							} break;
						case DBT_ST_UTF8:
							{
								Setting.Value.pUTF8 = mir_utf8encodeW((wchar_t*)str);
								Setting.Value.Length = static_cast<uint32_t>(strlen(Setting.Value.pUTF8) + 1);
							} break;
						case DBT_ST_WCHAR:
							{
								Setting.Value.Length = setting->BlobLength / sizeof(wchar_t);
								Setting.Value.pWide = (wchar_t*) mir_realloc(Setting.Value.pWide, Setting.Value.Length * sizeof(wchar_t));
								memcpy(Setting.Value.pWide, str, Setting.Value.Length * sizeof(wchar_t));
							} break;
						case DBT_ST_BLOB:
							{
								Setting.Value.pBlob = (uint8_t *) mir_realloc(Setting.Value.pBlob, setting->BlobLength);
								memcpy(Setting.Value.pBlob, str, setting->BlobLength);
								Setting.Value.Length = setting->BlobLength;
							} break;
					}
				} break;
			case DBT_ST_BLOB:
				{
					switch (Setting.Type)
					{
						case DBT_ST_BYTE: case DBT_ST_WORD: case DBT_ST_DWORD: case DBT_ST_QWORD: case DBT_ST_BOOL:
						case DBT_ST_CHAR: case DBT_ST_SHORT: case DBT_ST_INT: case DBT_ST_INT64:
							{
								Setting.Value.QWord = 0;
							} break;
						case DBT_ST_ANSI: case DBT_ST_WCHAR: case DBT_ST_UTF8:
							{
								Setting.Value.Length = 0;
								if (Setting.Value.pBlob)
									mir_free(Setting.Value.pBlob);

								Setting.Value.pBlob = NULL;
							} break;
						case DBT_ST_BLOB:
							{
								Setting.Value.pBlob = (uint8_t *) mir_realloc(Setting.Value.pBlob, setting->BlobLength);
								memcpy(Setting.Value.pBlob, str, setting->BlobLength);
								Setting.Value.Length = setting->BlobLength;
							} break;
					}
				} break;

		}
	}


	if (Setting.Descriptor)
	{
		Setting.Descriptor->Entity = setting->Entity;
		Setting.Descriptor->FoundInEntity = setting->Entity;

		Setting.Descriptor->pszSettingName = (char *) mir_realloc(Setting.Descriptor->pszSettingName, setting->NameLength + 1);
		memcpy(Setting.Descriptor->pszSettingName, setting + 1, setting->NameLength + 1);
		Setting.Descriptor->pszSettingName[setting->NameLength] = 0;
	}

	return setting->Type;
}
Beispiel #28
0
int Parser()
{
    static NETLIBPACKETRECVER nlpr = {0};
    char *ptr;
    char tmp[256];
    int i;
    char *buf;
    static char ver[16];
    nlpr.cbSize = sizeof(nlpr);
    nlpr.dwTimeout = 5;
    if(!ghConnection)
    {
        mir_forkthread(&Start, 0);
    }
    if(ghConnection)
    {
        int recvResult;
        /*		do
        		{
        			recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
        			if(recvResult == SOCKET_ERROR)
        			{
        				ReStart();
        				return 1;
        			}
        		}
        		while(recvResult > 0);*/
        if(!Connected)
        {
            char tmp[128];
            char *tmp2 = mir_t2a(gbPassword);
            recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
            if(recvResult == SOCKET_ERROR)
            {
                mir_forkthread(&ReStart, 0);
//				ReStart();
                return 1;
            }
            if(strlen(tmp2) > 2)
            {
                strcpy(tmp, "password ");
                strcat(tmp, tmp2);
                strcat(tmp, "\n");
                Netlib_Send(ghConnection, tmp, (int)strlen(tmp), 0);
                recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
                if(recvResult == SOCKET_ERROR)
                {
                    mir_forkthread(&ReStart, 0);
                    return 1;
                }
            }
            mir_free(tmp2);
        }
        Netlib_Send(ghConnection, "status\n", (int)strlen("status\n"), 0);
        recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
        if(recvResult == SOCKET_ERROR)
        {
            mir_forkthread(&ReStart, 0);
            return 1;
        }
        Netlib_Send(ghConnection, "currentsong\n", (int)strlen("currentsong\n"), 0);
        recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
        if(recvResult == SOCKET_ERROR)
        {
            mir_forkthread(&ReStart, 0);
            return 1;
        }
        nlpr.bytesUsed = nlpr.bytesAvailable;
    }
    buf = (char*)nlpr.buffer;
    if(ptr = strstr(buf, "MPD"))
    {
        Connected = TRUE;
        ptr = &ptr[4];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        strcpy(ver, tmp);
        SongInfo.txtver = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.txtver = (TCHAR*)mir_utf8decodeW(ver);
    if(ptr = strstr(buf, "file:"))
    {
        ptr = &ptr[6];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.mfile = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.mfile = _T("");
    if(ptr = strstr(buf, "Time:"))
    {
        ptr = &ptr[6];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.total = atoi(tmp);
    }
    else if(!SongInfo.total)
        SongInfo.total = 0;
    if(ptr = strstr(buf, "time:"))
    {
        ptr = &ptr[6];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.time = atoi(tmp);
    }
    else if(!SongInfo.time)
        SongInfo.time = 0;
    if(ptr = strstr(buf, "Title:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.title = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.title = _T("Unknown track");
    if(ptr = strstr(buf, "Artist:"))
    {
        ptr = &ptr[8];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.artist = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.artist = _T("Unknown artist");
    if(ptr = strstr(buf, "Genre:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.genre = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.genre = _T("Unknown genre");
    if(ptr = strstr(buf, "Album:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.album = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.album = _T("Unknown album");
    if(ptr = strstr(buf, "Date:"))
    {
        ptr = &ptr[6];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.year = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.year = _T("Unknown year");
    if(ptr = strstr(buf, "volume:"))
    {
        ptr = &ptr[8];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.volume = atoi(tmp);
    }
    else if(!SongInfo.volume)
        SongInfo.volume = 0;
    if(ptr = strstr(buf, "audio:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.khz = atoi(tmp);
    }
    else if(!SongInfo.khz)
        SongInfo.khz = 0;
    if(ptr = strstr(buf, "bitrate:"))
    {
        ptr = &ptr[9];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.kbps = atoi(tmp);
    }
    else if(!SongInfo.kbps)
        SongInfo.kbps = 0;

    if(ptr = strstr(buf, "Track:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.track = atoi(tmp);
    }
    else if(!SongInfo.track)
        SongInfo.track = 0;
    if(ptr = strstr(buf, "state:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        if(strstr(tmp, "play"))
            gbState = WAT_PLS_PLAYING;
        if(strstr(tmp, "pause"))
            gbState = WAT_PLS_PAUSED;
        if(strstr(tmp, "stop"))
            gbState = WAT_PLS_STOPPED;
    }
    else if(!gbState)
        gbState = WAT_PLS_UNKNOWN;
    return 0;
}
STDMETHODIMP_(BOOL) CDataBase::GetContactSetting(HANDLE hContact, DBCONTACTGETSETTING *dbcgs)
{
	dbcgs->pValue->type = 0;

	char namebuf[512];
	namebuf[0] = 0;

	if (!(dbcgs->szModule || dbcgs->szSetting))
		return -1;

	if (dbcgs->szModule)
		strcpy_s(namebuf, dbcgs->szModule);
	strcat_s(namebuf, "/");
	if (dbcgs->szSetting)
		strcat_s(namebuf, dbcgs->szSetting);

	TDBTSettingDescriptor desc = {0,0,0,0,0,0,0,0};
	TDBTSetting set = {0,0,0,0};
	desc.cbSize = sizeof(desc);
	desc.Entity = (WPARAM)hContact;
	desc.pszSettingName = namebuf;

	set.cbSize = sizeof(set);
	set.Descriptor = &desc;

	if (DBSettingRead(reinterpret_cast<WPARAM>(&set), 0) == DBT_INVALIDPARAM)
		return -1;

	switch (set.Type) {
	case DBT_ST_ANSI:
		dbcgs->pValue->type = DBVT_ASCIIZ;
		dbcgs->pValue->pszVal = set.Value.pAnsi;
		dbcgs->pValue->cchVal = set.Value.Length - 1;
		if (isEncrypted(dbcgs->szModule, dbcgs->szSetting))
			DecodeString(dbcgs->pValue->pszVal);
		break;
	case DBT_ST_UTF8:
		if (isEncrypted(dbcgs->szModule, dbcgs->szSetting))
			DecodeString(set.Value.pUTF8);
		dbcgs->pValue->type = DBVT_WCHAR;
		dbcgs->pValue->pwszVal = mir_utf8decodeW(set.Value.pUTF8);
		if (dbcgs->pValue->pwszVal)
			dbcgs->pValue->cchVal = static_cast<uint32_t>(wcslen(dbcgs->pValue->pwszVal));
		else
			dbcgs->pValue->cchVal = 0;
		mir_free(set.Value.pUTF8);
		break;
	case DBT_ST_WCHAR:
		dbcgs->pValue->type = DBVT_WCHAR;
		dbcgs->pValue->pwszVal = set.Value.pWide;
		dbcgs->pValue->cchVal = set.Value.Length - 1;
		break;
	case DBT_ST_BLOB:
		dbcgs->pValue->type = DBVT_BLOB;
		dbcgs->pValue->pbVal = set.Value.pBlob;
		dbcgs->pValue->cpbVal = set.Value.Length;
		break;
	case DBT_ST_BOOL:
		dbcgs->pValue->type = DBVT_BYTE;
		dbcgs->pValue->bVal = (uint8_t)set.Value.Bool;
		break;
	case DBT_ST_BYTE: case DBT_ST_CHAR:
		dbcgs->pValue->type = DBVT_BYTE;
		dbcgs->pValue->bVal = set.Value.Byte;
		break;
	case DBT_ST_SHORT: case DBT_ST_WORD:
		dbcgs->pValue->type = DBVT_WORD;
		dbcgs->pValue->wVal = set.Value.Word;
		break;
	case DBT_ST_INT: case DBT_ST_DWORD:
		dbcgs->pValue->type = DBVT_DWORD;
		dbcgs->pValue->dVal = set.Value.DWord;
		break;
	case DBT_ST_INT64: case DBT_ST_QWORD:
	case DBT_ST_DOUBLE: case DBT_ST_FLOAT:
		dbcgs->pValue->type = DBVT_BLOB;
		dbcgs->pValue->cpbVal = sizeof(set.Value);
		dbcgs->pValue->pbVal = reinterpret_cast<BYTE*>(mir_alloc(sizeof(set.Value)));
		memcpy(dbcgs->pValue->pbVal, &set.Value, sizeof(set.Value));
		break;

	default:
		return -1;
	}

	return 0;
}
Beispiel #30
0
void ShowErrorUtf(char* msg) {
	wchar_t* m = (msg) ? mir_utf8decodeW(msg) : nullptr;
	ShowError(m);
	if (m) mir_free(m);
}