summaryrefslogtreecommitdiff
path: root/protocols/WinPopup/src/winpopup_proto.cpp
blob: 53e8245ec6bd702f7546964dd2ebcd1382cca14f (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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
/*

WinPopup Protocol plugin for Miranda IM.

Copyright (C) 2004-2011 Nikolay Raspopov

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include "stdafx.h"

volatile WPARAM		pluginRequestedStatus	= ID_STATUS_OFFLINE;
volatile WPARAM		pluginCurrentStatus		= ID_STATUS_OFFLINE;
CIntStrMap			pluginStatusMessage;
CString				pluginMachineName;
CString				pluginUserName;
CString				pluginDomainName;
HMODULE				pluginModule			= NULL;
volatile bool		pluginBusy				= false;
volatile bool		pluginInstalled			= false;
volatile bool		pluginInitialized		= false;
HANDLE				pluginNetLibUser		= NULL;
HANDLE				pluginInternalState		= NULL;
bool				pluginChatEnabled		= false;
OSVERSIONINFO		pluginOS				= { sizeof( OSVERSIONINFO ) };

CComAutoCriticalSection	pluginGuard;		// Çàùèòà äîñòóïà ê êàðòàì:
CThreadContactMap	pluginAwayThreadMap;	// Êàðòà àñèíõðîííûõ çàïðîñîâ ýâåé-ñîîáùåíèé
CThreadContactMap	pluginAvatarThreadMap;	// Êàðòà àñèíõðîííûõ çàïðîñîâ àâàòàðîâ

CString GetNick(HANDLE hContact)
{
	CString sNick;
	DBVARIANT dbv = {};
	if ( ! DBGetContactSettingTString( hContact, modname, "Nick", &dbv ) )
	{
		sNick = dbv.ptszVal;
		DBFreeVariant( &dbv );
	}
	return sNick;
}

void SetNick(HANDLE hContact, LPCTSTR szNick)
{
	DBWriteContactSettingTString( hContact, modname, "Nick", szNick );
}

CComAutoCriticalSection _LOG_SECTION;

int LOG(const char *fmt,...)
{
	CComCritSecLock< CComAutoCriticalSection > _Lock( _LOG_SECTION );

	int ret = 0;
	const int size = 512;
	if ( char* szText = (char*)mir_alloc( size ) )
	{
		*szText = 0;
		va_list va;
		va_start( va, fmt );
		mir_vsnprintf( szText, size, fmt, va );
		va_end( va );
		ret = CallService( MS_NETLIB_LOG, (WPARAM)pluginNetLibUser, (LPARAM)szText );
		mir_free( szText );
	}
	return ret;
}

void GetAvatarCache(LPTSTR szPath)
{
	// Ïîëó÷èòü ïóòü íîâûì ñïîñîáîì
	if ( ServiceExists( MS_UTILS_REPLACEVARS ) )
	{
		LPTSTR szAvatarCache = Utils_ReplaceVarsT(
			_T("%miranda_avatarcache%\\") modname_t _T("\\") );
		if ( szAvatarCache && szAvatarCache != (LPTSTR)0x80000000 )
		{
			lstrcpyn( szPath, szAvatarCache, MAX_PATH );

			// Ñîçäàíèå ïóòè äî áóäóùåãî ôàéëà àâàòàðà
			CallService( MS_UTILS_CREATEDIRTREET, 0, (LPARAM)szPath );
			return;
		}
	}

	// Ïîëó÷èòü ïóòü ñòàðûì ñïîñîáîì
	char szProfilePath[ MAX_PATH ], szProfileName[ MAX_PATH ];
	CallService( MS_DB_GETPROFILEPATH, MAX_PATH, (LPARAM)szProfilePath );
	CallService( MS_DB_GETPROFILENAME, MAX_PATH, (LPARAM)szProfileName );
	char *pos = strrchr( szProfileName, '.' );
	if ( lstrcmpA( pos, ".dat" ) == 0 )
		*pos = 0;
	lstrcpy( szPath, CA2T( szProfilePath ) );
	lstrcat( szPath, _T("\\") );
	lstrcat( szPath, CA2T( szProfileName ) );
	lstrcat( szPath, _T("\\AvatarCache\\") modname_t _T("\\") );

	// Ñîçäàíèå ïóòè äî áóäóùåãî ôàéëà àâàòàðà
	CallService( MS_UTILS_CREATEDIRTREET, 0, (LPARAM)szPath );
	return;
}

static LONG cookie = (LONG)GetTickCount();

HANDLE GenerateCookie()
{
	return (HANDLE)InterlockedIncrement( &cookie );
}

DWORD time()
{
	LARGE_INTEGER lft = {};
	GetSystemTimeAsFileTime ((FILETIME*) &lft);
	return (DWORD) ((lft.QuadPart - 116444736000000000) / 10000000);
}

bool IsMyContact(HANDLE hContact)
{
	if ( ! hContact )
		// Ýòî âîîáùå íå êîíòàêò
		return false;

	char* proto = (char*)CallService( MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0 );
	if ( ! proto )
		// Ýòî íè÷åéíûé êîíòàêò
		return false;

	if ( lstrcmpA( proto, modname ) )
		// Ýòî íå íàø êîíòàêò
		return false;

	// Ýòî íàø êîíòàêò
	return true;
}

void SetPluginStatus(WPARAM status)
{
	WPARAM old = pluginCurrentStatus;
	pluginCurrentStatus = status;
	if (pluginInstalled)
	{
		ProtoBroadcastAck (modname, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS,
			(HANDLE) old, (LPARAM) pluginCurrentStatus);

		if ( old != pluginCurrentStatus &&
			pluginCurrentStatus >= ID_STATUS_OFFLINE && 
			pluginCurrentStatus <= ID_STATUS_OUTTOLUNCH )
		{
			pluginNetBIOS.BroadcastStatus();
		}
	}
}

bool InternalStartup()
{
	_ASSERT( pluginInstalled == true );

	LOG ("Startup begin");

	ResetEvent( pluginInternalState );

	bool err = false;

	BYTE method = (BYTE) DBGetContactSettingByte (NULL, modname, "SendMethod", 0);
	if ( method == 2 )
	{
		// Èíèöèàëèçàöèÿ "Ñëóæáû Ñîîáùåíèé" ñ çàïóñêîì
		if (pluginMessenger.Create (TRUE))
			err = true;
		LOG ("Startup : Messenger");

		// Èíèöèàëèçàöèÿ NetBIOS
		if (!pluginNetBIOS.Create (FALSE))
			err = true;
		LOG ("Startup : NetBIOS");
	}
	else
	{
		// Èíèöèàëèçàöèÿ "Ñëóæáû Ñîîáùåíèé" ñ îñòàíîâîì
		if (pluginMessenger.Create (FALSE))
			err = true;

		// Çàïóñê ìîíèòîðèíãà âõîäÿùèõ ñîîáùåíèé ÷åðåç ìåéëñëîò
		if ( ! pluginMailslot.Create( MESSENGER_MAIL ) )
			err = true;
		LOG ("Startup : Mailslot");

		// Èíèöèàëèçàöèÿ è çàïóñê ìîíèòîðèíãà âõîäÿùèõ ñîîáùåíèé ÷åðåç NetBIOS
		if (!pluginNetBIOS.Create (TRUE))
			err = true;
		LOG ("Startup : NetBIOS");
	}

	// Çàïóñê ìîíèòîðèíãà êîíòàêòîâ
	if (!pluginScanner.Create ())
		err = true;
	LOG ("Startup : Scanner");

	LOG ("Startup end");

	return !err;
}

void InternalShutdown ()
{
	LOG ("Shutdown begin");

	// Ïðåäâàðèòåëüíûå çàïðîñû íà çàêðûòèå
	pluginSearch.AskForDestroy();
	pluginMailslot.AskForDestroy();
	pluginScanner.AskForDestroy();
	pluginNetBIOS.AskForDestroy();
	pluginMessenger.AskForDestroy();

	// Çàêðûòèå ìåéëñëîòà (áûñòðî)
	pluginMailslot.Destroy ();
	LOG ("Shutdown : Mailslot");

	// Çàâåðøåíèå ïîèñêà (ìåäëåííî, åñëè èä¸ò ïîèñê)
	pluginSearch.Destroy();
	LOG ("Shutdown : Search");

	// Äåðåãèñòðàöèÿ NetBIOS èì¸í (ìåäëåííî)
	pluginNetBIOS.Destroy ();
	LOG ("Shutdown : NetBIOS");

	// Îñòàíîâ ìîíèòîðèíãà êîíòàêòîâ (ìåäëåííî, åñëè èä¸ò îïðîñ)
	pluginScanner.Destroy ();
	LOG ("Shutdown : Scanner");

	// Îñâîáîæäåíèå "Ñëóæáû Ñîîáùåíèé" (ìåäëåííî, åñëè íóæíî çàïóñêàòü ñåðâèñ)
	pluginMessenger.Destroy ();
	LOG ("Shutdown : Messenger");

	LOG ("Shutdown end");
	SetEvent( pluginInternalState );
}

void GotoOnline ()
{
	if ( pluginCurrentStatus != ID_STATUS_OFFLINE )
	{
		// Óæå â îíëàéíå
		if ( pluginCurrentStatus != ID_STATUS_CONNECTING )
		{
			// Ïðîñòî óñòàíîâêà íîâîãî ñòàòóñà
			SetPluginStatus (pluginRequestedStatus);
			return;
		}
	}

	SetPluginStatus (ID_STATUS_CONNECTING);

	if (!pluginInstalled || !pluginInitialized || pluginBusy)
		// Îòëîæåííîå ïîäêëþ÷åíèå (èëè çàïðåò)
		return;
	pluginBusy = true;

	// Íà÷àëî ñîåäèíåíèÿ
	mir_forkthread( GotoOnlineTread, NULL );
}

void GotoOffline()
{
	// Ïîäòâåðæäåíèå òåêóùåãî ñòàòóñà
	SetPluginStatus (ID_STATUS_OFFLINE);

	if (pluginBusy)
		// Äâîéíîé âûçîâ
		return;
	pluginBusy = true;

	// Ïåðåâîä âñåõ êîíòàêòîâ â îôôëàéí
	FOR_EACH_CONTACT( hContact ) {
		SetContactStatus (hContact, ID_STATUS_OFFLINE, true);
	}

	// Íà÷àëî îòñîåäèíåíèÿ
	mir_forkthread( GotoOfflineTread, NULL );
}

void GotoOnlineTread(LPVOID /* status */)
{
	// Çàïóñê
	InternalStartup();
	pluginBusy = false;
	Sleep( 1000 );

	// Ïåðåïðîâåðêà ñòàòóñà
	if ( ! pluginInstalled || pluginRequestedStatus == ID_STATUS_OFFLINE )
		// ×åðò, íóæíî îáðàòíî â îôôëàéí
		GotoOffline ();
	else
		// Âñå â ïîðÿäêå, óñòàíîâêà ñòàòóñà
		SetPluginStatus (pluginRequestedStatus);
}

