summaryrefslogtreecommitdiff
path: root/protocols/MRA/Mra.cpp
blob: e5e5d22e0f57caee6f8dc261a14650557aeb3984 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#include "Mra.h"

PLUGINLINK *pluginLink;
MM_INTERFACE mmi;
MRA_SETTINGS masMraSettings;
int hLangpack;

PLUGININFOEX pluginInfoEx={
	sizeof(PLUGININFOEX),
	PROTOCOL_DISPLAY_NAME_ORIGA,
	PLUGIN_VERSION_DWORD,
	"Provides support for Mail.ru agent Instant Messenger protocol ("__DATE__" "__TIME__")",
	"Rozhuk Ivan",
	"Rozhuk_I@mail.ru",
	"© 2006-2011 Rozhuk Ivan",
	"http://addons.miranda-im.org/details.php?action=viewfile&id=2544",
	UNICODE_AWARE,		//not transient
	0,		//doesn't replace anything built-in
	// {E7C48BAB-8ACE-4CB3-8446-D4B73481F497}
	{ 0xe7c48bab, 0x8ace, 0x4cb3, { 0x84, 0x46, 0xd4, 0xb7, 0x34, 0x81, 0xf4, 0x97 } }
};

static const MUUID interfaces[]={MIID_PROTOCOL,MIID_LAST};


int		OnModulesLoaded		(WPARAM wParam,LPARAM lParam);
int		OnPreShutdown		(WPARAM wParam,LPARAM lParam);
void	VersionConversions	();


BOOL WINAPI DllMain(HINSTANCE hInstance,DWORD dwReason,LPVOID Reserved)
{
	switch(dwReason){
	case DLL_PROCESS_ATTACH:
		bzero(&masMraSettings,sizeof(masMraSettings));
		masMraSettings.hInstance=hInstance;
		masMraSettings.hHeap=HeapCreate(0,0,0);//GetProcessHeap();
		masMraSettings.bLoggedIn=FALSE;
		masMraSettings.dwStatusMode=ID_STATUS_OFFLINE;
		masMraSettings.dwDesiredStatusMode=ID_STATUS_OFFLINE;
		DisableThreadLibraryCalls((HMODULE)hInstance);
		break;
	case DLL_PROCESS_DETACH:
		HeapDestroy(masMraSettings.hHeap);
		masMraSettings.hHeap=NULL;
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
		break;
	}

	return(TRUE);
}


extern "C" MRA_API PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
{
	if (mirandaVersion<MIN_MIR_VER_VERSION_DWORD) 
	{
		MessageBox(NULL, TranslateT("Please, update your Miranda IM, MRA will not load with this version."), NULL, (MB_OK|MB_ICONERROR));
		return(NULL);
	}
	return(&pluginInfoEx);
}

extern "C" MRA_API const MUUID* MirandaPluginInterfaces()
{
	return(interfaces);
}


