summaryrefslogtreecommitdiff
path: root/protocols/MRA/Mra.cpp
blob: 3d8cea3744b750e35bd35ec1963864c159edb3d9 (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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
#include "Mra.h"






#ifndef  _WIN64

/*extern "C" __declspec(naked) void _chkstk()
{
	#define _PAGESIZE_ 4096

			__asm
			{
			push    ecx

	; Calculate new TOS.

			lea     ecx, [esp] + 8 - 4      ; TOS before entering function + size for ret value
			sub     ecx, eax                ; new TOS

	; Handle allocation size that results in wraparound.
	; Wraparound will result in StackOverflow exception.

			sbb     eax, eax                ; 0 if CF==0, ~0 if CF==1
			not     eax                     ; ~0 if TOS did not wrapped around, 0 otherwise
			and     ecx, eax                ; set to 0 if wraparound

			mov     eax, esp                ; current TOS
			and     eax, not ( _PAGESIZE_ - 1) ; Round down to current page boundary

	cs10:
			cmp     ecx, eax                ; Is new TOS
			jb      short cs20              ; in probed page?
			mov     eax, ecx                ; yes.
			pop     ecx
			xchg    esp, eax                ; update esp
			mov     eax, dword ptr [eax]    ; get return address
			mov     dword ptr [esp], eax    ; and put it at new TOS
			ret

	; Find next lower page and probe
	cs20:
			sub     eax, _PAGESIZE_         ; decrease by PAGESIZE
			test    dword ptr [eax],eax     ; probe page.
			jmp     short cs10

			}
}//*/




/*extern "C" __declspec(naked) void __cdecl _chkstk()
{ 
    _asm {    jz    esp_okay    }; 
    _asm {    int    3    }; 
esp_okay: 
    _asm {    ret    }; 
} //*/






 /*//_alloca_probe_16 : 16 byte aligned alloca
 extern "C" void _alloca_probe_16()
 {
 	__asm 
 	{
 		push    ecx
 		lea     ecx, [esp] + 8          ; TOS before entering this function
 		sub     ecx, eax                ; New TOS
 		and     ecx, (16 - 1)           ; Distance from 16 bit align (align down)
 		add     eax, ecx                ; Increase allocation size
 		sbb     ecx, ecx                ; ecx = 0xFFFFFFFF if size wrapped around
 		or      eax, ecx                ; cap allocation size on wraparound
 		pop     ecx                     ; Restore ecx
 		jmp     _chkstk
 	}
 }
 
 //alloca_8: 8 byte aligned alloca
 extern "C" void _alloca_probe_8()
 {
 	__asm 
 	{
 		push    ecx
 		lea     ecx, [esp] + 8          ; TOS before entering this function
 		sub     ecx, eax                ; New TOS
 		and     ecx, (8 - 1)            ; Distance from 8 bit align (align down)
 		add     eax, ecx                ; Increase allocation Size
 		sbb     ecx, ecx                ; ecx = 0xFFFFFFFF if size wrapped around
 		or      eax, ecx                ; cap allocation size on wraparound
 		pop     ecx                     ; Restore ecx
 		jmp     _chkstk
 	}
 }//*/

/*extern "C" void __cdecl _chkstk()
{ 
	__asm
	{ 
		push	ebp 
		sub		eax, 4 
		xchg	[esp+4], ebp 
		sub		esp, eax 
		xchg	[esp], ebp 
		mov		ebp, esp 
		add		ebp, eax 
		mov		ebp, [ebp] 
	} 
}//*/



/*#define _PAGESIZE_ 1000h

#if !defined (__MARM__)
extern "C" void __declspec(naked) _chkstk(void)
{
	_asm 
	{
		push ecx 
		cmp eax,_PAGESIZE_
		lea ecx,[esp] + 8
		jb short lastpage

		probepages:
		sub ecx,_PAGESIZE_
		sub eax,_PAGESIZE_

		test dword ptr [ecx],eax

		cmp eax,_PAGESIZE_
		jae short probepages

		lastpage:
		sub ecx,eax
		mov eax,esp

		test dword ptr [ecx],eax

		mov esp,ecx

		mov ecx,dword ptr [eax]
		mov eax,dword ptr [eax + 4]

		push eax
		ret
	}
}
#endif**/



/*// будем тока выделять место в стеке под переменные
extern "C" __declspec(naked) void _chkstk()
{
	__asm
	{
		// Enter: EAX = size

		xor ebx, ebx
		xchg [esp], ebx  // запоминаем адрес возврата
		add esp, 4  // удаляем его
		sub esp, eax  //  выделяем место
		push ebx  // кладем адрес возврата на место и возвращаемся
		retn
	}
}//*/



//extern "C" void __declspec(naked) __cdecl _chkesp()
/*extern "C" __declspec(naked)  void __cdecl _chkstk()
{
#ifndef _PAGESIZE_
    #define _PAGESIZE_ 1000h
#endif //_PAGESIZE_

    __asm
    {
        push    ecx                     // save ecx
        cmp     eax, _PAGESIZE_         // more than one page requested?
        lea     ecx, [esp] + 8          // compute new stack pointer in ecx
                                        // correct for return address and
                                        // saved ecx
        jb      short lastpage          // no


probepages:

        sub     ecx, _PAGESIZE_         // yes, move down a page
        sub     eax, _PAGESIZE_         // adjust request and...

        test    dword ptr [ecx], eax    // ...probe it

        cmp     eax, _PAGESIZE_         // more than one page requested?
        jae     short probepages        // no


lastpage:

        sub     ecx, eax                // move stack down by eax
        mov     eax, esp                // save current tos and do a...

        test    dword ptr [ecx], eax    // ...probe in case a page was crossed

        mov     esp, ecx                // set the new stack pointer

        mov     ecx, dword ptr [eax]    // recover ecx
        mov     eax, dword ptr [eax + 4]// recover return address

        push    eax                     // prepare return address
                                        // ...probe in case a page was crossed
        ret
    }
}//*/






extern "C" __declspec(naked) void __cdecl _chkstk()
{
	#define _PAGESIZE_ 4096

			__asm
			{
			push    ecx

	; Calculate new TOS.

			lea     ecx, [esp] + 8 - 4      ; TOS before entering function + size for ret value
			sub     ecx, eax                ; new TOS

	; Handle allocation size that results in wraparound.
	; Wraparound will result in StackOverflow exception.

			sbb     eax, eax                ; 0 if CF==0, ~0 if CF==1
			not     eax                     ; ~0 if TOS did not wrapped around, 0 otherwise
			and     ecx, eax                ; set to 0 if wraparound

			mov     eax, esp                ; current TOS
			and     eax, not ( _PAGESIZE_ - 1) ; Round down to current page boundary

	cs10:
			cmp     ecx, eax                ; Is new TOS
			jb      short cs20              ; in probed page?
			mov     eax, ecx                ; yes.
			pop     ecx
			xchg    esp, eax                ; update esp
			mov     eax, dword ptr [eax]    ; get return address
			mov     dword ptr [esp], eax    ; and put it at new TOS
			ret

	; Find next lower page and probe
	cs20:
			sub     eax, _PAGESIZE_         ; decrease by PAGESIZE
			test    dword ptr [eax],eax     ; probe page.
			jmp     short cs10

			}
}//


extern "C" void __declspec(naked) __cdecl _aulldiv()
{// http://tamiaode.3322.org/svn/ntldr/trunk/source/ntldr/ia32/x86stub.cpp
	__asm
	{
		push	ebx
		push	esi

		mov	eax,[esp + 24]
		or	eax,eax
		jnz	short L1

		mov	ecx,[esp + 20]
		mov	eax,[esp + 16]
		xor	edx,edx
		div	ecx
		mov	ebx,eax
		mov	eax,[esp + 12]
		div	ecx
		mov	edx,ebx
		jmp	short L2

	L1:
		mov	ecx,eax
		mov	ebx,[esp + 20]
		mov	edx,[esp + 14]
		mov	eax,[esp + 12]

	L3:
		shr	ecx,1
		rcr	ebx,1
		shr	edx,1
		rcr	eax,1
		or	ecx,ecx
		jnz	short L3
		div	ebx
		mov	esi,eax

		mul	dword ptr [esp + 24]
		mov	ecx,eax
		mov	eax,[esp + 20]
		mul	esi
		add	edx,ecx
		jc	short L4

		cmp	edx,[esp + 16]
		ja	short L4
		jb	short L5
		cmp	eax,[esp + 12]
		jbe	short L5
	L4:
		dec	esi
	L5:
		xor	edx,edx
		mov	eax,esi

	L2:

		pop	esi
		pop	ebx

		ret	16
	}
}//

//
// LONG64 mul
//
extern "C" void __declspec(naked) __cdecl _allmul()
{
	__asm
	{
		mov	eax,[esp + 4][4]
		mov	ecx,[esp + 12][4]
		or	ecx,eax
		mov	ecx,[esp + 12]
		jnz	short hard

		mov	eax,[esp + 4]
		mul	ecx
		ret	16

hard:
		push	ebx
		mul	ecx
		mov	ebx,eax
		mov	eax,[esp + 8]
		mul	dword ptr [esp + 16][4]
		add	ebx,eax
		mov	eax,[esp + 8]
		mul	ecx
		add	edx,ebx
		pop	ebx

		ret	16
	}
}//*/


//
// 64bits shift left
//
extern "C" __declspec(naked) void __cdecl _allshl()
{
	__asm
	{
		cmp	cl, 64
		jae	short RETZERO

		cmp	cl, 32
		jae	short MORE32
		shld	edx,eax,cl
		shl	eax,cl
		ret

	MORE32:
		mov	edx,eax
		xor	eax,eax
		and	cl,31
		shl	edx,cl
		ret

	RETZERO:
		xor	eax,eax
		xor	edx,edx
		ret
	}
}
#endif




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.",
	"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:
		memset(&masMraSettings, 0, 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;
    }

	/*BYTE szBuff[1024]={0};
	LPSTR lpszString="\r\n\t  GET \t  \r\n  \r\n  \r\n    http://mail.ru/  \tHTTP/1.1  \t  ";
	LPSTR lpszFindString="123456  ";
	LPSTR lpszWhatFindString="123456";
	SIZE_T dwStringLen=lstrlenA(lpszString),dwBuffSize,dwBuffLen;

//#define LWSHT "\r\n\t"
//#define LWSSP "\r\n "


	//lpszString=(LPSTR)MemoryFind(0,lpszFindString,(lstrlenA(lpszFindString)),lpszWhatFindString,lstrlenA(lpszWhatFindString));
	//lpszString=(LPSTR)MemoryFindByte(0,lpszFindString,(lstrlenA(lpszFindString)-1),'6');


	//WSP2SP(lpszString,dwStringLen,(LPSTR)szBuff,&dwBuffSize);
	//HT2SP(lpszString,dwStringLen,(LPSTR)szBuff,&dwBuffSize);
	CleanUnneededSP(lpszString,dwStringLen,(LPSTR)szBuff,&dwBuffSize);

	dwBuffLen=lstrlenA((LPSTR)szBuff);
	if (dwBuffSize!=dwBuffLen) DebugBreak();
	//*/


	/*LPCSTR lpszHeader,lpszHeaderLow,lpszValueName;
	LPSTR lpszValueNameRet;
	SIZE_T dwHeaderSize,dwValueNameSize,dwValueNameRetSize;
	CHAR szHeader[4096]={0},szHeaderLow[4096]={0};

	//lstrcpynA(szHeader,"Server: squid/3.1.0.15\r\nMime-Version: 1.0\r\nContent-Length: 0\r\nX-Cache: MISS from Firewall\r\nProxy-Connection: keep-alive",SIZEOF(szHeader));
	lstrcpynA(szHeader,"http/1.0 200 ok\r\nserver: apache-coyote/1.1\r\ndate: fri, 30 apr 2010 08:36:10 gmt\r\nlast-modified: wed, 28 apr 2010 03:22:49 gmt\r\ncache-control: max-age=360000\r\ncontent-type: \r\ncontent-length: 55946",SIZEOF(szHeader));
	lpszHeader=(LPCSTR)szHeader;
	lpszHeaderLow=(LPCSTR)szHeaderLow;
	dwHeaderSize=lstrlenA(lpszHeader);
	
	//lpszValueName="proxy-connection";
	//lpszValueName="content-length";
	lpszValueName="content-type";
	dwValueNameSize=lstrlenA(lpszValueName);


	BuffToLowerCase(lpszHeaderLow,lpszHeader,dwHeaderSize);

	HeaderValueGet(lpszHeader,lpszHeaderLow,dwHeaderSize,lpszValueName,dwValueNameSize,&lpszValueNameRet,&dwValueNameRetSize);
	//HeaderValueRemove(lpszHeader,lpszHeaderLow,dwHeaderSize,&dwBuffLen,lpszValueName,dwValueNameSize);
	szHeader[dwBuffLen]=0;
	szHeaderLow[dwBuffLen]=0;//*/


return(TRUE);
}


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

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