void GotoOfflineTread(LPVOID /* status */)
{
	// Âûêëþ÷åíèå âñåãî
	InternalShutdown ();
	pluginBusy = false;
	Sleep( 1000 );

	// Ïåðåïðîâåðêà ñòàòóñà
	if ( pluginInstalled && pluginRequestedStatus != ID_STATUS_OFFLINE )
		// ×åðò, íóæíî îáðàòíî â îíëàéí
		GotoOnline ();
	else
		// Ïîäòâåðæäåíèå òåêóùåãî ñòàòóñà
		SetPluginStatus (ID_STATUS_OFFLINE);
}

void GetAwayMsgThread(LPVOID param)
{
	// Çàäåðæêà ÷òîáû ìèðàíäà óñïåëà "ïåðåâàðèòü" îòâåò
	Sleep( 250 );

	ContactData* data = (ContactData*)param;

	bool ret = false;

	bool bGroup = IsGroup( data->hContact );
	CString sNick = GetNick( data->hContact );
	if ( ! bGroup && ! sNick.IsEmpty() )
	{
		ThreadEvent te = { CreateEvent( NULL, TRUE, FALSE, NULL ), data->cookie };

		// Îòìå÷àåìñÿ â êàðòå îæèäàþùèõ íèòåé
		{
			CLock oLock( pluginGuard );
			pluginAwayThreadMap.SetAt( data->hContact, te );
		}

		// Àñèíõðîííûé çàïðîñ ýâåé-ñîîáùåíèÿ
		ret = pluginNetBIOS.AskAway( netbios_name( sNick, 0x03, false ) );

		// Îæèäàíèå çàâåðøåíèÿ (3 ñåêóíäû)
		ret = ret && ( WaitForSingleObject( te.evt, 3000 ) == WAIT_OBJECT_0 );

		// Î÷èñòêà êàðòû îæèäàþùèõ íèòåé
		{
			CLock oLock( pluginGuard );
			pluginAwayThreadMap.Lookup( data->hContact, te );
			pluginAwayThreadMap.RemoveKey( data->hContact );
		}

		CloseHandle( te.evt );
	}

	if ( ! ret )
	{
		// Óâåäîìëåíèå î íåóäà÷å
		ProtoBroadcastAck (modname, data->hContact, ACKTYPE_AWAYMSG,
			ACKRESULT_SUCCESS /* ACKRESULT_FAILED */, data->cookie, (LPARAM)"" );
		LOG( "Get away message failed" );
	}

	delete data;
}