extern "C" MRA_API int Load(PLUGINLINK *link)
{
	SIZE_T dwBuffLen;
	WCHAR szBuff[MAX_FILEPATH];
	LPSTR lpszFullFileName=(LPSTR)szBuff;
	LPWSTR lpwszFileName;
	PROTOCOLDESCRIPTOR pd={0};

	pluginLink=link;
	mir_getLP(&pluginInfoEx);
	mir_getMMI(&mmi);


	// Get module name from DLL file name
	if (GetModuleFileName(masMraSettings.hInstance,szBuff,MAX_FILEPATH))
	{
		WCHAR sztmBuff[MAX_FILEPATH];
		if ((dwBuffLen=GetFullPathName(szBuff,MAX_FILEPATH,sztmBuff,&lpwszFileName)))
		{
			dwBuffLen=(lstrlenW(lpwszFileName)-4);
			//lpwszFileName=L"MRA.dll";
			//dwBuffLen=3;
			masMraSettings.dwModuleNameLen=(dwBuffLen<MAXMODULELABELLENGTH)? dwBuffLen:(MAXMODULELABELLENGTH-1);
			memmove(masMraSettings.wszModuleName,lpwszFileName,(masMraSettings.dwModuleNameLen*sizeof(WCHAR)));
			CharUpperBuff(masMraSettings.wszModuleName,masMraSettings.dwModuleNameLen);
			masMraSettings.wszModuleName[masMraSettings.dwModuleNameLen]=0;
			WideCharToMultiByte(MRA_CODE_PAGE,0,masMraSettings.wszModuleName,(masMraSettings.dwModuleNameLen+1),masMraSettings.szModuleName,MAXMODULELABELLENGTH,NULL,NULL);

			if (DB_Mra_GetByte(NULL,"UseDisplayModuleName",TRUE))
			{
				masMraSettings.dwDisplayModuleNameLen=mir_sntprintf(masMraSettings.wszDisplayModuleName,SIZEOF(masMraSettings.wszDisplayModuleName),L"%s: %S",PROTOCOL_NAMEW,PROTOCOL_DISPLAY_NAME_ORIGA);
			}else{
				memmove(masMraSettings.wszDisplayModuleName,masMraSettings.wszModuleName,(masMraSettings.dwModuleNameLen*sizeof(WCHAR)));
				masMraSettings.dwDisplayModuleNameLen=masMraSettings.dwModuleNameLen;
				masMraSettings.szDisplayModuleName[masMraSettings.dwDisplayModuleNameLen]=0;
			}
			WideCharToMultiByte(MRA_CODE_PAGE,0,masMraSettings.wszDisplayModuleName,(masMraSettings.dwDisplayModuleNameLen+1),masMraSettings.szDisplayModuleName,MAX_PATH,NULL,NULL);
		}
	}

	// load libs
	if (GetModuleFileName(NULL,szBuff,MAX_FILEPATH))
	{// 
		DWORD dwErrorCode;

		masMraSettings.dwMirWorkDirPathLen=GetFullPathName(szBuff,MAX_FILEPATH,masMraSettings.szMirWorkDirPath,&lpwszFileName);
		if (masMraSettings.dwMirWorkDirPathLen)
		{
			masMraSettings.dwMirWorkDirPathLen-=lstrlenW(lpwszFileName);
			masMraSettings.szMirWorkDirPath[masMraSettings.dwMirWorkDirPathLen]=0;

			// load xstatus icons lib
			dwErrorCode=FindFile(masMraSettings.szMirWorkDirPath,masMraSettings.dwMirWorkDirPathLen,L"xstatus_MRA.dll",-1,szBuff,SIZEOF(szBuff),(DWORD*)&dwBuffLen);
			if (dwErrorCode==NO_ERROR)
			{
				masMraSettings.hDLLXStatusIcons=LoadLibraryEx(szBuff,NULL,/*LOAD_LIBRARY_AS_DATAFILE*/0);
				if (masMraSettings.hDLLXStatusIcons)
				{
					if ((dwBuffLen=LoadStringW(masMraSettings.hDLLXStatusIcons,IDS_IDENTIFY,szBuff,MAX_FILEPATH))==0 || CompareStringW(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),NORM_IGNORECASE,L"# Custom Status Icons #",23,szBuff,dwBuffLen)!=CSTR_EQUAL)
					{
						FreeLibrary(masMraSettings.hDLLXStatusIcons);
						masMraSettings.hDLLXStatusIcons=NULL;
					}
				}
			}

			// load zlib
			dwErrorCode=FindFile(masMraSettings.szMirWorkDirPath,masMraSettings.dwMirWorkDirPathLen,L"zlib.dll",-1,szBuff,SIZEOF(szBuff),(DWORD*)&dwBuffLen);
			if (dwErrorCode!=NO_ERROR) dwErrorCode=FindFile(masMraSettings.szMirWorkDirPath,masMraSettings.dwMirWorkDirPathLen,L"zlib1.dll",-1,szBuff,SIZEOF(szBuff),(DWORD*)&dwBuffLen);
			if (dwErrorCode==NO_ERROR)
			{// load xstatus icons lib
				masMraSettings.hDLLZLib=LoadLibraryEx(szBuff,NULL,0);
				if (masMraSettings.hDLLZLib)
				{
					masMraSettings.lpfnCompress2=(HANDLE)GetProcAddress(masMraSettings.hDLLZLib,"compress2");
					masMraSettings.lpfnUncompress=(HANDLE)GetProcAddress(masMraSettings.hDLLZLib,"uncompress");
				}
			}
		}
	}

	InitializeCriticalSectionAndSpinCount(&masMraSettings.csCriticalSectionSend,0);
	MraSendQueueInitialize(0,&masMraSettings.hSendQueueHandle);
	MraFilesQueueInitialize(0,&masMraSettings.hFilesQueueHandle);
	MraMPopSessionQueueInitialize(&masMraSettings.hMPopSessionQueue);

	FifoMTInitialize(&masMraSettings.ffmtAPCQueue,0);
	masMraSettings.hWaitEventThreadAPCHandle=CreateEvent(NULL,FALSE,FALSE,NULL);
	InterlockedExchange((volatile LONG*)&masMraSettings.dwAPCThreadRunning,TRUE);
	masMraSettings.hThreadAPC=(HANDLE)mir_forkthread((pThreadFunc)MraUserAPCThreadProc,NULL);
	if (masMraSettings.hThreadAPC==NULL)
	{
		MraAPCQueueDestroy(&masMraSettings.ffmtAPCQueue);
		CloseHandle(masMraSettings.hWaitEventThreadAPCHandle);
		masMraSettings.hWaitEventThreadAPCHandle=NULL;
		DuplicateHandle(GetCurrentProcess(),GetCurrentThread(),GetCurrentProcess(),&masMraSettings.hThreadAPC,THREAD_SET_CONTEXT,FALSE,0);
		DebugPrintCRLFW(L"Fail on create event APC thread, using miranda main thread");
		MessageBoxW(NULL,L"Fail on create event APC thread, using miranda main thread",PROTOCOL_DISPLAY_NAMEW,(MB_OK|MB_ICONINFORMATION));
	}//*/

	masMraSettings.hHookModulesLoaded=HookEvent(ME_SYSTEM_MODULESLOADED,OnModulesLoaded);
	masMraSettings.hHookPreShutdown=HookEvent(ME_SYSTEM_PRESHUTDOWN,OnPreShutdown);

	LoadServices();

	//pd.cbSize=sizeof(pd);
	pd.cbSize=PROTOCOLDESCRIPTOR_V3_SIZE;
	pd.szName=PROTOCOL_NAMEA;
	pd.type=PROTOTYPE_PROTOCOL;
	CallService(MS_PROTO_REGISTERMODULE,0,(LPARAM)&pd);

	DebugPrintCRLFW(L"Load - DONE");
