-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathNetBIOSNameServer.java
More file actions
1773 lines (1408 loc) · 58.1 KB
/
NetBIOSNameServer.java
File metadata and controls
1773 lines (1408 loc) · 58.1 KB
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
/*
* Copyright (C) 2006-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.filesys.netbios.server;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;
import org.filesys.debug.Debug;
import org.filesys.netbios.NetBIOSName;
import org.filesys.netbios.NetBIOSNameList;
import org.filesys.netbios.NetBIOSPacket;
import org.filesys.netbios.NetworkSettings;
import org.filesys.netbios.RFCNetBIOSProtocol;
import org.filesys.server.NetworkServer;
import org.filesys.server.ServerListener;
import org.filesys.server.Version;
import org.filesys.server.config.ConfigId;
import org.filesys.server.config.ConfigurationListener;
import org.filesys.server.config.InvalidConfigurationException;
import org.filesys.server.config.ServerConfiguration;
import org.filesys.smb.server.SMBConfigSection;
import org.filesys.util.HexDump;
import org.filesys.util.StringList;
/**
* NetBIOS name server class.
*
* @author gkspencer
*/
public class NetBIOSNameServer extends NetworkServer implements Runnable, ConfigurationListener {
// Server version
private static final String ServerVersion = Version.NetBIOSServerVersion;
// Various NetBIOS packet sizes
public static final int AddNameSize = 256;
public static final int DeleteNameSize = 256;
public static final int RefreshNameSize = 256;
// Add name thread broadcast interval and retry count
private static final int AddNameInterval = 2000; // ms between transmits
private static final int AddNameRetries = 5; // number of broadcasts
private static final int AddNameWINSInterval = 250; // ms between requests when using WINS
// Delete name interval and retry count
private static final int DeleteNameInterval = 200; // ms between transmits
private static final int DeleteNameRetries = 1; // number of broadcasts
// Refresh name retry count
public static final int RefreshNameRetries = 2; // number of broadcasts
// NetBIOS flags
public static final int GroupName = 0x8000;
// Default time to live value for names registered by this server, in seconds
public static final int DefaultTTL = 10800; // 3 hours
// Name refresh thread wakeup interval
public static final long NameRefreshWakeupInterval = 180000L; // 3 minutes
// SMB server configuration section
private SMBConfigSection m_smbConfig;
// Name transaction id
private static int m_tranId;
// NetBIOS name service datagram socket
private DatagramSocket m_socket;
// Shutdown flag
private boolean m_shutdown;
// Local address to bind the name server to
private InetAddress m_bindAddress;
// Broadcast address, if not using WINS
private InetAddress m_bcastAddr;
// Port/socket to bind to
private int m_port = RFCNetBIOSProtocol.NAMING;
// WINS server addresses
private InetAddress m_winsPrimary;
private InetAddress m_winsSecondary;
// Local add name listener list
private List<AddNameListener> m_addListeners;
// Local name query listener list
private List<QueryNameListener> m_queryListeners;
// Remote name add listener list
private List<RemoteNameListener> m_remoteListeners;
// Local NetBIOS name table
private List<NetBIOSName> m_localNames;
// Remote NetBIOS name table
private Hashtable<NetBIOSName, byte[]> m_remoteNames;
// List of active add name requests
private List<NetBIOSRequest> m_reqList;
// NetBIOS request handler and name refresh threads
private NetBIOSRequestHandler m_reqHandler;
private NetBIOSNameRefresh m_refreshThread;
// Server thread
private Thread m_srvThread;
// NetBIOS request handler thread inner class
class NetBIOSRequestHandler extends Thread {
// Shutdown request flag
private boolean m_hshutdown = false;
/**
* Default constructor
*/
public NetBIOSRequestHandler() {
setDaemon(true);
setName("NetBIOSRequest");
}
/**
* Shutdown the request handler thread
*/
public final void shutdownRequest() {
m_hshutdown = true;
synchronized (m_reqList) {
m_reqList.notify();
}
}
/**
* Main thread code
*/
public void run() {
// Loop until shutdown requested
while (m_hshutdown == false) {
try {
// Wait for something to do
NetBIOSRequest req = null;
synchronized (m_reqList) {
// Check if there are any requests in the queue
if (m_reqList.size() == 0) {
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println("NetBIOS handler waiting for request ...");
// Wait for some work ...
m_reqList.wait();
}
// Remove a request from the queue
if (m_reqList.size() > 0)
req = m_reqList.get(0);
else if (m_hshutdown == true)
break;
}
// Get the request retry count, for WINS only send one request
int reqRetry = req.getRetryCount();
if (hasPrimaryWINSServer())
reqRetry = 1;
// Process the request
boolean txsts = true;
int retry = 0;
while (req.hasErrorStatus() == false && retry++ < reqRetry) {
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println("NetBIOS handler, processing " + req);
// Process the request
switch (req.isType()) {
// Add name request
case ADD_NAME:
// Check if a WINS server is configured
if (hasPrimaryWINSServer())
txsts = sendAddName(req, getPrimaryWINSServer(), false);
else
txsts = sendAddName(req, getBroadcastAddress(), true);
break;
// Delete name request
case DELETE_NAME:
// Check if a WINS server is configured
if (hasPrimaryWINSServer())
txsts = sendDeleteName(req, getPrimaryWINSServer(), false);
else
txsts = sendDeleteName(req, getBroadcastAddress(), true);
break;
// Refresh name request
case REFRESH_NAME:
// Check if a WINS server is configured
if (hasPrimaryWINSServer())
txsts = sendRefreshName(req, getPrimaryWINSServer(), false);
else
txsts = sendRefreshName(req, getBroadcastAddress(), true);
break;
}
// Check if the request was successful
if (txsts == true && req.getRetryInterval() > 0) {
// Sleep for a while
sleep(req.getRetryInterval());
}
}
// Check if the request was successful
if (req.hasErrorStatus() == false) {
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println("NetBIOS handler successful, " + req);
// Update the name record
NetBIOSName nbName = req.getNetBIOSName();
switch (req.isType()) {
// Add name request
case ADD_NAME:
// Add the name to the list of local names
if (m_localNames.contains(nbName) == false)
m_localNames.add(nbName);
// Update the expiry time for the name
nbName.setExpiryTime(System.currentTimeMillis() + (nbName.getTimeToLive() * 1000L));
// Inform listeners that the request was successful
fireAddNameEvent(nbName, NetBIOSNameEvent.Status.ADD_SUCCESS);
break;
// Delete name request
case DELETE_NAME:
// Remove the name from the list of local names
m_localNames.remove(req.getNetBIOSName());
break;
// Refresh name registration request
case REFRESH_NAME:
// Update the expiry time for the name
nbName.setExpiryTime(System.currentTimeMillis() + (nbName.getTimeToLive() * 1000L));
break;
}
} else {
// Error occurred
switch (req.isType()) {
// Add name request
case ADD_NAME:
// Remove the name from the local name list
m_localNames.remove(req.getNetBIOSName());
break;
}
}
// Remove the request from the queue
synchronized (m_reqList) {
m_reqList.remove(0);
}
}
catch (InterruptedException ex) {
}
// Check if the request handler has been shutdown
if (m_hshutdown == true)
break;
}
}
/**
* Send an add name request
*
* @param req NetBIOSRequest
* @param dest InetAddress
* @param bcast boolean
* @return boolean
*/
private final boolean sendAddName(NetBIOSRequest req, InetAddress dest, boolean bcast) {
try {
// Allocate a buffer for the add name NetBIOS packet
byte[] buf = new byte[AddNameSize];
NetBIOSPacket addPkt = new NetBIOSPacket(buf);
// Build an add name packet for each IP address
for (int i = 0; i < req.getNetBIOSName().numberOfAddresses(); i++) {
// Build an add name request for the current IP address
int len = addPkt.buildAddNameRequest(req.getNetBIOSName(), i, req.getTransactionId());
if (bcast == false)
addPkt.setFlags(0);
// Allocate the datagram packet, using the add name buffer
DatagramPacket pkt = new DatagramPacket(buf, len, dest, getPort());
// Send the add name request
if (m_socket != null)
m_socket.send(pkt);
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println(" Add name " + (bcast ? "broadcast" : "WINS") + ", " + req);
}
}
catch (IOException ex) {
fireAddNameEvent(req.getNetBIOSName(), NetBIOSNameEvent.Status.ADD_IOERROR);
req.setErrorStatus(true);
return false;
}
// Add name broadcast successful
return true;
}
/**
* Send a refresh name request
*
* @param req NetBIOSRequest
* @param dest InetAddress
* @param bcast boolean
* @return boolean
*/
private final boolean sendRefreshName(NetBIOSRequest req, InetAddress dest, boolean bcast) {
try {
// Allocate a buffer for the refresh name NetBIOS packet
byte[] buf = new byte[RefreshNameSize];
NetBIOSPacket refreshPkt = new NetBIOSPacket(buf);
// Build a refresh name packet for each IP address
for (int i = 0; i < req.getNetBIOSName().numberOfAddresses(); i++) {
// Build a refresh name request for the current IP address
int len = refreshPkt.buildRefreshNameRequest(req.getNetBIOSName(), i, req.getTransactionId());
if (bcast == false)
refreshPkt.setFlags(0);
// Allocate the datagram packet, using the refresh name buffer
DatagramPacket pkt = new DatagramPacket(buf, len, dest, getPort());
// Send the refresh name request
if (m_socket != null)
m_socket.send(pkt);
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println(" Refresh name " + (bcast ? "broadcast" : "WINS") + ", " + req);
}
}
catch (IOException ex) {
req.setErrorStatus(true);
return false;
}
// Add name broadcast successful
return true;
}
/**
* Send a delete name request via a network broadcast
*
* @param req NetBIOSRequest
* @param dest InetAddress
* @param bcast boolean
* @return boolean
*/
private final boolean sendDeleteName(NetBIOSRequest req, InetAddress dest, boolean bcast) {
try {
// Allocate a buffer for the delete name NetBIOS packet
byte[] buf = new byte[DeleteNameSize];
NetBIOSPacket delPkt = new NetBIOSPacket(buf);
// Build a delete name packet for each IP address
for (int i = 0; i < req.getNetBIOSName().numberOfAddresses(); i++) {
// Build an add name request for the current IP address
int len = delPkt.buildDeleteNameRequest(req.getNetBIOSName(), i, req.getTransactionId());
if (bcast == false)
delPkt.setFlags(0);
// Allocate the datagram packet, using the add name buffer
DatagramPacket pkt = new DatagramPacket(buf, len, dest, getPort());
// Send the add name request
if (m_socket != null)
m_socket.send(pkt);
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println(" Delete name " + (bcast ? "broadcast" : "WINS") + ", " + req);
}
}
catch (IOException ex) {
req.setErrorStatus(true);
return false;
}
// Delete name broadcast successful
return true;
}
}
;
// NetBIOS name refresh thread inner class
class NetBIOSNameRefresh extends Thread {
// Shutdown request flag
private boolean m_hshutdown = false;
/**
* Default constructor
*/
public NetBIOSNameRefresh() {
setDaemon(true);
setName("NetBIOSRefresh");
}
/**
* Shutdown the name refresh thread
*/
public final void shutdownRequest() {
m_hshutdown = true;
// Wakeup the thread
this.interrupt();
}
/**
* Main thread code
*/
public void run() {
// Loop for ever
while (m_hshutdown == false) {
try {
// Sleep for a while
sleep(NameRefreshWakeupInterval);
// Check if there is a shutdown pending
if (m_hshutdown == true)
break;
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println("NetBIOS name refresh wakeup ...");
// Check if there are any registered names that will expire in the next interval
synchronized (m_localNames) {
// Get the current time plus the wakeup interval
long expireTime = System.currentTimeMillis() + NameRefreshWakeupInterval;
// Loop through the local name list
for (int i = 0; i < m_localNames.size(); i++) {
// Get a name from the list
NetBIOSName nbName = (NetBIOSName) m_localNames.get(i);
// Check if the name has expired, or will expire before the next wakeup event
if (nbName.getExpiryTime() < expireTime) {
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println("Queuing name refresh for " + nbName);
// Queue a refresh request for the NetBIOS name
NetBIOSRequest nbReq = new NetBIOSRequest(NetBIOSRequest.Type.REFRESH_NAME, nbName, getNextTransactionId());
nbReq.setRetryCount(RefreshNameRetries);
// Queue the request
synchronized (m_reqList) {
// Add the request to the list
m_reqList.add(nbReq);
// Wakeup the processing thread
m_reqList.notify();
}
}
}
}
}
catch (Exception ex) {
// Debug
if (Debug.EnableError && hasDebug()) {
Debug.println("NetBIOS Name refresh thread exception");
Debug.println(ex);
}
}
}
}
}
;
/**
* Default constructor
*
* @param config ServerConfiguration
* @throws SocketException If a network setup error occurs
*/
public NetBIOSNameServer(ServerConfiguration config)
throws SocketException {
super("NetBIOS", config);
// Perform common constructor code
commonConstructor();
}
/**
* Common constructor code
*
* @throws SocketException If a network setup error occurs
*/
private final void commonConstructor()
throws SocketException {
// Add the NetBIOS name server as a configuration change listener of the server configuration
getConfiguration().addListener(this);
// Set the server version
setVersion(ServerVersion);
// Find the SMB server configuration
m_smbConfig = (SMBConfigSection) getConfiguration().getConfigSection(SMBConfigSection.SectionName);
if (m_smbConfig != null) {
// Allocate the local and remote name tables
m_localNames = new ArrayList<NetBIOSName>();
m_remoteNames = new Hashtable<NetBIOSName, byte[]>();
// Check if NetBIOS name server debug output is enabled
if (getSMBConfiguration().hasNetBIOSDebug())
setDebug(true);
// Set the local address to bind the server to, and server port
setBindAddress(getSMBConfiguration().getNetBIOSBindAddress());
setServerPort(getSMBConfiguration().getNameServerPort());
// Copy the WINS server addresses, if set
setPrimaryWINSServer(getSMBConfiguration().getPrimaryWINSServer());
setSecondaryWINSServer(getSMBConfiguration().getSecondaryWINSServer());
// Check if WINS is not enabled, use broadcasts instead
if (hasPrimaryWINSServer() == false) {
try {
m_bcastAddr = InetAddress.getByName(getSMBConfiguration().getBroadcastMask());
}
catch (Exception ex) {
}
}
} else
setEnabled(false);
}
/**
* Return the local address the server binds to, or null if all local addresses
* are used.
*
* @return java.net.InetAddress
*/
public final InetAddress getBindAddress() {
return m_bindAddress;
}
/**
* Return the next available transaction id for outgoing NetBIOS packets.
*
* @return int
*/
protected final synchronized int getNextTransactionId() {
return m_tranId++;
}
/**
* Return the port/socket that the server is bound to.
*
* @return int
*/
public final int getPort() {
return m_port;
}
/**
* Determine if the server binds to a particulat local address, or all addresses
*
* @return boolean
*/
public final boolean hasBindAddress() {
return m_bindAddress != null ? true : false;
}
/**
* Return the SMB server configuration
*
* @return SMBConfigSection
*/
private final SMBConfigSection getSMBConfiguration() {
return m_smbConfig;
}
/**
* Return the remote name table
*
* @return Hashtable
*/
public final Hashtable getNameTable() {
return m_remoteNames;
}
/**
* Return the broadcast address, if WINS is disabled
*
* @return InetAddress
*/
public final InetAddress getBroadcastAddress() {
return m_bcastAddr;
}
/**
* Determine if the primary WINS server address has been set
*
* @return boolean
*/
public final boolean hasPrimaryWINSServer() {
return m_winsPrimary != null ? true : false;
}
/**
* Return the primary WINS server address
*
* @return InetAddress
*/
public final InetAddress getPrimaryWINSServer() {
return m_winsPrimary;
}
/**
* Determine if the secondary WINS server address has been set
*
* @return boolean
*/
public final boolean hasSecondaryWINSServer() {
return m_winsSecondary != null ? true : false;
}
/**
* Return the secondary WINS server address
*
* @return InetAddress
*/
public final InetAddress getSecondaryWINSServer() {
return m_winsSecondary;
}
/**
* Add a NetBIOS name.
*
* @param name NetBIOS name to be added
* @throws java.io.IOException I/O error occurred.
*/
public final synchronized void AddName(NetBIOSName name)
throws IOException {
// Check if the NetBIOS name socket has been initialized
if (m_socket == null)
throw new IOException("NetBIOS name socket not initialized");
// Create an add name request and add to the request list
NetBIOSRequest nbReq = new NetBIOSRequest(NetBIOSRequest.Type.ADD_NAME, name, getNextTransactionId());
// Set the retry interval
if (hasPrimaryWINSServer())
nbReq.setRetryInterval(AddNameWINSInterval);
else
nbReq.setRetryInterval(AddNameInterval);
// Add the name to the local name list
m_localNames.add(name);
// Queue the request
synchronized (m_reqList) {
// Add the request to the list
m_reqList.add(nbReq);
// Wakeup the processing thread
m_reqList.notify();
}
}
/**
* Delete a NetBIOS name.
*
* @param name NetBIOS name to be deleted
* @throws java.io.IOException I/O error occurred.
*/
public final synchronized void DeleteName(NetBIOSName name)
throws IOException {
// Check if the NetBIOS name socket has been initialized
if (m_socket == null)
throw new IOException("NetBIOS name socket not initialized");
// Create a delete name request and add to the request list
NetBIOSRequest nbReq = new NetBIOSRequest(NetBIOSRequest.Type.DELETE_NAME, name, getNextTransactionId(), DeleteNameRetries);
nbReq.setRetryInterval(DeleteNameInterval);
synchronized (m_reqList) {
// Add the request to the list
m_reqList.add(nbReq);
// Wakeup the processing thread
m_reqList.notify();
}
}
/**
* Add a local add name listener to the NetBIOS name server.
*
* @param l AddNameListener
*/
public final synchronized void addAddNameListener(AddNameListener l) {
// Check if the add name listener list is allocated
if (m_addListeners == null)
m_addListeners = new ArrayList<AddNameListener>();
m_addListeners.add(l);
}
/**
* Add a query name listener to the NetBIOS name server.
*
* @param l QueryNameListener
*/
public final synchronized void addQueryListener(QueryNameListener l) {
// Check if the query name listener list is allocated
if (m_queryListeners == null)
m_queryListeners = new ArrayList<QueryNameListener>();
m_queryListeners.add(l);
}
/**
* Add a remote name listener to the NetBIOS name server.
*
* @param l RemoteNameListener
*/
public final synchronized void addRemoteListener(RemoteNameListener l) {
// Check if the remote name listener list is allocated
if (m_remoteListeners == null)
m_remoteListeners = new ArrayList<RemoteNameListener>();
m_remoteListeners.add(l);
}
/**
* Trigger an add name event to all registered listeners.
*
* @param name NetBIOSName
* @param sts NetBIOSNameEvent.Status
*/
protected final synchronized void fireAddNameEvent(NetBIOSName name, NetBIOSNameEvent.Status sts) {
// Check if there are any listeners
if (m_addListeners == null || m_addListeners.size() == 0)
return;
// Create a NetBIOS name event
NetBIOSNameEvent evt = new NetBIOSNameEvent(name, sts);
// Inform all registered listeners
for (int i = 0; i < m_addListeners.size(); i++) {
AddNameListener addListener = m_addListeners.get(i);
addListener.netbiosNameAdded(evt);
}
}
/**
* Trigger an query name event to all registered listeners.
*
* @param name NetBIOSName
* @param addr InetAddress
*/
protected final synchronized void fireQueryNameEvent(NetBIOSName name, InetAddress addr) {
// Check if there are any listeners
if (m_queryListeners == null || m_queryListeners.size() == 0)
return;
// Create a NetBIOS name event
NetBIOSNameEvent evt = new NetBIOSNameEvent(name, NetBIOSNameEvent.Status.QUERY_NAME);
// Inform all registered listeners
for (int i = 0; i < m_queryListeners.size(); i++) {
QueryNameListener queryListener = m_queryListeners.get(i);
queryListener.netbiosNameQuery(evt, addr);
}
}
/**
* Trigger a name register event to all registered listeners.
*
* @param name NetBIOSName
* @param addr InetAddress
*/
protected final synchronized void fireNameRegisterEvent(NetBIOSName name, InetAddress addr) {
// Check if there are any listeners
if (m_remoteListeners == null || m_remoteListeners.size() == 0)
return;
// Create a NetBIOS name event
NetBIOSNameEvent evt = new NetBIOSNameEvent(name, NetBIOSNameEvent.Status.REGISTER_NAME);
// Inform all registered listeners
for (int i = 0; i < m_remoteListeners.size(); i++) {
RemoteNameListener nameListener = m_remoteListeners.get(i);
nameListener.netbiosAddRemoteName(evt, addr);
}
}
/**
* Trigger a name release event to all registered listeners.
*
* @param name NetBIOSName
* @param addr InetAddress
*/
protected final synchronized void fireNameReleaseEvent(NetBIOSName name, InetAddress addr) {
// Check if there are any listeners
if (m_remoteListeners == null || m_remoteListeners.size() == 0)
return;
// Create a NetBIOS name event
NetBIOSNameEvent evt = new NetBIOSNameEvent(name, NetBIOSNameEvent.Status.REGISTER_NAME);
// Inform all registered listeners
for (int i = 0; i < m_remoteListeners.size(); i++) {
RemoteNameListener nameListener = m_remoteListeners.get(i);
nameListener.netbiosReleaseRemoteName(evt, addr);
}
}
/**
* Open the server socket
*
* @exception SocketException Socket error
*/
private void openSocket()
throws java.net.SocketException {
// Check if the server should bind to a particular local address, or all addresses
if (hasBindAddress())
m_socket = new DatagramSocket(getPort(), m_bindAddress);
else
m_socket = new DatagramSocket(getPort());
}
/**
* Process a NetBIOS name query.
*
* @param pkt NetBIOSPacket
* @param fromAddr InetAddress
* @param fromPort int
*/
protected final void processNameQuery(NetBIOSPacket pkt, InetAddress fromAddr, int fromPort) {
// Check that the name query packet is valid
if (pkt.getQuestionCount() != 1)
return;
// Get the name that is being queried
String searchName = pkt.getQuestionName();
char nameType = searchName.charAt(15);
int len = 0;
while (len <= 14 && searchName.charAt(len) != ' ' && searchName.charAt(len) != 0)
len++;
searchName = searchName.substring(0, len);
// Check if this is an adapter status request
if (searchName.equals(NetBIOSName.AdapterStatusName)) {
// Process the adapter status request
processAdapterStatus(pkt, fromAddr, fromPort);
return;
}
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println("%% Query name=" + searchName + ", type=" + NetBIOSName.TypeAsString(nameType) + ", len=" + len);
// Search for the name in the local name table
Iterator<NetBIOSName> enm = m_localNames.iterator();
NetBIOSName nbName = null;
boolean foundName = false;
while (enm.hasNext() && foundName == false) {
// Get the current NetBIOS name item from the local name table
nbName = enm.next();
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println("NetBIOS Name - " + nbName.getName() + ", len=" + nbName.getName().length() + ",type=" + NetBIOSName.TypeAsString(nbName.getType()));
// Check if the name matches the query name
if (nbName.getType() == nameType && nbName.getName().compareTo(searchName) == 0)
foundName = true;
}
// Check if we found a matching name
if (foundName == true) {
// Debug
if (Debug.EnableInfo && hasDebug())
Debug.println("%% Found name " + searchName + " in local name table : " + nbName.toString());
// Build the name query response
int pktLen = pkt.buildNameQueryResponse(nbName);
// Debug
if (Debug.EnableInfo && hasDebug()) {
Debug.println("%% NetBIOS Reply to " + fromAddr.getHostAddress() + " :-");
pkt.DumpPacket(false);
}
// Send the reply packet
try {
// Send the name query reply
sendPacket(pkt, pktLen, fromAddr, fromPort);
}
catch (java.io.IOException ex) {
Debug.println(ex);
}
// Inform listeners of the name query
fireQueryNameEvent(nbName, fromAddr);
} else {