void SetContactAway(HANDLE hContact, LPCSTR away)
{
	if ( ! pluginInstalled )
		return;

	// Îïðåäåëåíèå îæèäàþùåé íèòè ïî êîíòàêòó
	bool ret = false;
	ThreadEvent te = {};
	{
		CLock oLock( pluginGuard );
		if ( pluginAwayThreadMap.Lookup( hContact, te ) )
		{
			SetEvent( te.evt );
			ret = true;
		}
	}

	if ( ret )
	{
		// Óâåäîìëåíèå îá ýâåé-ñîîáùåíèè
		ProtoBroadcastAck( modname, hContact, ACKTYPE_AWAYMSG,
			ACKRESULT_SUCCESS, te.cookie, (LPARAM)away );
	}
	else
	{
		// Ïðèíóäèòåëüíàÿ óñòàíîâêà ýôåé-ñîîáùåíèÿ äëÿ êîíòàêòà
	}
}

void GetInfoThread(LPVOID param)
{
	// Çàäåðæêà ÷òîáû ìèðàíäà óñïåëà "ïåðåâàðèòü" îòâåò
	Sleep( 500 );

	HANDLE hContact = (HANDLE)param;

	ProtoBroadcastAck( modname, hContact, ACKTYPE_GETINFO,
		ACKRESULT_SUCCESS, (HANDLE)0, 0 );
}

void Autoanswer(HANDLE hContact)
{
	switch ( pluginCurrentStatus )
	{
	case ID_STATUS_AWAY:
	case ID_STATUS_DND:
	case ID_STATUS_NA:
	case ID_STATUS_OCCUPIED:
	case ID_STATUS_ONTHEPHONE:
	case ID_STATUS_OUTTOLUNCH:
		{
			CString msg;
			if ( pluginStatusMessage.Lookup( pluginCurrentStatus, msg ) )
			{
				// Îòñûëêà ñîîáùåíèÿ îòïðàâèòåëþ
				CString answer (TranslateT ("Auto-reply"));
				answer += _T(":\r\n");
				answer += msg;
				DWORD foo;
				SendContactMessage( hContact, answer, foo );

				// Äîáàâëåíèå ñîîáùåíèÿ
				DBEVENTINFO ei = {};
				ei.cbSize = sizeof (DBEVENTINFO);
				ei.szModule = modname;
				ei.timestamp = time();
				ei.flags = DBEF_SENT;
				ei.eventType = EVENTTYPE_MESSAGE;
				ei.cbBlob = (DWORD)answer.GetLength () + 1;
				ei.pBlob = (PBYTE) (LPCTSTR) answer;
				CallServiceSync( MS_DB_EVENT_ADD, (WPARAM)hContact, (LPARAM)&ei );
			}
		}
		break;
	}
}