return(0);
}


extern "C" MRA_API int Unload(void)
{
	UnloadServices();
	//if (hHookOnUserInfoInit)				UnhookEvent(hHookOnUserInfoInit);
	if (masMraSettings.hHookPreShutdown)	{UnhookEvent(masMraSettings.hHookPreShutdown);		masMraSettings.hHookPreShutdown=NULL;}
	if (masMraSettings.hHookModulesLoaded)	{UnhookEvent(masMraSettings.hHookModulesLoaded);	masMraSettings.hHookModulesLoaded=NULL;}

	Netlib_CloseHandle(masMraSettings.hNetlibUser);
	masMraSettings.hNetlibUser=NULL;

	MraMPopSessionQueueDestroy(masMraSettings.hMPopSessionQueue);
	masMraSettings.hMPopSessionQueue=NULL;

	MraFilesQueueDestroy(masMraSettings.hFilesQueueHandle);
	masMraSettings.hFilesQueueHandle=NULL;

	MraSendQueueDestroy(masMraSettings.hSendQueueHandle);
	masMraSettings.hSendQueueHandle=NULL;

	DeleteCriticalSection(&masMraSettings.csCriticalSectionSend);
	SecureZeroMemory(&masMraSettings.csCriticalSectionSend,sizeof(CRITICAL_SECTION));

	if (masMraSettings.hDLLXStatusIcons)
	{
		FreeLibrary(masMraSettings.hDLLXStatusIcons);
		masMraSettings.hDLLXStatusIcons=NULL;
	}

	if (masMraSettings.hDLLZLib)
	{
		FreeLibrary(masMraSettings.hDLLZLib);
		masMraSettings.hDLLZLib=NULL;
		masMraSettings.lpfnCompress2=NULL;
		masMraSettings.lpfnUncompress=NULL;
	}

	SecureZeroMemory(pluginLink,sizeof(pluginLink));
	SecureZeroMemory(&mmi,sizeof(pluginLink));

	DebugPrintCRLFW(L"Unload - DONE");
return(0);
}