extern "C" __declspec(dllexport) 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");
				}
			}
		}
	}


	/*HMODULE hDLLCrypt32=LoadLibraryW(L"Crypt32.dll");
	if (hDLLCrypt32)
	{
		HANDLE hFunc=(HANDLE)GetProcAddress(hDLLCrypt32,"CryptProtectMemory");
		FreeLibrary(hDLLCrypt32);
	}

	HMODULE hDLLAdvapi32=LoadLibraryW(L"Advapi32.dll");
	if (hDLLAdvapi32)
	{
		HANDLE hFunc=(HANDLE)GetProcAddress(hDLLAdvapi32,"SystemFunction040");
		FreeLibrary(hDLLAdvapi32);
	}

	for(DWORD i=0;i<MRA_XSTATUS_COUNT;i++)
	{
		if (lstrlenA(lpcszXStatusNameDef[i])>STATUS_TITLE_MAX) 
		{
			DebugPrintCRLF(lpcszXStatusNameDef[i]);
		}
		if (lstrlenA(TranslateW(lpcszXStatusNameDef[i]))>STATUS_TITLE_MAX) 
		{
			DebugPrintCRLF(TranslateW(lpcszXStatusNameDef[i]));
		}
	}*/



	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" __declspec(dllexport) 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);
	/*{
		HANDLE hContact;
		for(hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);hContact!=NULL;hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0))
		{// функция сама проверяет принадлежность контакта к MRA
			if (IsContactMra(hContact)) break;
		}
		DB_Mra_DeleteValue(hContact,"AvatarLastCheckTime");
		MraAvatarsQueueGetAvatar(masMraSettings.hAvatarsQueueHandle,GAIF_FORCE,hContact,NULL,NULL,NULL);
	}//*/
	
	VersionConversions();

	MraAntiSpamLoadBadWordsW();

	LoadModules();

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


	//hHookOnUserInfoInit=HookEvent(ME_USERINFO_INITIALISE,MsnOnDetailsInit);


	/*//BYTE btRND[MAX_PATH]={0};
	char szPass[MAX_PATH]={0};
	//LPSTR lpszPass="1234567890";
	SIZE_T dwBuffLen;

	//dwBuffLen=lstrlenA(lpszPass);
	//SetPassDB(lpszPass,dwBuffLen);
	GetPassDB(szPass,sizeof(szPass),&dwBuffLen);

	MessageBoxA(NULL,szPass,"Password",(MB_OK));

	//*/


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

	//MraSetStatus(ID_STATUS_OFFLINE,0);

	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");
		}
	}

//*/
}