void ReceiveContactMessage(LPCTSTR msg_from, LPCTSTR msg_to, LPCTSTR msg_text, int msg_len)
{
	if ( ! pluginInstalled )
		return;

	CString from( msg_from );
	CString to( msg_to );
	CString text( msg_text, msg_len );

	from.MakeUpper();
	to.MakeUpper();

	// Ñâîå ñîáñòâåííîå ñîîáùåíèå?
	if ( IsItMe( from ) )
	{
		LOG ( "Ignoring my message." );
		return;
	}

	// Íîðìàëèçàöèÿ ðàçáèåíèÿ ñîîáùåíèÿ íà ñòðîêè
	Normalize( text );

	// Äóáëèêàò?
	if (DBGetContactSettingByte (NULL, modname, "Filter-dups", TRUE))
	{		
		// Âû÷èñëåíèå ïðîøåäøåãî âðåìåíè ñ ïîñëåäíåãî ñîîáùåíèÿ
		static FILETIME last_time = { 0, 0 };
		FILETIME current_time;
		GetSystemTimeAsFileTime (&current_time);
		ULONGLONG elapsed =
			((ULONGLONG) current_time.dwLowDateTime |
				(ULONGLONG) current_time.dwHighDateTime << 32) -
			((ULONGLONG) last_time.dwLowDateTime |
				(ULONGLONG) last_time.dwHighDateTime << 32);

		// Âû÷èñëåíèå MD5-õýøåé îòïðàâèòåëÿ
		MD5Context ctx;
		md5init (&ctx);
		md5update (&ctx, (const unsigned char*)(LPCTSTR)from,
			from.GetLength() * sizeof (TCHAR));
		unsigned char digest_from_current [16] = {0};
		static unsigned char digest_from_last [16] = {0};
		md5final (digest_from_current, &ctx);

		// Âû÷èñëåíèå MD5-õýøåé ñîîáùåíèÿ
		md5init (&ctx);
		md5update (&ctx, (const unsigned char*)(LPCTSTR)text,
			text.GetLength() * sizeof (TCHAR));
		unsigned char digest_text_current [16] = {0};
		static unsigned char digest_text_last [16] = {0};
		md5final (digest_text_current, &ctx);

		// Åñëè ïðîøëî ìåíåå 2 ñåêóíä ìåæäó ñîîáùåíèÿìè
		if (elapsed < 20000000)
		{
			// È îòïðàâèòåëè ñîâïàäàþò
			if (memcmp (digest_from_current, digest_from_last, 16) == 0)
			{
				// È ñîîáùåíèå ñîâïàäàåò
				if (memcmp (digest_text_current, digest_text_last, 16) == 0)
				{
					// òî ïðîïóñêàåì òàêîå ñîîáùåíèå
					LOG ("Duplicate message detected");
					return;
				}
			}
		}
		last_time = current_time;
		CopyMemory (digest_from_last, digest_from_current, 16);
		CopyMemory (digest_text_last, digest_text_current, 16);
	}

#ifdef CHAT_ENABLED
	if ( ! IsItMe( to ) && pluginChatEnabled ) // Ãðóïïîâîé àäðåñ?
	{
		// Ôîðìèðîâàíèå ãðóïïîâîãî ñîîáùåíèÿ
		if ( ChatNewSession( to ) )
		{
			// Äîáàâèòü ãðóïïó
			ATLVERIFY( ChatAddGroup( to, _T("Normal") ) );

			// Äîáàâèòü ñåáÿ
			ATLVERIFY( ChatJoinMe( to, _T("Normal") ) );

			// Äîáàâèòü "Îò Êîãî"
			ATLVERIFY( ChatJoinUser( to, from, _T("Normal") ) );

			// Çàâåðøåíèå ñîçäàíèÿ ÷àòà
			ATLVERIFY( ChatInitDone( to ) );

			// Ïåðåâîä ÷àò-êîíòàêòà â îíëàéí
			ATLVERIFY( ChatOnline( to ) );

			// Ñîîáùåíèå
			ATLVERIFY( ChatMessage( to, from, text ) );
		}
	}
	else
#endif // CHAT_ENABLED
	{
		// Ôîðìèðîâàíèå ïðèâàòíîãî ñîîáùåíèÿ
		HANDLE hContact = AddToListByName( from, 0, NULL, false, false );
		if ( hContact )
		{
			PROTORECVEVENT pre = { 0 };
			pre.timestamp = time ();
			CT2A textA( text );
			pre.szMessage = (LPSTR)(LPCSTR)textA;
			CCSDATA ccs = { 0 };
			ccs.szProtoService = PSR_MESSAGE;
			ccs.hContact = hContact;
			DBDeleteContactSetting (ccs.hContact, "CList", "Hidden");
			ccs.lParam = (LPARAM) &pre;
			CallServiceSync (MS_PROTO_CHAINRECV, 0, (LPARAM) &ccs);

			// Ïåðåâîäèì êîíòàêò â îíëàéí
			SetContactStatus( hContact, contact_scanner::ScanContact( hContact ), true );

			// Àâòî-îòâåò÷èê
			if ( DBGetContactSettingByte( NULL, modname, "Auto-answer", FALSE ) )
				Autoanswer( hContact );
		}
	}
}