static int OnModulesLoaded(WPARAM wParam,LPARAM lParam)
{
	WCHAR szBuffer[MAX_PATH];
	NETLIBUSER nlu={0};

	mir_sntprintf(szBuffer,SIZEOF(szBuffer),L"%s %s",PROTOCOL_NAMEW,TranslateW(L"plugin connections"));
	nlu.cbSize=sizeof(nlu);
	nlu.flags=(NUF_INCOMING|NUF_OUTGOING|NUF_HTTPCONNS|NUF_UNICODE);
	nlu.szSettingsModule=PROTOCOL_NAMEA;
	nlu.ptszDescriptiveName=szBuffer;
	masMraSettings.hNetlibUser=(HANDLE)CallService(MS_NETLIB_REGISTERUSER,0,(LPARAM)&nlu);

#ifdef _DEBUG
	// всех в offline // тк unsaved values сохраняются их нужно инициализировать
	for(HANDLE hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);hContact!=NULL;hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0))
	{// функция сама проверяет принадлежность контакта к MRA
		SetContactBasicInfoW(hContact,SCBIFSI_LOCK_CHANGES_EVENTS,(SCBIF_ID|SCBIF_GROUP_ID|SCBIF_SERVER_FLAG|SCBIF_STATUS),-1,-1,0,0,ID_STATUS_OFFLINE,NULL,0,NULL,0,NULL,0);
	}
#else
	// unsaved values
	DB_Mra_CreateResidentSetting("Status");// NOTE: XStatus cannot be temporary
	DB_Mra_CreateResidentSetting("LogonTS");
	DB_Mra_CreateResidentSetting("ContactID");
	DB_Mra_CreateResidentSetting("GroupID");
	DB_Mra_CreateResidentSetting("ContactFlags");
	DB_Mra_CreateResidentSetting("ContactSeverFlags");
	DB_Mra_CreateResidentSetting("HooksLocked");
	DB_Mra_CreateResidentSetting(DBSETTING_CAPABILITIES);
	DB_Mra_CreateResidentSetting(DBSETTING_XSTATUSNAME);
	DB_Mra_CreateResidentSetting(DBSETTING_XSTATUSMSG);
	DB_Mra_CreateResidentSetting(DBSETTING_BLOGSTATUSTIME);
	DB_Mra_CreateResidentSetting(DBSETTING_BLOGSTATUSID);
	DB_Mra_CreateResidentSetting(DBSETTING_BLOGSTATUS);
	DB_Mra_CreateResidentSetting(DBSETTING_BLOGSTATUSMUSIC);
	
	// всех в offline // тк unsaved values сохраняются их нужно инициализировать
	for(HANDLE hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);hContact!=NULL;hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0))
	{// функция сама проверяет принадлежность контакта к MRA
		SetContactBasicInfoW(hContact,SCBIFSI_LOCK_CHANGES_EVENTS,(SCBIF_ID|SCBIF_GROUP_ID|SCBIF_SERVER_FLAG|SCBIF_STATUS),-1,-1,0,0,ID_STATUS_OFFLINE,NULL,0,NULL,0,NULL,0);
	}
#endif

	MraAvatarsQueueInitialize(&masMraSettings.hAvatarsQueueHandle);
	
	VersionConversions();

	MraAntiSpamLoadBadWordsW();

	LoadModules();

	CallService(MS_UPDATE_REGISTERFL,(WPARAM)MRA_PLUGIN_UPDATER_ID,(LPARAM)&pluginInfoEx);

	InterlockedExchange((volatile LONG*)&masMraSettings.dwGlobalPluginRunning,TRUE);

	DebugPrintCRLFW(L"OnModulesLoaded - DONE");
return(0);
}


int OnPreShutdown(WPARAM wParam,LPARAM lParam)
{
	InterlockedExchange((volatile LONG*)&masMraSettings.dwGlobalPluginRunning,FALSE);

	MraSetStatus(ID_STATUS_OFFLINE,0);
	
	MraAvatarsQueueDestroy(masMraSettings.hAvatarsQueueHandle);
	masMraSettings.hAvatarsQueueHandle=NULL;

	if (masMraSettings.hThreadWorker)
	{
		if (IsThreadAlive(masMraSettings.hThreadWorker)) WaitForSingleObjectEx(masMraSettings.hThreadWorker,(WAIT_FOR_THREAD_TIMEOUT*1000),FALSE);
		masMraSettings.hThreadWorker=NULL;
	}

	InterlockedExchange((volatile LONG*)&masMraSettings.dwAPCThreadRunning,FALSE);
	if (masMraSettings.hWaitEventThreadAPCHandle)
	if (IsThreadAlive(masMraSettings.hThreadAPC))
	{
		SetEvent(masMraSettings.hWaitEventThreadAPCHandle);
	}else{
		CloseHandle(masMraSettings.hWaitEventThreadAPCHandle);
		//WaitForSingleObjectEx(masMraSettings.hThreadAPC,(WAIT_FOR_THREAD_TIMEOUT*1000),FALSE); // no wait - dead lock.
		masMraSettings.hWaitEventThreadAPCHandle=NULL;
		masMraSettings.hThreadAPC=NULL;
	}

	UnloadModules();

	MraAntiSpamFreeBadWords();

	DebugPrintCRLFW(L"OnPreShutdown - DONE");
return(0);
}



