summaryrefslogtreecommitdiff
path: root/plugins/!NotAdopted/WinPopup/src/netbios.cpp
blob: 4ee029859791280cbb37fd2661c269c4fb24b82a (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
/*

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"

netbios pluginNetBIOS;	// Ïðèåì/îòïðàâêà ñîîáùåíèé ÷åðåç NetBIOS

// Ìàêðîñ ïå÷àòè NetBIOS-èìåíè
#define NETBIOS_NAME_TRACE(bb,mm,nn) mir_snprintf((bb),(mm),"%s #%d %02x %c %s", \
	(nn.GetANSIFullName()), (nn.name_num), (nn.name_flags), \
	(((nn.name_flags & GROUP_NAME) == GROUP_NAME) ? 'G' : 'U'), \
	(((nn.name_flags & (NAME_FLAGS_MASK & ~GROUP_NAME)) == REGISTERING) ? "REGISTERING" : \
	(((nn.name_flags & (NAME_FLAGS_MASK & ~GROUP_NAME)) == REGISTERED) ? "REGISTERED" : \
	(((nn.name_flags & (NAME_FLAGS_MASK & ~GROUP_NAME)) == DEREGISTERED) ? "DEREGISTERED" : \
	(((nn.name_flags & (NAME_FLAGS_MASK & ~GROUP_NAME)) == DUPLICATE) ? "DUPLICATE" : \
	(((nn.name_flags & (NAME_FLAGS_MASK & ~GROUP_NAME)) == DUPLICATE_DEREG) ? "DUPLICATE_DEREG" : \
	"UNKNOWN"))))));

// NetBIOS commands
static const struct
{
	UCHAR	code;		// NetBIOS command code
	LPCSTR	name;		// NetBIOS command description
}
NCBCommands[] = 
{
	{ NCBCALL,			"CALL" },
	{ NCBLISTEN,		"LISTEN" },
	{ NCBHANGUP,		"HANG UP" },
	{ NCBSEND,			"SEND" },
	{ NCBRECV,			"RECEIVE" },
	{ NCBRECVANY,		"RECEIVE ANY" },
	{ NCBCHAINSEND,		"CHAIN SEND" },
	{ NCBDGSEND,		"SEND DATAGRAM" },
	{ NCBDGRECV,		"RECEIVE DATAGRAM" },
	{ NCBDGSENDBC,		"SEND BROADCAST DATAGRAM" },
	{ NCBDGRECVBC,		"RECEIVE BROADCAST DATAGRAM" },
	{ NCBADDNAME,		"ADD NAME" },
	{ NCBDELNAME,		"DELETE NAME" },
	{ NCBRESET,			"RESET" },
	{ NCBASTAT,			"ADAPTER STATUS" },
	{ NCBSSTAT,			"SESSION STATUS" },
	{ NCBCANCEL,		"CANCEL" },
	{ NCBADDGRNAME,		"ADD GROUP NAME" },
	{ NCBENUM,			"ENUMERATE LANA NUMBERS" },
	{ NCBUNLINK,		"UNLINK" },
	{ NCBSENDNA,		"SEND NO ACK" },
	{ NCBCHAINSENDNA,	"CHAIN SEND NO ACK" },
	{ NCBLANSTALERT,	"LAN STATUS ALERT" },
	{ NCBACTION,		"ACTION" },
	{ NCBFINDNAME,		"FIND NAME" },
	{ NCBTRACE,			"TRACE" },
	{ 0,				NULL }
};

// NetBIOS errors
static const struct
{
	UCHAR	error;		// NetBIOS error code
	LPCSTR	message;	// NetBIOS error message
}
NRCErrors [] =
{
	{ NRC_GOODRET,		"The operation succeeded." },
	{ NRC_BUFLEN,		"An illegal buffer length was supplied." },
	{ NRC_ILLCMD,		"An illegal command was supplied." },
	{ NRC_CMDTMO,		"The command was timed out." },
	{ NRC_INCOMP,		"The message was incomplete. The application is to issue another command." },
	{ NRC_BADDR,		"The buffer address was illegal." },
	{ NRC_SNUMOUT,		"The session number was out of range." },
	{ NRC_NORES,		"No resource was available." },
	{ NRC_SCLOSED,		"The session was closed." },
	{ NRC_CMDCAN,		"The command was canceled." },
	{ NRC_DUPNAME,		"A duplicate name existed in the local name table." },
	{ NRC_NAMTFUL,		"The name table was full." },
	{ NRC_ACTSES,		"The command finished; the name has active sessions and is no longer registered." },
	{ NRC_LOCTFUL,		"The local session table was full." },
	{ NRC_REMTFUL,		"The remote session table was full. The request to open a session was rejected." },
	{ NRC_ILLNN,		"An illegal name number was specified." },
	{ NRC_NOCALL,		"The system did not find the name that was called." },
	{ NRC_NOWILD,		"Wildcards are not permitted in the ncb_name member." },
	{ NRC_INUSE,		"The name was already in use on the remote adapter." },
	{ NRC_NAMERR,		"The name was deleted." },
	{ NRC_SABORT,		"The session ended abnormally." },
	{ NRC_NAMCONF,		"A name conflict was detected." },
	{ NRC_IFBUSY,		"The interface was busy." },
	{ NRC_TOOMANY,		"Too many commands were outstanding; the application can retry the command later." },
	{ NRC_BRIDGE,		"The ncb_lana_num member did not specify a valid network number." },
	{ NRC_CANOCCR,		"The command finished while a cancel operation was occurring." },
	{ NRC_CANCEL,		"The NCBCANCEL command was not valid; the command was not canceled." },
	{ NRC_DUPENV,		"The name was defined by another local process." },
	{ NRC_ENVNOTDEF,	"The environment was not defined." },
	{ NRC_OSRESNOTAV,	"Operating system resources were exhausted. The application can retry the command later." },
	{ NRC_MAXAPPS,		"The maximum number of applications was exceeded." },
	{ NRC_NOSAPS,		"No service access points (SAPs) were available for NetBIOS." },
	{ NRC_NORESOURCES,	"The requested resources were not available." },
	{ NRC_INVADDRESS,	"The NCB address was not valid." },
	{ NRC_INVDDID,		"The NCB DDID was invalid." },
	{ NRC_LOCKFAIL,		"The attempt to lock the user area failed." },
	{ NRC_OPENERR,		"An error occurred during an open operation being performed by the device driver." },
	{ NRC_SYSTEM,		"A system error occurred." },
	{ NRC_PENDING,		"An asynchronous operation is not yet finished." },
	{ 0,				NULL }
};

LPCSTR GetNetbiosCommand(UCHAR command)
{
	command &= 0x7f; // strip ASYNCH bit
	for ( int i = 0; NCBCommands[ i ].name; ++i )
		if ( NCBCommands[ i ].code == command )
			return NCBCommands[ i ].name;
	return "UNKNOWN";
}

LPCSTR GetNetbiosError(UCHAR err)
{
	for ( int i = 0; NRCErrors [ i ].message; ++i )
		if ( NRCErrors [ i ].error == err )
			return NRCErrors [ i ].message;
	return "Unknown error.";
}

UCHAR NetbiosEx(NCB* pNCB)
{
	UCHAR command = pNCB->ncb_command;
	UCHAR ret = Netbios( pNCB );
	//if ( ret != NRC_GOODRET )
	if ( ret == pNCB->ncb_retcode )
	{
		LOG( "NetBIOS call 0x%02x \"%s\" result: 0x%02x \"%s\"",
			command, GetNetbiosCommand( command ),
			ret, GetNetbiosError( ret ) );
	}
	else
	{
		LOG( "NetBIOS call 0x%02x \"%s\" result: 0x%02x \"%s\", return: 0x%02x \"%s\"",
			command, GetNetbiosCommand( command ),
			ret, GetNetbiosError( ret ),
			pNCB->ncb_retcode, GetNetbiosError( pNCB->ncb_retcode ) );
	}
	return ret;
}

// Îïðåäåëåíèå NCB íå íà ñòåêå
// KB317437: "NetBIOS Listen May Return a Damaged NCB Structure"
// The _NCB structure that is returned when a NetBIOS Listen call completes may have a changed server name offset. 
class CNCB
{
public:
	CNCB() :
		m_buf( VirtualAlloc( NULL, 4096, MEM_COMMIT, PAGE_READWRITE ) )
	{
	}

	~CNCB()
	{
		if ( m_buf )
		{
			VirtualFree( m_buf, 0, MEM_RELEASE );
		}
	}

	inline operator bool() const
	{
		return ( m_buf != NULL );
	}

	inline operator NCB*() const
	{
		return (NCB*)m_buf;
	}

	inline NCB* operator->() const
	{
		return (NCB*)m_buf;
	}

protected:
	void* m_buf;
};

////////////////////////////////////////////////////////////////////////
// Class netbios

netbios::netbios () :
	m_initialized( false )
{
	ZeroMemory (&m_le, sizeof (m_le));
}

netbios::~netbios ()
{
	Destroy ();
}

bool netbios::Create (BOOL registration)
{
	CLock oLock( m_csData );

	if ( ! m_initialized )
	{
		// Ïåðå÷èñëåíèå àäàïòåðîâ
		if ( EnumLanas( m_le ) == NRC_GOODRET )
		{		
			// Ñáðîñ àäàïòåðîâ
			for ( UCHAR i = 0; i < m_le.length; i++ )
			{
				ResetLana( m_le.lana [i] );
			}

			// Ðåãèñòðàöèÿ èì¸í, åñëè íóæíà
			if ( registration )
			{
				Register ();
			}
		}

		m_initialized = true;
	}

	return m_initialized;
}

void netbios::AskForDestroy()
{
	CLock oLock( m_csData );

	// Çàïðîñ íà äåðåãèñòðàöèþ èì¸í
	for ( size_t i = 0; i < m_names.GetCount (); ++i )
		m_names [i]->AskForDestroy();
}

void netbios::Destroy ()
{
	CLock oLock( m_csData );

	if ( m_initialized )
	{
		Deregister();
		m_initialized = false;
	}
}

unsigned char* netbios::SetSMBHeaderCommand (unsigned char* szHeader, BYTE iCommandCode, size_t iBufferLen)
{
	ZeroMemory (szHeader, iBufferLen);
	*(DWORD*)szHeader = SMB_MAGIC;
	szHeader [4] = iCommandCode;
	return (szHeader + SMB_HEADER_SIZE);
}

netbios::operator bool() const
{
	return m_initialized;
}

bool netbios::SendNetBIOSMessage(HANDLE hContact, LPCTSTR msg, DWORD& err)
{
	// Created by Ilja Razinkov (also known as IPv6), 2002, IPv6Intendo@yandex.ru
	// Keep this comment if you redistribute this file

	//Ñõåìà îòïðàâêè áîëüøîãî NB-ñîîáùåíèÿ:
	//1) Øëåòñÿ D5. Òåêñò ñîîáùåíèÿ:
	//- 00, äëèíà îñòàòêà A (1 áàéò), 00 (3 áàéòà)
	//- îñòàòîê A. 04, ñòðîêà ÊÒÎ, 00, 04, ñòðîêà ÊÎÌÓ, 00
	//â îòâåò ïðèõîäèò ÊÎÄ ÑÎÎÁÙÅÍÈß (2 áàéòà) è 00,00,00 (âñåãî 5 áàéò), ñ D5 â çàãîëîâêå
	//
	//2) Øëåòñÿ D7. Òåêñò ñîîáùåíèÿ:
	//- ÊÎÄ ÑÎÎÁÙÅÍÈß (2 áàéòà), 00, äëèíà îñòàòêà (A+B) (1 áàéò), 00 (âñåãî 5 áàéò)
	//- îñòàòîê A. 01, äëèíà îñòàòêà B, 00 (3 áàéòà)
	//- îñòàòîê B. î÷åðåäíîé êóñîê ïîñëàííîãî ÑÎÎÁÙÅÍÈß
	//â îòâåò ïðèõîäèò ïóñòîå ñîîáùåíèå (ñ 3ìÿ 0-ëÿìè), ñ D7 â çàãîëîâêå
	//
	//3) Ïóíêò 2 ïîâòîðÿåòñÿ ïîêà íå áóäåò îòîñëàíî âñå ÑÎÎÁÙÅÍÈÅ
	//
	//4) Øëåòñÿ D6.Òåêñò ñîîáùåíèÿ:
	//- ÊÎÄ ÑÎÎÁÙÅÍÈß (2 áàéòà), 00, 00, 00 (âñåãî 5 áàéò)
	//â îòâåò ïðèõîäèò ïóñòîå ñîîáùåíèå (ñ 3ìÿ 0-ëÿìè), ñ D6 â çàãîëîâêå

	// Ïîëó÷åíèå àäðåñàòà
	CString sTo = GetNick( hContact );
	if ( sTo.IsEmpty() )
	{
		err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, NRC_NOCALL );
		return false;
	}

	// Ïîëó÷åíèå ñâîåãî èìåíè
	CString sFrom = GetNick( NULL );
	if ( sFrom.IsEmpty() )
	{
		err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, NRC_NOCALL );
		return false;
	}

	bool bGroup = IsGroup( hContact );

	// Ïîäãîòîâêà äàííûõ
	CStringA sMessage( msg );
	sMessage.AnsiToOem();
	sMessage.Replace( "\r\n", "\x14" );	// <CR><LF> -> <14>
	sMessage.Replace( "\r", "\x14" );	// <CR> -> <14>
	sMessage.Replace( "\n", "\x14" );	// <LF> -> <14>
	netbios_name nname_To( sTo, 3, bGroup );
	netbios_name nname_From( sFrom, 3 );

	// Ïîèñê àäàïòåðà
	UCHAR lana = 0;
	if ( ! FindNameLana( nname_To, lana ) )
	{
		LOG ("SendNetBIOSMessage : Unknown name");
		err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, NRC_NOCALL );
		return false;
	}

	// Êîííåêò ê êëèåíòó
	UCHAR lsn = 0;
	err = Call (lana, nname_From, nname_To, lsn);
	if (err != NRC_GOODRET)
	{
		LOG ("SendNetBIOSMessage : Cannot connect" );
		err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, err );
		return false;
	}

	UCHAR SMBBlock [168] = { 0 };
	UCHAR* szSMBData = NULL;
	UCHAR iFromLen = (UCHAR)nname_From.GetLength ();
	UCHAR iToLen = (UCHAR)nname_To.GetLength ();
	UCHAR iHiMsgCode = 0, iLoMsgCode = 0;

	// 1. Øëåì çàãîëîâîê
	LOG ( "SendNetBIOSMessage : Send start of multi-block message" );
	szSMBData = SetSMBHeaderCommand (SMBBlock, SMBsendstrt, sizeof (SMBBlock));
	UCHAR dwD5ALength = (UCHAR)( 1 + iFromLen + 2 + iToLen + 1 );
	szSMBData[1] = dwD5ALength;
	szSMBData[3] = 4;
	szSMBData[4+iFromLen+1] = 4;
	CopyMemory ( szSMBData + 4, nname_From.netbiosed.name, iFromLen );
	CopyMemory ( szSMBData + 4 + iFromLen + 2, nname_To.netbiosed.name, iToLen );
	UCHAR dwD5Length = (UCHAR)( 3 + dwD5ALength );
	err = Send (lana, lsn, SMBBlock, (WORD) (SMB_HEADER_SIZE + dwD5Length));
	if (err != NRC_GOODRET)
	{
		LOG ( "SendNetBIOSMessage : Can`t start session" );
		Hangup (lana, lsn);
		err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, err );
		return false;
	}

	// Æäåì ïîäòâåðæäåíèÿ
	WORD length = sizeof (SMBBlock);
	err = Recv (lana, lsn, SMBBlock, length);
	if (err != NRC_GOODRET)
	{
		LOG ( "SendNetBIOSMessage : No reply (start session)" );
		Hangup (lana, lsn);
		err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, err );
		return false;
	}
	iHiMsgCode=SMBBlock[SMB_HEADER_SIZE];
	iLoMsgCode=SMBBlock[SMB_HEADER_SIZE+1];

	// 2. Øëåì ñîîáùåíèå (êóñî÷êàìè)
	UCHAR dwD7BLength = 0;
	for (int iSendedBytes = 0; iSendedBytes < sMessage.GetLength (); iSendedBytes += dwD7BLength)
	{
		dwD7BLength = sizeof (SMBBlock) - (5 + 3 + SMB_HEADER_SIZE);
		szSMBData = SetSMBHeaderCommand (SMBBlock, SMBsendtxt, sizeof (SMBBlock));
		if (iSendedBytes + dwD7BLength > sMessage.GetLength ())
			dwD7BLength = (UCHAR)( sMessage.GetLength () - iSendedBytes );
		szSMBData[0]=iHiMsgCode;
		szSMBData[1]=iLoMsgCode;
		szSMBData[3]=(UCHAR)( dwD7BLength + 3 );
		szSMBData[5]=1;
		szSMBData[6]=dwD7BLength;
		CopyMemory (szSMBData + 5 + 3, (LPCSTR) sMessage + iSendedBytes, dwD7BLength);
		LOG( "SendNetBIOSMessage : Send text (%u-%u bytes) of multi-block message" , iSendedBytes, iSendedBytes + dwD7BLength - 1);
		err = Send (lana, lsn, SMBBlock, (WORD) (SMB_HEADER_SIZE + 5 + 3 + dwD7BLength));
		if (err != NRC_GOODRET)
		{
			LOG ( "SendNetBIOSMessage : Can`t use session" );
			Hangup (lana, lsn);
			err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, err );
			return false;
		}
		// Æäåì ïîäòâåðæäåíèÿ
		length = sizeof (SMBBlock);
		err = Recv (lana, lsn, SMBBlock, length);
		if (err != NRC_GOODRET)
		{
			LOG ( "SendNetBIOSMessage : No reply (use session)" );
			Hangup (lana, lsn);
			err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, err );
			return false;
		}
	}

	// 3. Øëåì èçâåùåíèå ÷òî âñå îòîñëàíî
	LOG ( "SendNetBIOSMessage : Send and of multi-block message" );
	szSMBData = SetSMBHeaderCommand (SMBBlock, SMBsendend, sizeof (SMBBlock));
	DWORD dwD6Length=5;
	szSMBData[0]=iHiMsgCode;
	szSMBData[1]=iLoMsgCode;
	err = Send (lana, lsn, SMBBlock, (WORD) (SMB_HEADER_SIZE + dwD6Length));
	if (err != NRC_GOODRET)
	{
		LOG ( "SendNetBIOSMessage : Can`t close session" );
		Hangup (lana, lsn);
		err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, err );
		return false;
	}

	// Æäåì ïîäòâåðæäåíèÿ
	length = sizeof (SMBBlock);
	err = Recv (lana, lsn, SMBBlock, length);
	if (err != NRC_GOODRET)
	{
		LOG ( "SendNetBIOSMessage : No reply (close session)" );
		Hangup (lana, lsn);
		err = (DWORD)MAKE_HRESULT( 0, FACILITY_NETBIOS, err );
		return false;
	}

	// Çàêðûâàåì ñåññèþ
	Hangup (lana, lsn);
	err = (DWORD)MAKE_HRESULT( 1, FACILITY_NETBIOS, NRC_GOODRET );
	return true;
}

ip netbios::FindNameIP (LPCTSTR szName, UCHAR type)
{
	// Ïîèñê èìåíè
	netbios_name nname( szName, type );
	ip addr = INADDR_NONE;
	FIND_NAME_BLOCK fn = { 0 };
	for (UCHAR i = 0; i < m_le.length; i++) {
		UINT uReturn = FindName (nname, m_le.lana [i], fn);
		if (uReturn == NRC_GOODRET) {
			LOG( "Found %s at %u boxes. LAN #%u IP: %u.%u.%u.%u", nname.GetANSIFullName(),
				fn.fnb_header.node_count, m_le.lana [i],
				fn.fnb_Names [0].source_addr[2],
				fn.fnb_Names [0].source_addr[3],
				fn.fnb_Names [0].source_addr[4],
				fn.fnb_Names [0].source_addr[5]);
			addr = ((ip)fn.fnb_Names [0].source_addr[5]) |
				((ip)fn.fnb_Names [0].source_addr[4] << 8) |
				((ip)fn.fnb_Names [0].source_addr[3] << 16) |
				((ip)fn.fnb_Names [0].source_addr[2] << 24);
			break;
		}
	}
	return addr;
}

void netbios::GetRegisteredNames (netbios_name_list& names)
{
	CLock oLock( m_csData );

	for (size_t i = 0; i < m_names.GetCount (); ++i)
		names.AddTail (*m_names [i]);
}

bool netbios::GetNames(netbios_name_list& names, LPCTSTR name, bool bGroup)
{
	// Ïîëó÷åíèå èìåí
	ADAPTER_STATUS_BLOCK astat = { 0 };
	netbios_name nname( name, 0, bGroup );
	UINT uReturn = NRC_GOODRET;
	for (UCHAR i = 0; i < m_le.length; i++)
	{
		uReturn = GetAdapterStatus (nname, m_le.lana [i], astat);
		if (uReturn == NRC_GOODRET)
		{
			for (int j = 0; j < astat.asb_header.name_count; ++j)
			{
				names.AddTail (netbios_name (astat.asb_Names [j], m_le.lana [i]));
			}
		}
	}
	return (uReturn == NRC_GOODRET);
}

netbios_name* netbios::GetName (const netbios_name& nname)
{
	CLock oLock( m_csData );

	netbios_name* ret = NULL;
	for (size_t i = 0; i < m_names.GetCount (); ++i)
	{
		if ( nname == *(m_names [i]) )
		{
			// Ïîõîæåå èìÿ îáíàðóæåíî
			ret = m_names [i];
			break;
		}
	}

	return ret;
}

bool netbios::FindNameLana(const netbios_name& nname, UCHAR& lana)
{
	// Ïîëó÷åíèå èìåí
	ADAPTER_STATUS_BLOCK astat = {};
	for (UCHAR i = 0; i < m_le.length; i++)
	{
		UINT uReturn = GetAdapterStatus (nname, m_le.lana [i], astat);
		if ( uReturn == NRC_GOODRET )
		{
			for ( int j = 0; j < astat.asb_header.name_count; ++j )
			{
				if (nname == astat.asb_Names [j])
				{
					// Èìÿ îáíàðóæåíî
					LOG ( "FindNameLana : Name \"%s\" found at #%d", nname.GetANSIFullName(), m_le.lana [i]);
					lana = m_le.lana [i];
					return true;
				}
			}
		}
		LOG( "FindNameLana : Name \"%s\" not found", nname.GetANSIFullName());
	}

	return false;
}

bool netbios::GetMAC (UCHAR lana, CString& mac)
{
	ADAPTER_STATUS_BLOCK astat = { 0 };
	netbios_name nname;
	UINT uReturn = GetAdapterStatus (nname, lana, astat);
	if (uReturn == NRC_GOODRET) {
		mac.Format (_T("%02x:%02x:%02x:%02x:%02x:%02x"),
			astat.asb_header.adapter_address[0],
			astat.asb_header.adapter_address[1],
			astat.asb_header.adapter_address[2],
			astat.asb_header.adapter_address[3],
			astat.asb_header.adapter_address[4],
			astat.asb_header.adapter_address[5]);
	} else
		mac.Empty ();
	return true;
}

UCHAR netbios::FindName (const netbios_name& nname, UCHAR lana, FIND_NAME_BLOCK& fn)
{
	ZeroMemory (&fn, sizeof (FIND_NAME_BLOCK));
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_command = NCBFINDNAME;
	ncb->ncb_lana_num = lana;
	CopyMemory( ncb->ncb_callname, nname.netbiosed.name, NCBNAMSZ );
	ncb->ncb_buffer = reinterpret_cast <BYTE*> (&fn);
	ncb->ncb_length = sizeof (FIND_NAME_BLOCK);
	NetbiosEx (ncb);
	return ncb->ncb_retcode;
}

UCHAR netbios::GetAdapterStatus (const netbios_name& nname, UCHAR lana, ADAPTER_STATUS_BLOCK& astat)
{
	ZeroMemory (&astat, sizeof (ADAPTER_STATUS_BLOCK));
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_command = NCBASTAT;
	ncb->ncb_lana_num = lana;
	CopyMemory( ncb->ncb_callname, nname.netbiosed.name, NCBNAMSZ );
	ncb->ncb_buffer = reinterpret_cast <BYTE*> (&astat);
	ncb->ncb_length = sizeof (ADAPTER_STATUS_BLOCK);
	NetbiosEx (ncb);
	return ncb->ncb_retcode;
}

UCHAR netbios::EnumLanas (LANA_ENUM& le)
{
	// Ïåðå÷èñëåíèå àäàïòåðîâ
	ZeroMemory (&le, sizeof (LANA_ENUM));
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_command = NCBENUM;
	ncb->ncb_buffer = (PUCHAR) &le;
	ncb->ncb_length = sizeof (LANA_ENUM);
	NetbiosEx (ncb);
	return ncb->ncb_retcode;
}

UCHAR netbios::ResetLana (UCHAR lana)
{
	// Ñáðîñ àäàïòåðà
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_command = NCBRESET;
	ncb->ncb_lana_num = lana;
	ncb->ncb_callname [0] = 20;	// maximum sessions 
	ncb->ncb_callname [2] = 30;	// maximum names 
	NetbiosEx (ncb);
	return ncb->ncb_retcode;
}

UCHAR netbios::Hangup (UCHAR lana, UCHAR lsn)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_command = NCBHANGUP;
	ncb->ncb_lana_num = lana;
	ncb->ncb_lsn = lsn;
	NetbiosEx (ncb);
	return ncb->ncb_retcode;
}

UCHAR netbios::Send (UCHAR lana, UCHAR lsn, unsigned char* data, WORD length)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_lana_num = lana;
	ncb->ncb_command = NCBSEND;
	ncb->ncb_lsn = lsn;
	ncb->ncb_length = length;
	ncb->ncb_buffer = data;
	ncb->ncb_rto = ncb->ncb_sto = (UCHAR) 10;	// 10 * 500 ms = 5 s
	NetbiosEx (ncb);
	return ncb->ncb_retcode;
}

UCHAR netbios::Recv (UCHAR lana, UCHAR lsn, unsigned char* data, WORD& length)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_command = NCBRECV;
	ncb->ncb_lana_num = lana;
	ncb->ncb_lsn = lsn;
	ncb->ncb_length = length;
	ncb->ncb_buffer = data;
	ncb->ncb_rto = ncb->ncb_sto = (UCHAR) 10;	// 10 * 500 ms = 5 s
	NetbiosEx (ncb);
	length = ncb->ncb_length;
	return ncb->ncb_retcode;
}

UCHAR netbios::Stat (const netbios_name& nname, SESSION_INFO_BLOCK* psibSession)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_command = NCBSSTAT;
	ncb->ncb_lana_num = nname.GetLana();
	ncb->ncb_buffer = (unsigned char*)psibSession;
	ncb->ncb_length = sizeof (SESSION_INFO_BLOCK);
	CopyMemory (ncb->ncb_name, nname.netbiosed.name, NCBNAMSZ);
	NetbiosEx (ncb);
	return ncb->ncb_retcode;
}

UCHAR netbios::Listen (const netbios_name& nname, UCHAR& lsn)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	CopyMemory (ncb->ncb_name, nname.netbiosed.name, NCBNAMSZ);
	CopyMemory (ncb->ncb_callname, SMB_ANY_NAME, NCBNAMSZ);
	ncb->ncb_command = NCBLISTEN;
	ncb->ncb_num = nname.netbiosed.name_num;
	ncb->ncb_lana_num = nname.GetLana();
	ncb->ncb_rto = ncb->ncb_sto = (UCHAR) 2;	// 2 * 500 ms = 1 s
	NetbiosEx (ncb);
	lsn = ncb->ncb_lsn;
	return ncb->ncb_retcode;
}

UCHAR netbios::AddName (netbios_name& nname)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_command = (UCHAR)( nname.IsGroupName() ? NCBADDGRNAME : NCBADDNAME );
	ncb->ncb_lana_num = nname.GetLana();
	CopyMemory (ncb->ncb_name, nname.netbiosed.name, NCBNAMSZ);
	NetbiosEx (ncb);
	nname.netbiosed.name_num = ncb->ncb_num;
	return ncb->ncb_retcode;
}

UCHAR netbios::DeleteName (const netbios_name& nname)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	ncb->ncb_command = NCBDELNAME;
	ncb->ncb_lana_num = nname.GetLana();
	ncb->ncb_num = nname.netbiosed.name_num;
	CopyMemory (ncb->ncb_name, nname.netbiosed.name, NCBNAMSZ);
	NetbiosEx (ncb);
	return ncb->ncb_retcode;
}

UCHAR netbios::SendDatagram (const netbios_name& nname_from, const netbios_name& nname_to, unsigned char* data, WORD length)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	CopyMemory( ncb->ncb_name, nname_from.netbiosed.name, NCBNAMSZ );
	CopyMemory( ncb->ncb_callname, nname_to.netbiosed.name, NCBNAMSZ );
	ncb->ncb_command = NCBDGSEND;
	ncb->ncb_num = nname_from.netbiosed.name_num;
	ncb->ncb_lana_num = nname_from.GetLana();
	ncb->ncb_buffer = data;
	ncb->ncb_length = length;

	CLock oLock( m_csNetBIOS );
	Sleep( 100 );

	NetbiosEx (ncb);

	return ncb->ncb_retcode;
}

UCHAR netbios::RecvDatagram (netbios_name& nname_from, const netbios_name& nname_to, unsigned char* data, WORD& length)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	CopyMemory (ncb->ncb_name, nname_to.netbiosed.name, NCBNAMSZ);
	ncb->ncb_command = NCBDGRECV;
	ncb->ncb_num = nname_to.netbiosed.name_num;
	ncb->ncb_lana_num = nname_to.GetLana();
	ncb->ncb_buffer = data;
	ncb->ncb_length = length;
	NetbiosEx (ncb);
	nname_from = ncb->ncb_callname;
	length = ncb->ncb_length;
	return ncb->ncb_retcode;
}

UCHAR netbios::Call (UCHAR lana, const netbios_name& nname_from, const netbios_name& nname_to, UCHAR& lsn)
{
	CNCB ncb;
	if ( ! ncb ) return NRC_SYSTEM;
	CopyMemory( ncb->ncb_name, nname_from.netbiosed.name, NCBNAMSZ );
	CopyMemory( ncb->ncb_callname, nname_to.netbiosed.name, NCBNAMSZ );
	ncb->ncb_lana_num = lana;
	ncb->ncb_rto = ncb->ncb_sto = 10; // 5 ñåêóíä
	ncb->ncb_command = NCBCALL;
	NetbiosEx (ncb);
	lsn = ncb->ncb_lsn;
	return ncb->ncb_retcode;
}

bool netbios::AskAway(const netbios_name& nname_to)
{
	bool ret = false;
	if ( m_initialized )
	{
		// Ñáîðêà ïàêåòà
		const WORD packet_size = sizeof( WORD ) + 1;
		if ( UCHAR* packet = (UCHAR*)mir_alloc( packet_size ) )
		{
			*(WORD*)packet = SM_MAGIC;
			packet[ 2 ] = SM_GETAWAYMESSAGE;

			for (UCHAR i = 0; i < m_le.length; i++)
			{
				if ( netbios_name* nname = GetName( netbios_name(
					pluginMachineName, 0x03, false, m_le.lana [i] ) ) )
				{
					LOG( "Send \"Ask Away\" request to \"%s\"", nname_to.GetANSIFullName() );

					if ( SendDatagram( *nname, nname_to, packet, packet_size ) == NRC_GOODRET )
					{
						ret = true;
					}
				}
			}

			mir_free( packet );
		}
	}
	return ret;
}

bool netbios::SendAway(netbios_name& nname_from, const netbios_name& nname_to)
{
	bool ret = false;
	if ( m_initialized )
	{
		CString sAwayT;
		pluginStatusMessage.Lookup( pluginCurrentStatus, sAwayT );
		CT2A sAwayA( sAwayT );
		WORD len = (WORD)min( lstrlenA( sAwayA ), 250 );

		// Ñáîðêà ïàêåòà
		WORD packet_size = (WORD)( 2 + 1 + 4 + len );
		if ( UCHAR* packet = (UCHAR*)mir_alloc( packet_size ) )
		{
			*(WORD*)packet = SM_MAGIC;
			packet [ 2 ] = SM_SENDAWAYMESSAGE;
			*(__int32*)( packet + 2 + 1 ) = 0;
			CopyMemory( packet + 2 + 1 + 4, sAwayA, len );

			LOG( "Send \"Away\" answer from \"%s\" to \"%s\" : \"%s\"", nname_from.GetANSIFullName(), nname_to.GetANSIFullName(), (LPCSTR)sAwayA );

			ret = ( SendDatagram( nname_from, nname_to, packet, packet_size ) == NRC_GOODRET );

			mir_free( packet );
		}
	}
	return ret;
}

bool netbios::AskStatus(const netbios_name& nname_to)
{
	bool ret = false;
	if ( m_initialized )
	{
		// Ñáîðêà ïàêåòà
		const WORD packet_size = 2 + 1;
		if ( UCHAR* packet = (UCHAR*)mir_alloc( packet_size ) )
		{
			*(WORD*)packet = SM_MAGIC;
			packet[ 2 ] = SM_GETSTATUS;

			for (UCHAR i = 0; i < m_le.length; i++)
			{
				if ( netbios_name* nname = GetName( netbios_name(
					pluginMachineName, 0x03, false, m_le.lana [i] ) ) )
				{
					LOG( "Send \"Ask Status\" request to \"%s\"", nname_to.GetANSIFullName() );

					if ( SendDatagram( *nname, nname_to, packet, packet_size ) == NRC_GOODRET )
					{
						ret = true;
					}
				}
			}

			mir_free( packet );
		}
	}
	return ret;
}

bool netbios::SendStatus(netbios_name& nname_from, const netbios_name& nname_to)
{
	bool ret = false;
	if ( m_initialized )
	{
		// Ñáîðêà ïàêåòà
		const WORD packet_size = 2 + 1 + 4;
		if ( UCHAR* packet = (UCHAR*)mir_alloc( packet_size ) )
		{
			*(WORD*)packet = SM_MAGIC;
			packet [ 2 ] = SM_SENDSTATUS;
			*(__int32*)( packet + 2 + 1 ) = (__int32)pluginCurrentStatus;

			LOG( "Send \"Status\" answer from \"%s\" to \"%s\" : \"%s\"", nname_from.GetANSIFullName(), nname_to.GetANSIFullName(), STATUS2TEXT(pluginCurrentStatus) );

			ret = ( SendDatagram( nname_from, nname_to, packet, packet_size ) == NRC_GOODRET );

			mir_free( packet );
		}
	}
	return ret;
}

bool netbios::BroadcastStatus()
{
	bool ret = false;
	if ( m_initialized )
	{
		for (UCHAR i = 0; i < m_le.length; i++)
		{
			netbios_name nname_to( MNS_STATUS, 0xab, true, m_le.lana [i] );
			netbios_name* nname = GetName(
				netbios_name ( pluginMachineName, 0x03, false, m_le.lana [i] ) );
			if ( nname )
				ret = SendStatus( *nname, nname_to ) || ret;
		}
	}
	return ret;
}

bool netbios::AskAvatar(const netbios_name& nname_to)
{
	bool ret = false;
	if ( m_initialized )
	{
		// Ñáîðêà ïàêåòà
		const WORD packet_size = 2 + 1;
		if ( UCHAR* packet = (UCHAR*)mir_alloc( packet_size ) )
		{
			*(WORD*)packet = SM_MAGIC;
			packet[ 2 ] = SM_GETAVATAR;

			for (UCHAR i = 0; i < m_le.length; i++)
			{
				if ( netbios_name* nname = GetName( netbios_name(
					pluginMachineName, 0x03, false, m_le.lana [i] ) ) )
				{
					LOG( "Send \"Ask Avatar\" request to \"%s\"", nname_to.GetANSIFullName() );

					if ( SendDatagram( *nname, nname_to, packet, packet_size ) == NRC_GOODRET )
					{
						ret = true;
					}
				}
			}

			mir_free( packet );
		}
	}
	return ret;
}

bool netbios::SendAvatar(netbios_name& nname_from, const netbios_name& nname_to)
{
	if ( ! m_initialized )
		return false;

	if ( ! ServiceExists( MS_AV_GETMYAVATAR ) )
		// Íåò àâàòàðñêîãî ïëàãèíà
		return false;

	// Çàïðîñ àâàòàðà ïðîòîêîëà
	AVATARCACHEENTRY* pAvatar = (AVATARCACHEENTRY*)CallService(
		MS_AV_GETMYAVATAR, 0, (LPARAM)modname );
	if ( ! pAvatar )
		// Çàïðîñ îáùåãî àâàòàðà
		pAvatar = (AVATARCACHEENTRY*)CallService( MS_AV_GETMYAVATAR, 0, (LPARAM)"" );
	if ( ! pAvatar || pAvatar->cbSize < sizeof( AVATARCACHEENTRY ) )
		// Íåò àâàòàðà
		return false;

	CString sFilename = pAvatar->szFilename;

	CAtlFile oAvatarFile;
	if ( FAILED( oAvatarFile.Create( sFilename, GENERIC_READ,
		FILE_SHARE_READ, OPEN_EXISTING ) ) )
		// Ôàéë íå íàéäåí
		return false;

	ULONGLONG avatar_size = 0;
	if ( FAILED( oAvatarFile.GetSize( avatar_size ) ) ||
		avatar_size < 16 || avatar_size > MAX_AVATAR_SIZE )
		// Ñëèøêîì ìàëåíüêèé èëè ñëèøêîì áîëüøîé ôàéë
		return false;

	bool ret = false;

	// Ñáîðêà ñòàòóñíîãî ïàêåòà
	WORD packet_size = (WORD)( 2 + 1 + avatar_size );
	if ( UCHAR* packet = (UCHAR*)mir_alloc( packet_size ) )
	{
		*(WORD*)packet = SM_MAGIC;
		packet[ 2 ] = SM_SENDAVATAR;

		// ×òåíèå àâàòàðà èç ôàéëà
		if ( SUCCEEDED( oAvatarFile.Read( packet + 2 + 1, avatar_size ) ) )
		{
			LOG( "Send \"Avatar\" answer from \"%s\" to \"%s\"", nname_from.GetANSIFullName(), nname_to.GetANSIFullName() );

			ret = ( SendDatagram( nname_from, nname_to, packet, packet_size ) == NRC_GOODRET );
		}

		mir_free( packet );
	}

	return ret;
}

bool netbios::Register ()
{
	CLock oLock( m_csData );

	bool ret = false;

	// Óäàëåíèå èì¸í, åñëè îíè åñòü
	for (size_t i = 0; i < m_names.GetCount (); ++i)
		delete m_names [i];
	m_names.RemoveAll ();

	// Äîáàâëåíèå èìåí íà êàæäîì àäàïòåðå
	for (UCHAR i = 0; i < m_le.length; i++)
	{
		// COMPUTER <01> U
		netbios_name *pnn1 =
			db_get_b (NULL, modname, "RegisterNick", TRUE) ? 
			new netbios_name ( pluginMachineName, 0x01, false, m_le.lana [i]) : NULL;
		if (pnn1)
			m_names.Add (pnn1);

		// COMPUTER <03> U
		netbios_name *pnn2 =
			db_get_b (NULL, modname, "RegisterNick", TRUE) ? 
			new netbios_name ( pluginMachineName, 0x03, false, m_le.lana [i]) : NULL;
		if (pnn2)
			m_names.Add (pnn2);

		// USER <03> U
		netbios_name *pnn3 =
			db_get_b (NULL, modname, "RegisterUser", TRUE) ? 
			new netbios_name ( pluginUserName, 0x03, false, m_le.lana [i]) : NULL;
		if (pnn3) {
			// Ïðîâåðêà íà ñîâïàäåíèå èìåíè ïîëüçîâàòåëÿ è èìåíè êîìïüþòåðà
			if (pnn2 && *pnn3 == *pnn2)
				// Èìåíà ñîâïàäàþò
				delete pnn3;
			else
				m_names.Add (pnn3);
		}

		// MNS_STATUS <AB> G
		netbios_name *pnn4 =
			db_get_b (NULL, modname, "RegisterStatus", TRUE) ? 
			new netbios_name (MNS_STATUS, 0xab, true, m_le.lana [i]) : NULL;
		if ( pnn4 )
			m_names.Add( pnn4 );
	}

	// Ðåãèñòðàöèÿ èìåí
	for ( size_t i = 0; i < m_names.GetCount (); ++i )
	{
		if ( m_names [i]->Register() )
		{
			ret = true;
		}
	}

	return ret;
}

// Äåðåãèñòðàöèÿ NetBIOS-èìåí
void netbios::Deregister ()
{
	CLock oLock( m_csData );

	// Äåðåãèñòðàöèÿ èì¸í
	for (size_t i = 0; i < m_names.GetCount (); ++i)
		m_names [i]->Destroy();

	// Óäàëåíèå èì¸í
	for (size_t i = 0; i < m_names.GetCount (); ++i)
		delete m_names [i];
	m_names.RemoveAll ();
}