void Normalize(CString& msg)
{
	enum { CR, LF, NOP };
	int line_break = NOP;
	int i = 0;
	for (; i < msg.GetLength (); ++i)
	{
		switch (msg [i])
		{
		case _T('\r'):
		case _T('\xb6'):
			switch (line_break)
			{
			case CR:	// CRCR
			case LF:	// LFCR
				msg.Delete (i);
				msg.Delete (i - 1);
				msg.Insert (i - 1, _T('\r'));
				msg.Insert (i, _T('\n'));
				line_break = NOP;
				break;
			default:	// xxCR
				line_break = CR;
			}
			break;
		case _T('\n'):
			switch (line_break)
			{
			case CR:	// CRLF
				line_break = NOP;
				break;
			case LF:	// LFLF
				msg.Delete (i);
				msg.Delete (i - 1);
				msg.Insert (i - 1, _T('\r'));
				msg.Insert (i, _T('\n'));
				line_break = NOP;
				break;
			default:	// xxLF
				line_break = LF;
			}
			break;
		default:
			switch (line_break)
			{
			case CR:	// CR áåç LF
			case LF:	// LF áåç CR
				msg.Delete (i - 1);
				msg.Insert (i - 1, _T('\r'));
				msg.Insert (i, _T('\n'));
				++i;
				break;
			}
			line_break = NOP;
		}
	}
	switch (line_break)
	{
	case CR:	// CR áåç LF
	case LF:	// LF áåç CR
		msg.Delete (i - 1);
		msg.Insert (i - 1, _T('\r'));
		msg.Insert (i, _T('\n'));
		break;
	}
}

HANDLE AddToListByName(const CString& sName, WPARAM flags, LPCTSTR about, bool bInteractive, bool bGroup)
{
	ip addr = INADDR_NONE;
	CString sShortName( sName );

	if ( ! bGroup )
	{
		// Ïîïûòêà ïîëó÷èòü IP èç èìåíè
		if ( addr == INADDR_NONE )
			addr = ResolveToIP( sShortName );

		// Ïîèñê NetBIOS-èìåíè
		if ( addr == INADDR_NONE )
			addr = pluginNetBIOS.FindNameIP( sName );

		// Íåèçâåñòíûé êîíòàêò
		if ( addr == INADDR_NONE && bInteractive )
		{
			if ( MessageBox( NULL,
				TranslateT("Cannot resolve contacts IP-address. Add it anyway?"),
				modname_t, MB_YESNO | MB_ICONQUESTION ) != IDYES )
			{
				return NULL;
			}
		}
	}

	// Ïîèñê ñóùåñòâóþùåãî êîíòàêòà
	HANDLE hContact = GetContact( sShortName );
	if ( ! hContact )
	{
		// Äîáàâëåíèå êîíòàêòà
		hContact = (HANDLE)CallService( MS_DB_CONTACT_ADD, 0, 0 );
		if ( hContact )
		{
			CallService( MS_PROTO_ADDTOCONTACT, (WPARAM)hContact, (LPARAM)modname );
			SetNick( hContact, sShortName );
			SetGroup( hContact, bGroup );
			DBWriteContactSettingTString( hContact, "CList", "MyHandle", sShortName );
			DBWriteContactSettingByte( hContact, "CList", "NotOnList", 1 );
			DBWriteContactSettingByte( hContact, "CList", "Hidden", 1 );
			SetContactIP( hContact, addr );
			SetElapsed( hContact, "IPTime" );
			if ( about )
				DBWriteContactSettingTString( hContact, modname, "About", about );

			contact_scanner::ScanContact( hContact );
		}
	}
	if ( hContact && ! ( flags & PALF_TEMPORARY ) &&
		DBGetContactSettingByte( hContact, "CList", "NotOnList", 1 ) )
	{
		// Îñòàâëÿåì êîíòàêò
		DBDeleteContactSetting( hContact, "CList", "NotOnList" );
		DBDeleteContactSetting( hContact, "CList", "Hidden" );
	}
	return hContact;
}

DWORD GetElapsed (HANDLE hContact, const char* name)
{
	FILETIME current = {};
	GetSystemTimeAsFileTime (&current);
	LARGE_INTEGER currentL = {};
	currentL.LowPart = current.dwLowDateTime;
	currentL.HighPart = (LONG)current.dwHighDateTime;					
	LARGE_INTEGER lastseenL = {};
	lastseenL.LowPart = DBGetContactSettingDword (hContact, modname,
		CStringA (name) + "L", 0);
	lastseenL.HighPart = (LONG)DBGetContactSettingDword (hContact, modname,
		CStringA (name) + "H", 0);
	return (DWORD) (((currentL.QuadPart - lastseenL.QuadPart) / 10000000L) & 0xffffffff);
}

void SetElapsed (HANDLE hContact, const char* name)
{
	FILETIME current = {};
	GetSystemTimeAsFileTime (&current);
	DBWriteContactSettingDword (hContact, modname,
		CStringA (name) + "L", current.dwLowDateTime);
	DBWriteContactSettingDword (hContact, modname,
		CStringA (name) + "H", current.dwHighDateTime);
}

HANDLE GetContact (ip addr)
{
	// Ïåðåáîð ñïèñêà êîíòàêòîâ
	FOR_EACH_CONTACT( hContact )
	{
		// Ïîëó÷åíèå èìåíè êîíòàêòà
		ip contact_addr = DBGetContactSettingDword (hContact, modname, "IP", 0);
		if (contact_addr && (contact_addr == addr))
			// Íàéäåíî ñîâïàäåíèå
			break;
	}
	return hContact;
}