void VersionConversions()
{
	/*switch(DB_Mra_GetDword(NULL,"LastPluginVersion",PLUGIN_MAKE_VERSION(0,0,0,0))){
	default:
	case PLUGIN_MAKE_VERSION(1,14,0,0):
	case PLUGIN_MAKE_VERSION(1,14,0,1):
	case PLUGIN_MAKE_VERSION(1,14,0,2):
		DB_Mra_DeleteValue(NULL,"MirVer");
		DB_Mra_DeleteValue(NULL,"MessagesCountSend");
		DB_Mra_DeleteValue(NULL,"MRAClient");
		DB_Mra_DeleteValue(NULL,"MRAClientVer");
		DB_Mra_DeleteValue(NULL,"MRAClientCapabilities");
		DB_Mra_DeleteValue(NULL,"Status");
		DB_Mra_DeleteValue(NULL,"ContactID");
		DB_Mra_DeleteValue(NULL,"GroupID");
		DB_Mra_DeleteValue(NULL,"ContactSeverFlags");
		DB_Mra_DeleteValue(NULL,"HooksLocked");
		for(HANDLE hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);hContact!=NULL;hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0))
		{
			DB_Mra_DeleteValue(hContact,"MessagesCountSend");
			DB_Mra_DeleteValue(hContact,"MRAClient");
			DB_Mra_DeleteValue(hContact,"MRAClientVer");
			DB_Mra_DeleteValue(hContact,"MRAClientCapabilities");
			DB_Mra_DeleteValue(hContact,"Status");
			DB_Mra_DeleteValue(hContact,"ContactID");
			DB_Mra_DeleteValue(hContact,"GroupID");
			DB_Mra_DeleteValue(hContact,"ContactSeverFlags");
			DB_Mra_DeleteValue(hContact,"HooksLocked");
		}
	case PLUGIN_MAKE_VERSION(1,14,0,3):
	case PLUGIN_MAKE_VERSION(1,14,0,4):
	case PLUGIN_MAKE_VERSION(1,14,0,5):
	case PLUGIN_MAKE_VERSION(1,14,0,6):
	case PLUGIN_MAKE_VERSION(1,14,0,7):
	//case PLUGIN_MAKE_VERSION(1,14,1,0):
		DB_Mra_SetByte(NULL,DBSETTING_XSTATUSID,(BYTE)DB_Mra_GetDword(NULL,DBSETTING_XSTATUSID,MRA_MIR_XSTATUS_NONE));
		for(HANDLE hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);hContact!=NULL;hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0))
		{
			if (IsContactMra(hContact)) DB_Mra_SetByte(hContact,DBSETTING_XSTATUSID,(BYTE)DB_Mra_GetDword(hContact,DBSETTING_XSTATUSID,MRA_MIR_XSTATUS_NONE));
		}
	case PLUGIN_MAKE_VERSION(1,16,0,2):
		DB_Mra_DeleteValue(NULL,"CvtSmilesToTags");
	case PLUGIN_MAKE_VERSION(1,16,0,3):
		for(HANDLE hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);hContact!=NULL;hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0))
		{
			if (IsContactMra(hContact)==FALSE) DB_Mra_DeleteValue(hContact,DBSETTING_XSTATUSID);
		}
	case PLUGIN_MAKE_VERSION(0,0,0,0):// no previos version
		MraAntiSpamResetBadWordsList();
	case PLUGIN_VERSION_DWORD:// current version
		break;
	}*/

	DB_Mra_SetDword(NULL,"LastPluginVersion",PLUGIN_VERSION_DWORD);



	{// pass conv
		char szPass[MAX_PATH];
		SIZE_T dwPassSize;

		if(DB_Mra_GetStaticStringA(NULL,"Password",(LPSTR)szPass,SIZEOF(szPass),&dwPassSize))
		{//bit of a security hole here, since it's easy to extract a password from an edit box
			CallService(MS_DB_CRYPT_DECODESTRING,(dwPassSize+1),(LPARAM)szPass);

			SetPassDB(szPass,dwPassSize);

			SecureZeroMemory(szPass,sizeof(szPass));
			DB_Mra_DeleteValue(NULL,"Password");
		}
	}
}