-
Notifications
You must be signed in to change notification settings - Fork 0
/
Proxy.java
3176 lines (2683 loc) · 123 KB
/
Proxy.java
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
/**
* This file is part of OpenJSIP, a free SIP service components.
*
* OpenJSIP 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
*
* OpenJSIP 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
*
* Copyright (c) 2009 - Yevgen Krapiva
*/
package openjsip.proxy;
import gov.nist.javax.sip.message.SIPResponse;
import gov.nist.javax.sip.stack.SIPServerTransaction;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Properties;
import java.util.Scanner;
import java.util.Timer;
import java.util.TooManyListenersException;
import java.util.Vector;
import javax.sip.ClientTransaction;
import javax.sip.DialogTerminatedEvent;
import javax.sip.IOExceptionEvent;
import javax.sip.InvalidArgumentException;
import javax.sip.ListeningPoint;
import javax.sip.ObjectInUseException;
import javax.sip.PeerUnavailableException;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.ServerTransaction;
import javax.sip.SipException;
import javax.sip.SipFactory;
import javax.sip.SipListener;
import javax.sip.SipProvider;
import javax.sip.SipStack;
import javax.sip.TimeoutEvent;
import javax.sip.TransactionAlreadyExistsException;
import javax.sip.TransactionState;
import javax.sip.TransactionTerminatedEvent;
import javax.sip.TransactionUnavailableException;
import javax.sip.TransportNotSupportedException;
import javax.sip.address.Address;
import javax.sip.address.AddressFactory;
import javax.sip.address.SipURI;
import javax.sip.address.URI;
import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.ContentLengthHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.HeaderFactory;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.ProxyAuthenticateHeader;
import javax.sip.header.ProxyAuthorizationHeader;
import javax.sip.header.ProxyRequireHeader;
import javax.sip.header.RecordRouteHeader;
import javax.sip.header.RouteHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.UnsupportedHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.MessageFactory;
import javax.sip.message.Request;
import javax.sip.message.Response;
import openjsip.SipUtils;
import openjsip.auth.DigestServerAuthenticationMethod;
import openjsip.proxy.plugins.MethodPlugin;
import openjsip.proxy.plugins.MethodPluginException;
import openjsip.remote.RemoteServiceInterface;
import openjsip.remote.locationservice.LocationServiceInterface;
import openjsip.remote.locationservice.UserNotFoundException;
import openjsip.snmp.SNMPAssistant;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import org.apache.log4j.PropertyConfigurator;
import snmp.SNMPCounter32;
import snmp.SNMPGauge32;
import snmp.SNMPv1AgentInterface;
public class Proxy extends UnicastRemoteObject implements SipListener, RemoteServiceInterface, Runnable
{
/**
* BEQOS FUNCTIONS ACTIVATION
*/
private static boolean BEQOS = true;
/**
* Logger
*/
private static Logger log = Logger.getLogger(Proxy.class);
/**
* Main SIP stack
*/
private SipStack sipStack;
/**
* Factory that constructs address fields
*/
private AddressFactory addressFactory;
/**
* Factory that constructs headers
*/
private HeaderFactory headerFactory;
/**
* Factory that constructs entire SIP messages
*/
private MessageFactory messageFactory;
/**
* Set of responsible domains
*/
private final HashSet<String> domains = new HashSet<String>();
/**
* Method plugins, such as REGISTER
*/
private final Hashtable<String, MethodPlugin> methodPlugins = new Hashtable<String, MethodPlugin>();
/**
* SipProvider to ip address mapping
* SipProvider is an interface, and Address is its IP address
*/
private final Hashtable<SipProvider, String> providerToAddressMapping = new Hashtable<SipProvider, String>();
/**
* SipProvider to hostname mapping
* SipProvider is an interface, and Hostname is its FQDN ( Fully qualified domain name )
*/
private final Hashtable<SipProvider, String> providerToHostnameMapping = new Hashtable<SipProvider, String>();
/**
* Location service connection variables
*/
private String locationServiceName;
private String locationServiceHost;
private int locationServicePort = 1099;
/**
* See RFC3261 for Timer C details
*/
private int timercPeriod = 3 * 60 * 1000 + 1000;
/**
* Authenticate subscribers ?
*/
private boolean authenticationEnabled;
/**
* Digest authentication class
*/
private DigestServerAuthenticationMethod dsam;
/**
* Operation mode
*/
public static final int STATEFULL_MODE = 0;
public static final int STATELESS_MODE = 1;
/**
* Not implemented yet
*/
private final int operationMode;
/**
* RMI binding name
*/
private static String RMIBindName;
/**
* SNMP package used here is experimental and is likely to be
* substituted by SNMP4JAgent in future. Due to lack of good documentation
* on SNMP4J it cannot be done for now.
*/
/**
* SNMP agent engine
*/
private SNMPv1AgentInterface agentInterface;
/**
* Additional class to ease the work with SNMP.
*/
private SNMPAssistant snmpAssistant;
/**
* SNMP root oid. This is where all our objects reside.
* The current value corresponds to .iso.org.dod.internet.private.enterprises.
* 1937 is our random generated value for (OpenJSIP), but normally this number is to be
* given by IANA.
* The next value correspond to:
* 1 - OpenJSIP Location service
* 2 - OpenJSIP Registrar service
* 3 - OpenJSIP Proxy service
*/
protected static final String SNMP_ROOT_OID = "1.3.6.1.4.1.1937.3.";
protected static final String SNMP_OID_NUM_REQUESTS_PROCESSED = SNMP_ROOT_OID + "1.1";
protected static final String SNMP_OID_NUM_RESPONSES_PROCESSED = SNMP_ROOT_OID + "1.2";
protected static final String SNMP_OID_NUM_REQUEST_PROCESSING_ERRORS = SNMP_ROOT_OID + "1.3";
protected static final String SNMP_OID_NUM_RESPONSE_PROCESSING_ERRORS = SNMP_ROOT_OID + "1.4";
protected static final String SNMP_OID_NUM_SERVER_TRANSACTIONS = SNMP_ROOT_OID + "1.5";
protected static final String SNMP_OID_NUM_CLIENT_TRANSACTIONS = SNMP_ROOT_OID + "1.6";
/**
* SNMP database with default values.
*/
private static final Object SNMP_DATABASE[][] = new Object[][]
{
{ SNMP_OID_NUM_REQUESTS_PROCESSED, new SNMPCounter32(0) },
{ SNMP_OID_NUM_RESPONSES_PROCESSED, new SNMPCounter32(0) },
{ SNMP_OID_NUM_REQUEST_PROCESSING_ERRORS, new SNMPCounter32(0) },
{ SNMP_OID_NUM_RESPONSE_PROCESSING_ERRORS, new SNMPCounter32(0) },
{ SNMP_OID_NUM_SERVER_TRANSACTIONS, new SNMPGauge32(0) },
{ SNMP_OID_NUM_CLIENT_TRANSACTIONS, new SNMPGauge32(0) },
};
/**
* Entry point
*
* @param args command line arguments
*/
public static void main(String[] args)
{
Properties props = null;
if (args.length < 1)
{
printUsage();
System.exit(0);
}
try
{
if (!new File(args[0]).exists())
{
System.err.println("Error: Cannot open configuration file " + args[0]);
System.exit(1);
}
// Reading configuration data
props = new Properties();
props.load(new FileInputStream(args[0]));
String externalLoggingConf = props.getProperty("logging.properties");
if (externalLoggingConf != null)
PropertyConfigurator.configure(externalLoggingConf.trim());
else
PropertyConfigurator.configure(props);
}
catch(IOException e)
{
System.err.println("Error: Cannot open configuration file "+args[0]);
System.exit(1);
}
RemoteServiceInterface proxy = null;
try
{
// Start proxy
proxy = new Proxy(props);
}
catch (Exception ex)
{
log.error(ex.getMessage());
if (log.isTraceEnabled())
log.trace("", ex);
System.exit(1);
}
String name = props.getProperty("proxy.service.rmi.objectname", "Proxy").trim();
String host = props.getProperty("proxy.service.rmi.host", "localhost").trim();
int port = 1099;
try
{
port = Integer.parseInt(props.getProperty("proxy.rmi.port", "1099").trim());
}
catch(NumberFormatException ex)
{
// ignored
}
RMIBindName = "rmi://" + host + ":" + port + "/" + name;
try
{
Naming.rebind(RMIBindName, proxy);
}
catch(RemoteException ex)
{
log.error("Cannot register within RMI registry at "+host+":"+port, ex);
System.exit(1);
}
catch(MalformedURLException ex)
{
log.error("Cannot register within RMI registry at "+host+":"+port, ex);
System.exit(1);
}
if (log.isInfoEnabled())
log.info("Proxy registered as \""+name+"\" within RMI registry at "+host+":"+port);
if (log.isInfoEnabled())
log.info("Proxy started...");
}
/**
* Prints help on how to launch this program
*/
private static void printUsage()
{
System.out.println("\nUsage: Proxy <proxy.properties file>\n" +
"where proxy.properties is the path to .properties file with settings for Proxy server.");
}
/**
* Proxy constructor
* @param props Proxy server configuration
* @throws PeerUnavailableException
* @throws ObjectInUseException
* @throws TooManyListenersException
* @throws TransportNotSupportedException
* @throws InvalidArgumentException
*/
private Proxy(Properties props) throws PeerUnavailableException, ObjectInUseException, TooManyListenersException,
TransportNotSupportedException, InvalidArgumentException, RemoteException
{
if (log.isInfoEnabled())
log.info("Starting Proxy v" + SipUtils.OPENJSIP_VERSION + "...");
// Set security manager
if (System.getSecurityManager() == null)
System.setSecurityManager(new SecurityManager());
SipFactory sipFactory = SipFactory.getInstance();
sipFactory.setPathName("gov.nist");
props.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "off");
sipStack = sipFactory.createSipStack(props);
headerFactory = sipFactory.createHeaderFactory();
addressFactory = sipFactory.createAddressFactory();
messageFactory = sipFactory.createMessageFactory();
if (log.isInfoEnabled())
log.info("Configuring interfaces...");
try
{
// If there are no configured interfaces
if (props.getProperty("proxy.interface.1.addr") == null)
{
int index = 1;
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
while(nets.hasMoreElements())
{
NetworkInterface netInt = nets.nextElement();
Enumeration<InetAddress> inetAdresses = netInt.getInetAddresses();
while (inetAdresses.hasMoreElements())
{
InetAddress inetAddress = inetAdresses.nextElement();
props.setProperty("proxy.interface."+index+".addr", inetAddress.getHostAddress());
index++;
}
}
}
}
catch (SocketException e)
{
}
int index = 1;
String proxyHost = null;
while ((proxyHost = props.getProperty("proxy.interface."+index+".addr")) != null)
{
proxyHost = proxyHost.trim();
try
{
if (log.isTraceEnabled())
log.trace("Configuring interface #"+index+": "+proxyHost);
// Get IP address of interface
InetAddress inetAddress = InetAddress.getByName(proxyHost);
// Get desired port
String proxyPortStr = props.getProperty("proxy.interface."+index+".port");
if (proxyPortStr != null) proxyPortStr = proxyPortStr.trim();
int proxyPort = 5060;
try
{
proxyPort = Integer.parseInt(proxyPortStr);
}
catch (NumberFormatException e)
{
}
// Get list of transports
String[] transports = props.getProperty("proxy.interface."+index+".transport", "udp, tcp").split(",");
// SipProvider represents an interface
SipProvider sipProvider = null;
// Transport is represented by ListeningPoint
for (int i=0; i<transports.length; i++)
{
transports[i] = transports[i].trim();
try
{
if (log.isTraceEnabled())
log.trace("Creating ListeningPoint for " + inetAddress.getHostAddress() + ":" + proxyPort + " " + transports[i]);
// Try to create ListeningPoint for each transport
ListeningPoint lp = sipStack.createListeningPoint(inetAddress.getHostAddress(), proxyPort, transports[i]);
if (sipProvider == null)
{
if (log.isTraceEnabled())
log.trace("Creating new SipProvider.");
sipProvider = sipStack.createSipProvider(lp);
}
else
{
if (log.isTraceEnabled())
log.trace("Adding ListeningPoint to SipProvider.");
sipProvider.addListeningPoint(lp);
}
}
catch (Exception ex)
{
log.warn("Failed to create listening point " + inetAddress.getHostAddress() + ":" + proxyPort + " " + transports[i] +" ( "+ex.getMessage()+" )");
if (log.isTraceEnabled())
log.trace("", ex);
}
}
// If interface has any ListeningPoints
if (sipProvider != null && sipProvider.getListeningPoints().length > 0)
{
providerToAddressMapping.put(sipProvider, inetAddress.getHostAddress());
providerToHostnameMapping.put(sipProvider, inetAddress.getCanonicalHostName());
sipProvider.addSipListener(this);
}
}
catch (UnknownHostException ex)
{
log.warn("Interface #"+index+": "+ex.getMessage());
}
finally
{
index++;
}
}
if (providerToHostnameMapping.size() == 0)
{
log.error("There are no properly configured interfaces. Proxy cannot be started.");
System.exit(1);
}
// Print configuration info
Iterator sipProviders = sipStack.getSipProviders();
index = 1;
while (sipProviders.hasNext())
{
SipProvider sipProvider = (SipProvider) sipProviders.next();
ListeningPoint[] lps = sipProvider.getListeningPoints();
StringBuffer sb = new StringBuffer();
sb.append("Interface #" + index + ": " + getHostname(sipProvider) + " (");
for (int i=0; i<lps.length; i++)
{
if (i == 0)
sb.append(lps[i].getIPAddress()+") via ");
sb.append(lps[i].getTransport());
if (i < lps.length -1)
sb.append(", ");
}
if (log.isInfoEnabled())
log.info(sb.toString());
index++;
}
locationServiceName = props.getProperty("proxy.location.service.rmi.objectname", "LocationService").trim();
locationServiceHost = props.getProperty("proxy.location.service.rmi.host", "localhost").trim();
try
{
locationServicePort = Integer.parseInt(props.getProperty("proxy.location.service.rmi.port", "1099").trim());
}
catch(NumberFormatException ex)
{
// ignored
}
if (log.isInfoEnabled())
log.info("Connecting to Location Service server at " + locationServiceHost + ":" + locationServicePort + " ...");
LocationServiceInterface locationService = getLocationService();
if (locationService != null && locationService.isAlive())
{
if (log.isInfoEnabled())
log.info("Successfully connected.");
}
else
throw new RemoteException("Cannot connect to Location Service server.");
/**
* Reading domain configuration
*/
String domainsStr = props.getProperty("proxy.domains");
if (domainsStr != null)
{
String[] domainsArray = domainsStr.trim().split(",");
for (String domain : domainsArray)
{
domain = domain.trim();
if (domain.length() > 0) domains.add(domain);
}
}
if (domains.isEmpty())
{
log.warn("No domains configured. Retreiving the domain list from Location Service...");
domains.addAll(locationService.getDomains());
}
if (domains.isEmpty())
{
log.error("No domains configured. Proxy cannot be started.");
System.exit(1);
}
if (log.isInfoEnabled())
{
StringBuffer sb = new StringBuffer();
Iterator it = domains.iterator();
while (it.hasNext())
{
sb.append((String) it.next());
if (it.hasNext()) sb.append(", ");
}
log.info("Proxy is responsible for domains: " + sb.toString());
}
authenticationEnabled = props.getProperty("proxy.authentication.enabled", "no").trim().equalsIgnoreCase("yes");
if (log.isInfoEnabled())
{
if (authenticationEnabled)
log.info("Authentication enabled.");
else
log.info("Authentication disabled.");
}
String operationModeStr = props.getProperty("proxy.operation.mode", "stateless").trim().toLowerCase();
if (operationModeStr.equals("statefull"))
operationMode = STATEFULL_MODE;
else
operationMode = STATELESS_MODE;
if (log.isInfoEnabled())
{
if (operationMode == STATEFULL_MODE)
log.info("Proxy operation mode: statefull.");
else if (operationMode == STATELESS_MODE)
log.info("Proxy operation mode: stateless.");
else
log.info("Proxy operation mode: unknown.");
}
try
{
dsam = new DigestServerAuthenticationMethod(domains.iterator().next(), new String[] { "MD5" });
}
catch (NoSuchAlgorithmException ex)
{
log.error("Cannot create authentication method. Some algorithm is not implemented: " + ex.getMessage());
if (log.isTraceEnabled())
log.trace(null, ex);
System.exit(1);
}
/**
* It's time to load method plugins (REGISTER for example).
*/
if (log.isInfoEnabled())
log.info("Loading method plugins...");
index = 1;
String pluginClass;
while ((pluginClass = props.getProperty("proxy.method.plugin." + index + ".classname")) != null)
{
pluginClass = pluginClass.trim();
String pluginEnabled = props.getProperty("proxy.method.plugin." + index + ".enabled", "true");
if (!pluginEnabled.equals("true") && !pluginEnabled.equals("yes"))
{
index++;
continue;
}
if (log.isInfoEnabled())
log.info("Loading "+pluginClass);
try
{
Class c = Class.forName(pluginClass);
MethodPlugin methodPlugin = (MethodPlugin) c.newInstance();
String pathToPropertiesFile = props.getProperty("proxy.method.plugin." + index + ".properties");
Properties pluginProperties = props;
if (pathToPropertiesFile != null)
{
pluginProperties = new Properties();
pluginProperties.load(new FileInputStream(pathToPropertiesFile.trim()));
}
methodPlugin.initialize(pluginProperties, this);
if (methodPlugin.isInitialized())
methodPlugins.put(methodPlugin.getMethod(), methodPlugin);
}
catch (ClassNotFoundException ex)
{
log.error("Cannot load plugin class.", ex);
}
catch (InstantiationException ex)
{
log.error("Cannot load plugin class.", ex);
}
catch (IllegalAccessException ex)
{
log.error("Cannot load plugin class.", ex);
}
catch (IOException ex)
{
log.error("Cannot load .properties file. "+ ex.getMessage());
}
catch (Exception ex)
{
log.error("Plugin failed to initialize. "+ex.getMessage());
}
index++;
}
/**
* Read SNMP configuration
*/
boolean isSnmpEnabled = props.getProperty("proxy.snmp.agent.enabled", "yes").trim().equalsIgnoreCase("yes");
if (isSnmpEnabled)
{
int snmpPort = 1163;
try
{
snmpPort = Integer.parseInt(props.getProperty("proxy.snmp.agent.port", "1163").trim());
}
catch (NumberFormatException e)
{
/* ignored */
}
String communityName = props.getProperty("proxy.snmp.agent.community", "public").trim();
// Create our assistant class. This class should not be null even if SNMP is not enabled.
snmpAssistant = new SNMPAssistant(communityName, SNMP_DATABASE);
try
{
// Create SNMP agent engine
agentInterface = new SNMPv1AgentInterface(0 /* SNMP v1 */, snmpPort, null);
// Run agent
agentInterface.addRequestListener(snmpAssistant);
agentInterface.setReceiveBufferSize(5120);
agentInterface.startReceiving();
if (log.isInfoEnabled())
log.info("SNMP agent started at port "+snmpPort+" with community "+communityName);
}
catch(SocketException ex)
{
log.error("Cannot start SNMP agent at port "+snmpPort+": "+ex.getMessage());
}
}
// Add shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(this));
}
/**
* Shutdown hook
*/
public void run()
{
if (log != null && log.isInfoEnabled())
log.info("Shutting down...");
// Stop SNMP agent
try
{
if (agentInterface != null)
agentInterface.stopReceiving();
}
catch (SocketException ex)
{
/* ignored */
}
try
{
Naming.unbind(RMIBindName);
}
catch (Exception e)
{
/* ignored */
}
}
/**
* Returns remote Location Service instance. Do not cache this instance,
* because once Location Service restarted, it cannot be contacted without reconnecting.
* @return Remote Location Service instance.
*/
public LocationServiceInterface getLocationService()
{
try
{
Registry registry = LocateRegistry.getRegistry(locationServiceHost, locationServicePort);
LocationServiceInterface locationService = (LocationServiceInterface) registry.lookup(locationServiceName);
return locationService;
}
catch (RemoteException ex)
{
return null;
}
catch (NotBoundException ex)
{
return null;
}
}
/**
* @return SNMP assistant.
*/
public SNMPAssistant getSnmpAssistant()
{
return snmpAssistant;
}
public void processRequest(RequestEvent requestEvent)
{
Request request = requestEvent.getRequest();
CallIdHeader callidHeader = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
// Place Call-ID header to each log message
NDC.push(callidHeader != null ? callidHeader.getCallId() : Long.toString(System.currentTimeMillis()));
try
{
processIncomingRequest(requestEvent);
snmpAssistant.incrementSnmpInteger(SNMP_OID_NUM_REQUESTS_PROCESSED);
}
catch (Exception ex)
{
snmpAssistant.incrementSnmpInteger(SNMP_OID_NUM_REQUEST_PROCESSING_ERRORS);
if (log.isDebugEnabled())
log.debug("Exception: " + ex.getMessage());
if (log.isTraceEnabled())
log.trace("Exception dump: ", ex);
}
NDC.remove();
}
public void processResponse(ResponseEvent responseEvent)
{
Response response = responseEvent.getResponse();
CallIdHeader callidHeader = (CallIdHeader) response.getHeader(CallIdHeader.NAME);
// Place Call-ID header to each log message
NDC.push(callidHeader != null ? callidHeader.getCallId() : Long.toString(System.currentTimeMillis()));
try
{
processIncomingResponse(responseEvent);
snmpAssistant.incrementSnmpInteger(SNMP_OID_NUM_RESPONSES_PROCESSED);
}
catch (Exception ex)
{
snmpAssistant.incrementSnmpInteger(SNMP_OID_NUM_RESPONSE_PROCESSING_ERRORS);
if (log.isDebugEnabled())
log.debug("Exception: " + ex.getMessage());
if (log.isTraceEnabled())
log.trace("Exception dump: ", ex);
}
NDC.remove();
}
public void processTimeout(TimeoutEvent event)
{
ClientTransaction clientTransaction = event.getClientTransaction();
if (clientTransaction != null)
{
TransactionsMapping transactionsMapping = (TransactionsMapping) clientTransaction.getApplicationData();
if (transactionsMapping != null)
{
transactionsMapping.cancelTimerC(clientTransaction);
checkResponseContext(transactionsMapping);
}
}
if (log.isTraceEnabled())
log.trace("Timeout occured at "+getHostname((SipProvider) event.getSource())+". CT = "+event.getClientTransaction()+" ST = "+event.getServerTransaction());
}
public void processIOException(IOExceptionEvent event)
{
if (log.isTraceEnabled())
log.trace("IOException occured at "+getHostname((SipProvider) event.getSource())+". Host = "+event.getHost()+" Port = "+event.getPort()+" Transport = "+event.getTransport());
}
public void processTransactionTerminated(TransactionTerminatedEvent event)
{
if (event.isServerTransaction())
snmpAssistant.decrementSnmpInteger(SNMP_OID_NUM_SERVER_TRANSACTIONS);
else
snmpAssistant.decrementSnmpInteger(SNMP_OID_NUM_CLIENT_TRANSACTIONS);
if (log.isTraceEnabled())
log.trace("Transaction terminated at "+getHostname((SipProvider) event.getSource())+". CT = "+event.getClientTransaction()+" ST = "+event.getServerTransaction());
ClientTransaction clientTransaction = event.getClientTransaction();
if (clientTransaction != null)
{
TransactionsMapping transactionsMapping = (TransactionsMapping) clientTransaction.getApplicationData();
if (transactionsMapping != null)
{
transactionsMapping.cancelTimerC(clientTransaction);
checkResponseContext(transactionsMapping);
}
}
}
/**
* Cannot be called in proxies
* @param event DialogTerminatedEvent object
*/
public void processDialogTerminated(DialogTerminatedEvent event)
{
}
/**
* Returns whether proxy is responsible for domain
* @param domain Domain name. Cannot be IP or hostname. See addrMatchesInterface() function instead.
* @return true if proxy is responsible for <i>domain</i>, false otherwise.
*/
public boolean isDomainServed(String domain)
{
return domains.contains(domain);
}
public Iterator getSipProviders()
{
return sipStack.getSipProviders();
}
public HashSet getDomains()
{
return domains;
}
public String getDefaultDomain()
{
return domains.iterator().next();
}
public int getOperationMode()
{
return operationMode;
}
/**
* Returns whether <i>addr</i> matches any interface's IP or hostname.
* @param addr Address. Can be IP or hostname.
* @return true if <i>addr</i> matches any interface's IP or hostname.
*/
public boolean addrMatchesInterface(String addr)
{
return getProviderByAddr(addr) != null;
}
/**
* Returns SipProvider instance, whose associated network interface IP or hostname equals <i>addr</i>
* @param addr Address. Can be IP or hostname.
* @return returns SipProvider instance, whose associated network interface IP or hostname equals <i>addr</i>
*/
public SipProvider getProviderByAddr(String addr)
{
Iterator iterator = sipStack.getSipProviders();
while (iterator.hasNext())
{
SipProvider sipProvider = (SipProvider) iterator.next();
if (addr.equals(getIPAddress(sipProvider))) return sipProvider;
if (addr.equals(getHostname(sipProvider))) return sipProvider;
}