HANDLE GetContact (LPCTSTR name)
{
	// Ïåðåáîð ñïèñêà êîíòàêòîâ
	FOR_EACH_CONTACT( hContact )
	{
		// Ïîëó÷åíèå èìåíè êîíòàêòà
		CString sNick = GetNick( hContact );
		if ( ! sNick.IsEmpty() )
		{
			// Ñëè÷åíèå èìåí
			if ( sNick.CompareNoCase( name ) == 0 )
				// Íàéäåíî ñîâïàäåíèå
				break;
		}
	}
	return hContact;
}

void SetContactStatus (HANDLE hContact, int status, bool simple)
{
	if ( ! pluginInstalled )
		return;

	SetElapsed (hContact, "LastSeen");

#ifdef CHAT_ENABLED
	if ( IsChatRoom( hContact ) )
	{
		CString sSession = GetChatSession( hContact );
		if ( pluginChatEnabled && ! sSession.IsEmpty() )
		{
			if ( status != ID_STATUS_OFFLINE )
				ChatOnline( sSession );
			else
				ChatOffline( sSession );
		}
	}
	else
#endif // CHAT_ENABLED
	{
		int ns = DBGetContactSettingWord (hContact, modname, "Status", -1);
		if ( ns != status )
		{
			// Èçìåíåíèå ñòàòóñà
			if ( ! simple )
				// Òî÷íàÿ óñòàíîâêà ñòàòóñà
				DBWriteContactSettingWord (hContact, modname, "Status", (WORD) status);
			else if ( ns == -1 || ns == ID_STATUS_OFFLINE || status != ID_STATUS_ONLINE )
				// Ïðèìåðíàÿ óñòàíîâêà ñòàòóñà
				DBWriteContactSettingWord (hContact, modname, "Status", (WORD) status);
		}
	}
}

void GetAvatarInfoThread(LPVOID param)
{
	// Çàäåðæêà ÷òîáû ìèðàíäà óñïåëà "ïåðåâàðèòü" îòâåò
	Sleep( 500 );

	ContactData* data = (ContactData*)param;

	bool ret = false;
	ThreadEvent te = { CreateEvent( NULL, TRUE, FALSE, NULL ), data->cookie };
	PROTO_AVATAR_INFORMATION pai = { sizeof( PROTO_AVATAR_INFORMATION ), data->hContact };

	TCHAR szPath[ MAX_PATH ];
	GetAvatarCache( szPath );

	// Ïîëó÷åíèå êåøèðîâàííîãî àâàòàðà
	DBVARIANT dbv = {};
	if ( ! DBGetContactSettingTString( data->hContact, modname, "AvatarFile", &dbv ) )
	{
		lstrcat( szPath, dbv.ptszVal );

		if ( GetFileAttributes( szPath ) != INVALID_FILE_ATTRIBUTES )
		{
			ret = true;

			lstrcpyA( pai.filename, CT2A( szPath ) );

			// Îïðåäåëåíèå ôîðìàòà
			LPCTSTR szExt = _tcsrchr( dbv.ptszVal, _T('.') );
			if ( ! szExt )
			{
				pai.format = PA_FORMAT_UNKNOWN;
			}
			else if ( lstrcmpi( szExt, _T(".png") ) == 0 || lstrcmpi( szExt, _T(".dat") ) == 0 )
			{
				pai.format = PA_FORMAT_PNG;
			}
			else if ( lstrcmpi( szExt, _T(".jpg") ) == 0 )
			{
				pai.format = PA_FORMAT_JPEG;
			}
			else if ( lstrcmpi( szExt, _T(".ico") ) == 0 )
			{
				pai.format = PA_FORMAT_ICON;
			}
			else if ( lstrcmpi( szExt, _T(".bmp") ) == 0 )
			{
				pai.format = PA_FORMAT_BMP;
			}
			else if ( lstrcmpi( szExt, _T(".gif") ) == 0 )
			{
				pai.format = PA_FORMAT_GIF;
			}
			else if ( lstrcmpi( szExt, _T(".swf") ) == 0 )
			{
				pai.format = PA_FORMAT_SWF;
			}
			else if ( lstrcmpi( szExt, _T(".xml") ) == 0 )
			{
				pai.format = PA_FORMAT_XML;
			}
			else
			{
				pai.format = PA_FORMAT_UNKNOWN;
			}
		}
		DBFreeVariant( &dbv );
	}
	if ( ret )
	{
		ProtoBroadcastAck( modname, data->hContact, ACKTYPE_AVATAR,
			ACKRESULT_SUCCESS, &pai, 0 );
		LOG( "Returned cached avatar." );
	}
	else
	{
		bool bGroup = IsGroup( data->hContact );
		CString sNick = GetNick( data->hContact );
		if ( ! bGroup && ! sNick.IsEmpty() )
		{
			// Àñèíõðîííûé ñåòåâîé çàïðîñ àâàòàðà
			ProtoBroadcastAck( modname, data->hContact, ACKTYPE_AVATAR,
				ACKRESULT_SENTREQUEST, &pai, 0 );

			// Îòìå÷àåìñÿ â êàðòå îæèäàþùèõ íèòåé
			{
				CLock oLock( pluginGuard );
				pluginAvatarThreadMap.SetAt( data->hContact, te );
			}

			ret = pluginNetBIOS.AskAvatar( netbios_name( sNick, 0x03 ) );

			// Îæèäàíèå çàâåðøåíèÿ (3 ñåêóíäû)
			ret = ret && ( WaitForSingleObject( te.evt, 3000 ) == WAIT_OBJECT_0 );

			// Î÷èñòêà êàðòû îæèäàþùèõ íèòåé
			{
				CLock oLock( pluginGuard );
				pluginAvatarThreadMap.Lookup( data->hContact, te );
				pluginAvatarThreadMap.RemoveKey( data->hContact );
			}
		}
		if ( ! ret )
		{
			ProtoBroadcastAck( modname, data->hContact, ACKTYPE_AVATAR,
				ACKRESULT_FAILED, &pai, 0 );
			LOG( "Get avatar failed" );
		}
	}

	if ( te.evt )
		CloseHandle( te.evt );

	delete data;
}

void SetContactAvatar(HANDLE hContact, LPCVOID pBuffer, DWORD nLength)
{
	if ( ! pluginInstalled )
		return;

	PROTO_AVATAR_INFORMATION pai = { sizeof( PROTO_AVATAR_INFORMATION ), hContact };

	CString sFilename, sNick = GetNick( hContact );
	if ( sNick.IsEmpty() || sNick.FindOneOf( _T("/\\*?:|\"<>%") ) != -1 )
	{
		// Ïîëó÷åíèå ñòàðîãî èìåíè
		DBVARIANT dbv = {};
		if ( ! DBGetContactSettingTString( hContact, modname, "AvatarFile", &dbv ) )
		{
			sFilename = dbv.ptszVal;
			DBFreeVariant( &dbv );
		}
		else
			// Ãåíåðàöèÿ óíèêàëüíîãî èìåíè
			sFilename.Format( _T("%08x_avt"), (DWORD)hContact );
	}
	else
		// Ãåíåðàöèÿ óíèêàëüíîãî èìåíè
		sFilename.Format( _T("%s_%08x_avt"), sNick, (DWORD)hContact );

	// Îïðåäåëåíèå òèïà èçîáðàæåíèÿ
	if ( ! memcmp( pBuffer, "%PNG", 4 ) )
	{
		pai.format = PA_FORMAT_PNG;
		sFilename += _T(".png");
	}
	else if ( *(DWORD*)pBuffer == 0xE0FFD8FFul || *(DWORD*)pBuffer == 0xE1FFD8FFul )
	{
		pai.format = PA_FORMAT_JPEG;
		sFilename += _T(".jpg");
	}
	else if ( *(DWORD*)pBuffer == 0x00010000 )
	{
		pai.format = PA_FORMAT_ICON;
		sFilename += _T(".ico");
	}
	else if ( ! memcmp( pBuffer, "BM", 2 ) )
	{
		pai.format = PA_FORMAT_BMP;
		sFilename += _T(".bmp");
	}
	else if ( ! memcmp( pBuffer, "GIF", 3 ) )
	{
		pai.format = PA_FORMAT_GIF;
		sFilename += _T(".gif");
	}
	else if ( ! memcmp( pBuffer, "CWS", 3 ) )
	{
		pai.format = PA_FORMAT_SWF;
		sFilename += _T(".swf");
	}
	else if ( ! memcmp( pBuffer, "<?xml", 5 ) )
	{
		pai.format = PA_FORMAT_XML;
		sFilename += _T(".xml");
	}
	else
	{
		pai.format = PA_FORMAT_UNKNOWN;
		sFilename += _T(".dat");
	}

	// Ñáîðêà ïîëíîãî ïóòè ê ôàéëó
	TCHAR szPath[ MAX_PATH ];
	GetAvatarCache( szPath );

	lstrcat( szPath, sFilename );

	CAtlFile oAvatarFile;
	if ( FAILED( oAvatarFile.Create( szPath, GENERIC_WRITE,
		FILE_SHARE_READ, CREATE_ALWAYS ) ) )
		// Ôàéë íå íàéäåí
		return;

	if ( FAILED( oAvatarFile.Write( pBuffer, nLength ) ) )
		// Îøèáêà çàïèñè â ôàéë
		return;

	oAvatarFile.Close();

	DBWriteContactSettingTString( hContact, modname, "AvatarFile", sFilename );

	// Îïðåäåëåíèå îæèäàþùåé íèòè ïî êîíòàêòó
	bool ret = false;
	ThreadEvent te = {};
	{
		CLock oLock( pluginGuard );
		if ( pluginAvatarThreadMap.Lookup( hContact, te ) )
		{
			SetEvent( te.evt );
			ret = true;
		}
	}

	lstrcpyA( pai.filename, CT2A( szPath ) );

	if ( ret )
	{
		// Óâåäîìëåíèå î íîâîì àâàòàðå
		ProtoBroadcastAck( modname, hContact, ACKTYPE_AVATAR, ACKRESULT_SUCCESS, &pai, 0 );
	}
	else
	{
		// Ëèáî ïðîïóñòèëè ñîáûòèå, ëèáî åãî íå áûëî - ñòàâèì àâàòàð ïðèíóäèòåëüíî
		if ( ServiceExists( MS_AV_SETAVATAR ) )
		{
			CallService( MS_AV_SETAVATAR, (WPARAM)hContact, (LPARAM)pai.filename );
		}
	}
}

ip GetContactIP (HANDLE hContact)
{
	ip addr = INADDR_NONE;
	bool got_nick = false, nick_invalid = false;
	DBVARIANT dbv = {};
	if ( hContact )
	{
		CString sNick = GetNick( hContact );
		if ( ! sNick.IsEmpty() )
		{
			got_nick = true;
		}
		else if ( ! DBGetContactSettingTString( hContact, "CList", "MyHandle", &dbv ) )
		{
			nick_invalid = true;
			got_nick = true;
		}

		if ( got_nick )
		{
			// Âîññòàíîâëåíèå íèêà
			if ( nick_invalid )
				SetNick( hContact, dbv.ptszVal );

			// Åñëè íå èñòåêëî âðåìÿ êåøèðîâàíèÿ àäðåñà, òî èç êîíòàêòà 
			DWORD elapsed = GetElapsed (hContact, "IPTime");
			if (elapsed <= MAX_TRUSTED_IP_TIME)
				addr = DBGetContactSettingDword (hContact, modname, "IP", 0);
			if (addr == INADDR_NONE) {
				// Ðàçáîð DNS-àäðåñà
				CString name (dbv.pszVal);
				addr = ResolveToIP (name);
				if (addr != INADDR_NONE)
					SetElapsed (hContact, "IPTime");
			}
			if (addr != INADDR_NONE)
				SetContactIP (hContact, addr);
			DBFreeVariant (&dbv);
		}
	}
	return addr;
}

void SetContactIP(HANDLE hContact, ip addr)
{
	if ( ! pluginInstalled )
		return;

	if ( hContact )
	{
		DBWriteContactSettingDword	(hContact, modname, "IP", addr);
		DBWriteContactSettingDword	(hContact, modname, "RealIP", addr);
	}
}

bool IsGroup(HANDLE hContact)
{
	return ( DBGetContactSettingByte( hContact, modname, "Group", 0u ) != 0u );
}

void SetGroup(HANDLE hContact, bool bGroup)
{
	DBWriteContactSettingByte( hContact, modname, "Group", ( bGroup ? 1u : 0u ) );
}

bool IsLegacyOnline(HANDLE hContact)
{
	return ( DBGetContactSettingByte( hContact, modname, "Check00ForOnline", 0u ) != 0u );
}

void SetLegacyOnline(HANDLE hContact, bool bOnline)
{
	DBWriteContactSettingByte( hContact, modname, "Check00ForOnline", ( bOnline ? 1u : 0u ) );
}

bool SendContactMessage(HANDLE hContact, LPCTSTR msg, DWORD& err)
{
	// Ïîëó÷åíèå ìåòîäà ïîñûëêè
	BYTE method = (BYTE)DBGetContactSettingByte( NULL, modname, "SendMethod", 0 );
	switch ( method )
	{
		case 0:
			return pluginMailslot.SendMailslotMessage( hContact, msg, err );
		case 1:
			return pluginNetBIOS.SendNetBIOSMessage( hContact, msg, err );
		case 2:
			return pluginMessenger.SendMessengerMessage( hContact, msg, err );
		default:
			return false;
	}
}

void SendMsgThread(LPVOID param)
{
	SendMsgData* data = (SendMsgData*)param;

	DWORD dwLastError = 0;
	if ( SendContactMessage( data->hContact, data->text, dwLastError ) )
	{
		ProtoBroadcastAck ( modname, data->hContact, ACKTYPE_MESSAGE,
			ACKRESULT_SUCCESS, data->cookie, 0 );
	}
	else
	{
		// Óâåäîìëåíèå îá îøèáêå
		CString msg, buf;
		GetErrorMessage (dwLastError, buf);
		msg.Format( _T("%s\r\n%s"), TranslateT ("Cannot send message"), (LPCTSTR)buf);
		ProtoBroadcastAck (modname, data->hContact, ACKTYPE_MESSAGE,
			ACKRESULT_FAILED, data->cookie, (LPARAM)(LPCTSTR)msg );

		// È çàîäíî ïîïàïîì
		WarningBox( data->hContact, dwLastError, TranslateT("Cannot send message") );
	}

	delete data;
}

bool IsItMe(LPCTSTR name)
{
	return ! pluginMachineName.CompareNoCase( name ) ||
		! pluginUserName.CompareNoCase( name );
}

void EnumWorkgroups(CAtlList< CString >& lst, LPNETRESOURCE hRoot)
{
	HANDLE hEnum = NULL;
	DWORD res = WNetOpenEnum( RESOURCE_GLOBALNET, RESOURCETYPE_ANY,
		RESOURCEUSAGE_CONTAINER, hRoot, &hEnum );
	if ( res == NO_ERROR )
	{
		for (;;)
		{
			DWORD cCount = 1;
			DWORD BufferSize = 4096;
			char* Buffer = (char*)mir_alloc( BufferSize );
			if ( ! Buffer )
				break;
			res = WNetEnumResource( hEnum, &cCount, Buffer, &BufferSize );
			if ( res == NO_ERROR )
			{
				LPNETRESOURCE lpnr = (LPNETRESOURCE)Buffer;
				if ( lpnr->dwDisplayType == RESOURCEDISPLAYTYPE_DOMAIN )
				{
					CharUpper ( lpnr->lpRemoteName );
					lst.AddTail( lpnr->lpRemoteName );
				}
				else if ( ( lpnr->dwUsage & 0xffff ) == RESOURCEUSAGE_CONTAINER )
				{
					EnumWorkgroups( lst, lpnr );
				}
				mir_free( Buffer );
			}
			else
			{
				mir_free( Buffer );
				break;
			}
		}
		WNetCloseEnum (hEnum);
	}
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID /*lpReserved*/)
{
	pluginModule = hModule;
	return TRUE;
}