aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/neomedia/transform/zrtp/ZRTPTransformEngine.java
blob: 281920b2d0daaf2909596e770ebe565e1fff8959 (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
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
/*
 * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.neomedia.transform.zrtp;

import gnu.java.zrtp.*;
import gnu.java.zrtp.zidfile.*;

import org.osgi.framework.*;

import net.java.sip.communicator.impl.neomedia.*;
import net.java.sip.communicator.impl.neomedia.transform.*;
import net.java.sip.communicator.impl.neomedia.transform.srtp.*;
import net.java.sip.communicator.service.fileaccess.*;
import net.java.sip.communicator.util.*;

import java.io.*;
import java.util.*;

/**
 * JMF extension/connector to support GNU ZRTP4J.
 *
 * ZRTP was developed by Phil Zimmermann and provides functions to negotiate
 * keys and other necessary data (crypto data) to set-up the Secure RTP (SRTP)
 * crypto context. Refer to Phil's ZRTP specification at his
 * <a href="http://zfoneproject.com/">Zfone project</a> site to get more
 * detailed information about the capabilities of ZRTP.
 *
 * <h3>Short overview of the ZRTP4J implementation</h3>
 *
 * ZRTP is a specific protocol to negotiate encryption algorithms and the
 * required key material. ZRTP uses a RTP session to exchange its protocol
 * messages.
 *
 * A complete GNU ZRTP4J implementation consists of two parts, the GNU ZRTP4J
 * core and specific code that binds the GNU ZRTP core to the underlying
 * RTP/SRTP stack and the operating system:
 * <ul>
 * <li> The GNU ZRTP core is independent of a specific RTP/SRTP stack and the
 * operationg system and consists of the ZRTP protocol state engine, the ZRTP
 * protocol messages, and the GNU ZRTP4J engine. The GNU ZRTP4J engine provides
 * methods to setup ZRTP message and to analyze received ZRTP messages, to
 * compute the crypto data required for SRTP, and to maintain the required
 * hashes and HMAC. </li>
 * <li> The second part of an implementation is specific <em>glue</em> code
 * the binds the GNU ZRTP core to the actual RTP/SRTP implementation and other
 * operating system specific services such as timers. </li>
 * </ul>
 *
 * The GNU ZRTP4J core uses a callback interface class (refer to ZrtpCallback)
 * to access RTP/SRTP or operating specific methods, for example to send data
 * via the RTP/SRTP stack, to access timers, provide mutex handling, and to
 * report events to the application.
 *
 * <h3>The ZRTPTransformEngine</h3>
 *
 * ZRTPTransformEngine implements code that is specific to the JMF
 * implementation.
 *
 * To perform its tasks ZRTPTransformEngine
 * <ul>
 * <li> extends specific classes to hook into the JMF RTP methods and the
 * RTP/SRTP send and receive queues </li>
 * <li> implements the ZrtpCallback interface to provide to enable data send and
 * receive other specific services (timer to GNU ZRTP4J </li>
 * <li> provides ZRTP specific methods that applications may use to control and
 * setup GNU ZRTP </li>
 * <li> can register and use an application specific callback class (refer to
 * ZrtpUserCallback) </li>
 * </ul>
 *
 * After instantiating a GNU ZRTP4J session (see below for a short example)
 * applications may use the ZRTP specific methods of ZRTPTransformEngine to
 * control and setup GNU ZRTP, for example enable or disable ZRTP processing or
 * getting ZRTP status information.
 *
 * GNU ZRTP4J provides a ZrtpUserCallback class that an application may extend
 * and register with ZRTPTransformEngine. GNU ZRTP4J and ZRTPTransformEngine use
 * the ZrtpUserCallback methods to report ZRTP events to the application. The
 * application may display this information to the user or act otherwise.
 *
 * The following figure depicts the relationships between ZRTPTransformEngine,
 * JMF implementation, the GNU ZRTP4J core, and an application that provides an
 * ZrtpUserCallback class.
 *
 * <pre>
 *
 *                  +---------------------------+
 *                  |  ZrtpTransformConnector   |
 *                  | extends TransformConnector|
 *                  | implements RTPConnector   |
 *                  +---------------------------+
 *                                |
 *                                | uses
 *                                |
 *  +----------------+      +-----+---------------+
 *  |  Application   |      |                     |      +----------------+
 *  |  instantiates  | uses | ZRTPTransformEngine | uses |                |
 *  | a ZRTP Session +------+    implements       +------+   GNU ZRTP4J   |
 *  |  and provides  |      |   ZrtpCallback      |      |      core      |
 *  |ZrtpUserCallback|      |                     |      | implementation |
 *  +----------------+      +---------------------+      |  (ZRtp et al)  |
 *                                                       |                |
 *                                                       +----------------+
 * </pre>
 *
 * The following short code snippets show how an application could instantiate a
 * ZrtpTransformConnector, get the ZRTP4J engine and initialize it. Then the
 * code get a RTP manager instance and initializes it with the
 * ZRTPTransformConnector. Please note: setting the target must be done with the
 * connector, not with the RTP manager.
 *
 * <pre>
 * ...
 *   transConnector = (ZrtpTransformConnector)TransformManager
 *                                                  .createZRTPConnector(sa);
 *   zrtpEngine = transConnector.getEngine();
 *   zrtpEngine.setUserCallback(new MyCallback());
 *   if (!zrtpEngine.initialize(&quot;test_t.zid&quot;))
 *       System.out.println(&quot;iniatlize failed&quot;);
 *
 *   // initialize the RTPManager using the ZRTP connector
 *
 *   mgr = RTPManager.newInstance();
 *   mgr.initialize(transConnector);
 *
 *   mgr.addSessionListener(this);
 *   mgr.addReceiveStreamListener(this);
 *
 *   transConnector.addTarget(target);
 *   zrtpEngine.startZrtp();
 *
 *   ...
 * </pre>
 *
 * The <em>demo</em> folder contains a small example that shows how to use GNU
 * ZRTP4J.
 *
 * This ZRTPTransformEngine documentation shows the ZRTP specific extensions and
 * describes overloaded methods and a possible different behaviour.
 *
 * @author Werner Dittmann &lt;Werner.Dittmann@t-online.de>
 *
 */
public class ZRTPTransformEngine
    implements  TransformEngine,
                PacketTransformer,
                ZrtpCallback
{
    /**
     * Very simple Timeout provider class.
     *
     * This very simple timeout provider can handle one timeout request at
     * one time only. A second request would overwrite the first one and would
     * lead to unexpected results.
     *
     * @author Werner Dittmann <Werner.Dittmann@t-online.de>
     */
    private class TimeoutProvider extends Thread
    {
        /**
         * Constructs Timeout provider.
         * @param name the name of the provider.
         */
        public TimeoutProvider(String name)
        {
            super(name);
        }

        /**
         * The delay to wait before timeout.
         */
        private long nextDelay = 0;

        /**
         * Whether to execute the timeout if delay expires.
         */
        private boolean newTask = false;

        /**
         * Whether thread is stopped.
         */
        private boolean stop = false;

        /**
         * synchronizes delays and stop.
         */
        private final Object sync = new Object();

        /**
         * Request timeout after the specified delay.
         * @param delay the delay.
         */
        public synchronized void requestTimeout(long delay)
        {
            synchronized (sync)
            {
                nextDelay = delay;
                newTask = true;
                sync.notifyAll();
            }
        }

        /**
         * Stops the thread.
         */
        public void stopRun()
        {
            synchronized (sync)
            {
                stop = true;
                sync.notifyAll();
            }
        }

        /**
         * Cancels the last request.
         */
        public void cancelRequest()
        {
            synchronized (sync)
            {
                newTask = false;
                sync.notifyAll();
            }
        }

        /**
         * The running part of the thread.
         */
        @Override
        public void run()
        {
            while (!stop)
            {
                synchronized (sync)
                {
                    while (!newTask && !stop)
                    {
                        try
                        {
                            sync.wait();
                        }
                        catch (InterruptedException e)
                        {
                            // e.printStackTrace();
                        }
                    }
                }
                long currentTime = System.currentTimeMillis();
                long endTime = currentTime + nextDelay;
                synchronized (sync) {
                    while ((currentTime < endTime) && newTask && !stop)
                    {
                        try
                        {
                            sync.wait(endTime - currentTime);
                        }
                        catch (InterruptedException e)
                        {
                            //e.printStackTrace();
                        }
                        currentTime = System.currentTimeMillis();
                    }
                }
                if (newTask && !stop)
                {
                    newTask = false;
                    ZRTPTransformEngine.this.handleTimeout();
                }
            }
        }
    }

    /**
     * The logger.
     */
    private static final Logger logger
        = Logger.getLogger(ZRTPTransformEngine.class);

    /**
     * Each ZRTP packet has a fixed header of 12 bytes.
     */
    protected static final int ZRTP_PACKET_HEADER = 12;

    /**
     * This is the connector, required to send ZRTP packets
     * via the DatagramSocket.
     */
    private RTPTransformConnector zrtpConnector = null;

    /**
     * We need Out SRTPTransformer to transform RTP to SRTP.
     */
    private PacketTransformer srtpOutTransformer = null;

    /**
     * We need In SRTPTransformer to transform SRTP to RTP.
     */
    private PacketTransformer srtpInTransformer = null;

    /**
     * User callback class.
     */
    private SecurityEventManager securityEventManager = null;

    /**
     * The ZRTP engine.
     */
    private ZRtp zrtpEngine = null;

    /**
     * ZRTP engine enable flag (used for auto-enable at initialization)
     */
    private boolean enableZrtp = false;

    /**
     * Client ID string initialized with the name of the ZRTP4j library
     */
    private String clientIdString = ZrtpConstants.clientId;

    /**
     * SSRC identifier for the ZRTP packets
     */
    private int ownSSRC = 0;

    /**
     * ZRTP packet sequence number
     */
    private short senderZrtpSeqNo = 0;

    /**
     * The number of sent packets
     */
    private long sendPacketCount = 0;

    /**
     * The timeout provider instance
     * This is used for handling the ZRTP timers
     */
    private TimeoutProvider timeoutProvider = null;

    /**
     * The current condition of the ZRTP engine
     */
    private boolean started = false;

    /**
     * Sometimes we need to start muted so we will discard any packets during
     * some time after the start of the transformer. This is needed when for
     * this time we can receive encrypted packets but we hadn't established
     * a secure communication. This happens when a secure stream is recreated.
     */
    private boolean muted = false;

    /**
     * Construct a ZRTPTransformEngine.
     *
     */
    public ZRTPTransformEngine()
    {
        senderZrtpSeqNo = 1;    // should be a random number
    }

    /**
     * Returns an instance of <tt>ZRTPCTransformer</tt>.
     *
     * @see TransformEngine#getRTCPTransformer()
     */
    public PacketTransformer getRTCPTransformer()
    {
        return new ZRTPCTransformer(this);
    }

    /**
     * Returns this RTPTransformer.
     *
     * @see TransformEngine#getRTPTransformer()
     */
    public PacketTransformer getRTPTransformer()
    {
        return this;
    }

    /**
     * Engine initialization method.
     * Calling this for engine initialization and start it with auto-sensing
     * and a given configuration setting.
     *
     * @param zidFilename The ZID file name
     * @param config The configuration data
     * @return true if initialization fails, false if succeeds
     */
    public boolean initialize(String zidFilename, ZrtpConfigure config)
    {
        return initialize(zidFilename, true, config);
    }

    /**
     * Engine initialization method.
     * Calling this for engine initialization and start it with defined
     * auto-sensing and a default configuration setting.
     *
     * @param zidFilename The ZID file name
     * @param autoEnable If true start with auto-sensing mode.
     * @return true if initialization fails, false if succeeds
     */
    public boolean initialize(String zidFilename, boolean autoEnable) {
        return initialize(zidFilename, autoEnable, null);
    }

    /**
     * Default engine initialization method.
     *
     * Calling this for engine initialization and start it with auto-sensing
     * and default configuration setting.
     *
     * @param zidFilename The ZID file name
     * @return true if initialization fails, false if succeeds
     */
    public boolean initialize(String zidFilename) {
        return initialize(zidFilename, true, null);
    }

    /**
     * Custom engine initialization method.
     * This allows to explicit specify if the engine starts with auto-sensing
     * or not.
     *
     * @param zidFilename The ZID file name
     * @param autoEnable Set this true to start with auto-sensing and false to
     * disable it.
     * @param config the zrtp config to use
     * @return true if initialization fails, false if succeeds
     */
    public synchronized boolean initialize(String zidFilename,
            boolean autoEnable, ZrtpConfigure config)
    {
        // Get a reference to the FileAccessService
        BundleContext bc = NeomediaActivator.getBundleContext();
        ServiceReference faServiceReference = bc.getServiceReference(
                FileAccessService.class.getName());
        FileAccessService faService = (FileAccessService)
                bc.getService(faServiceReference);

        File file = null;
        try
        {
            // Create the zid file
            file = faService.getPrivatePersistentFile(zidFilename);
        }
        catch (Exception e)
        {
            logger.warn("Failed to create the zid file.");

            if (logger.isDebugEnabled())
                logger.debug("Failed to create the zid file.", e);
        }

        String zidFilePath = null;
        try
        {
            if (file != null)
                // Get the absolute path of the created zid file
                zidFilePath = file.getAbsolutePath();
        }
        catch (SecurityException e)
        {
            if (logger.isDebugEnabled())
                logger.debug(
                    "Failed to obtain the absolute path of the zid file.", e);
        }

        ZidFile zf = ZidFile.getInstance();
        if (!zf.isOpen())
        {
            String fname;
            if (zidFilePath == null)
            {
                String home = System.getenv("HOME");
                String baseDir = (home != null) ? ((home) + ("/.")) : ".";
                fname = baseDir + "GNUZRTP4J.zid";
                zidFilename = fname;
            }
            else
            {
                zidFilename = zidFilePath;
            }

            if (zf.open(zidFilename) < 0)
            {
                return false;
            }
        }
        if (config == null) {
            config = new ZrtpConfigure();
            config.setStandardConfig();
        }

        zrtpEngine = new ZRtp(zf.getZid(), this, clientIdString, config);

        if (timeoutProvider == null)
        {
            timeoutProvider = new TimeoutProvider("ZRTP");
            // timeoutProvider.setDaemon(true); // Daemon only if timeoutprovider is a global singleton
            timeoutProvider.start();
        }

        enableZrtp = autoEnable;
        return true;
    }

    /**
     *
     * @param startMuted whether to be started as muted if no secure
     *      communication is established
     */
    public void setStartMuted(boolean startMuted)
    {
        muted = startMuted;
        if(startMuted)
        {
            // make sure we don't mute for long time as secure communication
            // may fail.
            new Timer().schedule(new TimerTask()
            {
                public void run()
                {
                    ZRTPTransformEngine.this.muted = false;
                }
            }, 1500);
        }
    }

    /**
     * Method for getting the default secure status value for communication
     *
     * @return the default enabled/disabled status value for secure
     * communication
     */
    public boolean getSecureCommunicationStatus()
    {
        return srtpInTransformer != null || srtpOutTransformer != null;
    }

    /**
     * Start the ZRTP stack immediately, not autosensing mode.
     */
    public void startZrtp()
    {
        if (zrtpEngine != null)
        {
            zrtpEngine.startZrtpEngine();
            started = true;
        }
    }

    /**
     * Stop ZRTP engine.
     */
    public void stopZrtp()
    {
        if (zrtpEngine != null)
        {
            zrtpEngine.stopZrtp();
            zrtpEngine = null;
            started = false;
        }
    }

    /**
     * Cleanup function for any remaining timers
     */
    public void cleanup()
    {
        if (timeoutProvider != null)
        {
            timeoutProvider.stopRun();
            timeoutProvider = null;
        }
    }

    /**
     * Set the SSRC of the RTP transmitter stream.
     *
     * ZRTP fills the SSRC in the ZRTP messages.
     *
     * @param ssrc SSRC to set
     */
    public void setOwnSSRC(long ssrc) {
        ownSSRC = (int)(ssrc & 0xffffffff);
    }

    /**
     * The data output stream calls this method to transform outgoing
     * packets.
     *
     * @see PacketTransformer#transform(RawPacket)
     */
    public RawPacket transform(RawPacket pkt)
    {
        /*
         * Never transform outgoing ZRTP (invalid RTP) packets.
         */
        if (ZrtpRawPacket.isZrtpData(pkt))
        {
            return pkt;
        }

        // ZRTP needs the SSRC of the sending stream.
        if (enableZrtp && ownSSRC == 0)
        {
            ownSSRC = pkt.getSSRC();
        }

        // If SRTP is active then srtpTransformer is set, use it.
        sendPacketCount++;
        if (srtpOutTransformer == null)
        {
            return pkt;
        }

        return srtpOutTransformer.transform(pkt);
    }

    /**
     * The input data stream calls this method to transform
     * incoming packets.
     *
     * @see PacketTransformer#reverseTransform(RawPacket)
     */
    public RawPacket reverseTransform(RawPacket pkt)
    {
        // Check if we need to start ZRTP
        if (!started && enableZrtp && ownSSRC != 0)
            startZrtp();

        /*
         * Check if incoming packt is a ZRTP packet, if not treat
         * it as normal RTP packet and handle it accordingly.
         */
        if (!ZrtpRawPacket.isZrtpData(pkt))
        {
            if (srtpInTransformer == null)
            {
                if(muted)
                    return null;
                else
                    return pkt;
            }

            pkt = srtpInTransformer.reverseTransform(pkt);
            // if packet was valid (i.e. not null) and ZRTP engine started and
            // in Wait for Confirm2 Ack then emulate a Conf2Ack packet.
            // See ZRTP specification chap. 5.6
            if ((pkt != null)
                    && started
                    && zrtpEngine
                        .inState(ZrtpStateClass.ZrtpStates.WaitConfAck))
            {
                zrtpEngine.conf2AckSecure();
            }
            return pkt;
        }

        /*
         * If ZRTP is enabled process it.
         *
         * In any case return null because ZRTP packets must never reach
         * the application.
         */
        if (enableZrtp && started)
        {
            ZrtpRawPacket zPkt = new ZrtpRawPacket(pkt);
            if (!zPkt.checkCrc())
            {
                securityEventManager
                    .showMessage(
                        ZrtpCodes.MessageSeverity.Warning,
                        EnumSet.of(ZrtpCodes.WarningCodes.WarningCRCmismatch));
            }
            // Check if it is really a ZRTP packet, if not don't process it
            else if (zPkt.hasMagic())
            {
                int extHeaderOffset = zPkt.getHeaderLength()
                        - zPkt.getExtensionLength() - RawPacket.EXT_HEADER_SIZE;
                // zrtp engine need a "pointer" to the extension header, so
                // we give him the extension header and the payload data
                byte[] extHeader = zPkt.readRegion(
                    extHeaderOffset,
                    RawPacket.EXT_HEADER_SIZE +
                    zPkt.getExtensionLength() + zPkt.getPayloadLength());
                zrtpEngine.processZrtpMessage(extHeader, zPkt.getSSRC());
            }
        }

        return null;
    }

    /**
     * The callback method required by the ZRTP implementation.
     * First allocate space to hold the complete ZRTP packet, copy
     * the message part in its place, the initalize the header, counter,
     * SSRC and crc.
     *
     * @param data The ZRTP packet data
     * @return true if sending succeeds, false if it fails
     */
    public boolean sendDataZRTP(byte[] data)
    {
        int totalLength = ZRTP_PACKET_HEADER + data.length;
        byte[] tmp = new byte[totalLength];
        System.arraycopy(data, 0, tmp, ZRTP_PACKET_HEADER, data.length);
        ZrtpRawPacket packet = new ZrtpRawPacket(tmp, 0, tmp.length);

        packet.setSSRC(ownSSRC);

        packet.setSeqNum(senderZrtpSeqNo++);

        packet.setCrc();

        try
        {
            zrtpConnector.getDataOutputStream().write(  packet.getBuffer(),
                                                        packet.getOffset(),
                                                        packet.getLength());
        }
        catch (IOException e)
        {
            logger.warn("Failed to send ZRTP data.");

            if (logger.isDebugEnabled())
                logger.debug("Failed to send ZRTP data.", e);

            return false;
        }
        return true;
    }

    /**
     * Switch on the security for the defined part.
     *
     * @param secrets The secret keys and salt negotiated by ZRTP
     * @param part An enum that defines sender, receiver, or both.
     * @return always return true.
     */
    public boolean srtpSecretsReady(
        ZrtpSrtpSecrets secrets, EnableSecurity part)
    {
        SRTPPolicy srtpPolicy = null;

        if (part == EnableSecurity.ForSender)
        {
            // To encrypt packets: initiator uses initiator keys,
            // responder uses responder keys
            // Create a "half baked" crypto context first and store it. This is
            // the main crypto context for the sending part of the connection.
            if (secrets.getRole() == Role.Initiator)
            {
                srtpPolicy = new SRTPPolicy(SRTPPolicy.AESCM_ENCRYPTION,
                        secrets.getInitKeyLen() / 8,    // key length
                        SRTPPolicy.HMACSHA1_AUTHENTICATION,
                        20,                             // auth key length
                        secrets.getSrtpAuthTagLen() / 8,// auth tag length
                        secrets.getInitSaltLen() / 8    // salt length
                );

                SRTPTransformEngine engine = new SRTPTransformEngine(secrets
                        .getKeyInitiator(), secrets.getSaltInitiator(),
                        srtpPolicy, srtpPolicy);

                srtpOutTransformer = engine.getRTPTransformer();
            }
            else
            {
                srtpPolicy = new SRTPPolicy(SRTPPolicy.AESCM_ENCRYPTION,
                        secrets.getRespKeyLen() / 8,    // key length
                        SRTPPolicy.HMACSHA1_AUTHENTICATION,
                        20,                             // auth key length
                        secrets.getSrtpAuthTagLen() / 8,// auth taglength
                        secrets.getRespSaltLen() / 8    // salt length
                );

                SRTPTransformEngine engine = new SRTPTransformEngine(secrets
                        .getKeyResponder(), secrets.getSaltResponder(),
                        srtpPolicy, srtpPolicy);
                srtpOutTransformer = engine.getRTPTransformer();
            }
        }

        if (part == EnableSecurity.ForReceiver)
        {
            // To decrypt packets: initiator uses responder keys,
            // responder initiator keys
            // See comment above.
            if (secrets.getRole() == Role.Initiator)
            {
                srtpPolicy = new SRTPPolicy(SRTPPolicy.AESCM_ENCRYPTION,
                        secrets.getRespKeyLen() / 8,    // key length
                        SRTPPolicy.HMACSHA1_AUTHENTICATION,
                        20,                             // auth key length
                        secrets.getSrtpAuthTagLen() / 8,// auth tag length
                        secrets.getRespSaltLen() / 8    // salt length
                );

                SRTPTransformEngine engine = new SRTPTransformEngine(secrets
                        .getKeyResponder(), secrets.getSaltResponder(),
                        srtpPolicy, srtpPolicy);
                srtpInTransformer = engine.getRTPTransformer();
                this.muted = false;
            }
            else
            {
                srtpPolicy = new SRTPPolicy(SRTPPolicy.AESCM_ENCRYPTION,
                        secrets.getInitKeyLen() / 8,    // key length
                        SRTPPolicy.HMACSHA1_AUTHENTICATION,
                        20,                             // auth key length
                        secrets.getSrtpAuthTagLen() / 8,// auth tag length
                        secrets.getInitSaltLen() / 8    // salt length
                );

                SRTPTransformEngine engine = new SRTPTransformEngine(secrets
                        .getKeyInitiator(), secrets.getSaltInitiator(),
                        srtpPolicy, srtpPolicy);
                srtpInTransformer = engine.getRTPTransformer();
                this.muted = false;
            }
        }
        return true;
    }

    /**
     *
     * @param c
     * @param s
     * @param verified
     * @see gnu.java.zrtp.ZrtpCallback#srtpSecretsOn(java.lang.String,
     *                                               java.lang.String, boolean)
     */
    public void srtpSecretsOn(String c, String s, boolean verified)
    {
        if (securityEventManager != null)
        {
            securityEventManager.secureOn(c);
        }

        if (securityEventManager != null && s != null)
        {
            securityEventManager.showSAS(s, verified);
        }
    }

    /**
     * This method shall clear the ZRTP secrets.
     *
     * @param part Defines for which part (sender or receiver)
     *        to switch on security
     */
    public void srtpSecretsOff(EnableSecurity part)
    {
        if (part == EnableSecurity.ForSender)
        {
            srtpOutTransformer = null;
        }

        if (part == EnableSecurity.ForReceiver)
        {
            srtpInTransformer = null;
        }

        if (securityEventManager != null)
        {
            securityEventManager.secureOff();
        }
    }

    /**
     * Activate timer.
     * @param time    The time in ms for the timer.
     * @return always return 1.
     */
    public int activateTimer(int time)
    {
        if (timeoutProvider != null)
        {
            timeoutProvider.requestTimeout(time);
        }

        return 1;
    }

    /**
     * Cancel the active timer.
     * @return always return 1.
     */
    public int cancelTimer()
    {
        if (timeoutProvider != null)
        {
            timeoutProvider.cancelRequest();
        }
        return 1;
    }

    /**
     * Timeout handling function.
     * Delegates the handling to the ZRTP engine.
     */
    public void handleTimeout()
    {
        if (zrtpEngine != null)
        {
            zrtpEngine.processTimeout();
        }
    }

    /**
     * Send information messages to the hosting environment.
     * @param severity This defines the message's severity
     * @param subCode     The message code.
     */
    public void sendInfo(ZrtpCodes.MessageSeverity severity, EnumSet<?> subCode)
    {
        if (securityEventManager != null)
        {
            securityEventManager.showMessage(severity, subCode);
        }
    }

    /**
     * Comes a message that zrtp negotiation has failed.
     * @param severity This defines the message's severity
     * @param subCode     The message code.
     */
    public void zrtpNegotiationFailed(ZrtpCodes.MessageSeverity severity,
                                      EnumSet<?> subCode)
    {
        if (securityEventManager != null)
        {
            securityEventManager.zrtpNegotiationFailed(severity, subCode);
        }
    }

    /**
     * The other part doesn't support zrtp.
     */
    public void zrtpNotSuppOther()
    {
        if (securityEventManager != null)
        {
            securityEventManager.zrtpNotSuppOther();
        }
    }

    /**
     * Zrtp ask for Enrollment.
     * @param info supplied info.
     */
    public void zrtpAskEnrollment(String info)
    {
        if (securityEventManager != null)
        {
            securityEventManager.zrtpAskEnrollment(info);
        }
    }

    /**
     *
     * @param info
     * @see gnu.java.zrtp.ZrtpCallback#zrtpInformEnrollment(java.lang.String)
     */
    public void zrtpInformEnrollment(String info)
    {
        if (securityEventManager != null)
        {
            securityEventManager.zrtpInformEnrollment(info);
        }
    }

    /**
     *
     * @param sas
     * @see gnu.java.zrtp.ZrtpCallback#signSAS(java.lang.String)
     */
    public void signSAS(String sas)
    {
        if (securityEventManager != null)
        {
            securityEventManager.signSAS(sas);
        }
    }

    /**
     *
     * @param sas
     * @return false if signature check fails, true otherwise
     * @see gnu.java.zrtp.ZrtpCallback#checkSASSignature(java.lang.String)
     */
    public boolean checkSASSignature(String sas)
    {
        return ((securityEventManager != null)
                        ? securityEventManager.checkSASSignature(sas)
                        : false);
    }

    /**
     * Sets the enableZrtp flag.
     *
     * @param onOff The value for the enableZrtp flag.
     */
    public void setEnableZrtp(boolean onOff)
    {
        enableZrtp = onOff;
    }

    /**
     * Returns the enableZrtp flag.
     *
     * @return the enableZrtp flag.
     */
    public boolean isEnableZrtp()
    {
        return enableZrtp;
    }

    /**
     * Set the SAS as verified internally if the user confirms it
     */
    public void SASVerified()
    {
        if (zrtpEngine != null)
            zrtpEngine.SASVerified();
    }

    /**
     * Resets the internal engine SAS verified flag
     */
    public void resetSASVerified()
    {
        if (zrtpEngine != null)
            zrtpEngine.resetSASVerified();
    }

    /**
     * Method called when the user requests through GUI to switch a secured call
     * to unsecure mode. Just forwards the request to the Zrtp class.
     */
    public void requestGoClear()
    {
//        if (zrtpEngine != null)
//            zrtpEngine.requestGoClear();
    }

    /**
     * Method called when the user requests through GUI to switch a previously
     * unsecured call back to secure mode. Just forwards the request to the
     * Zrtp class.
     */
    public void requestGoSecure()
    {
//        if (zrtpEngine != null)
//            zrtpEngine.requestGoSecure();
    }

    /**
     * Sets the auxilliary secret data
     *
     * @param data The auxilliary secret data
     */
    public void setAuxSecret(byte[] data)
    {
        if (zrtpEngine != null)
            zrtpEngine.setAuxSecret(data);
    }


    /**
     * Sets the PBX secret data
     *
     * @param data The PBX secret data
     */
    public void setPbxSecret(byte[] data) {
        if (zrtpEngine != null)
            zrtpEngine.setPbxSecret(data);
    }

    /**
     * Sets the client ID
     *
     * @param id The client ID
     */
    public void setClientId(String id)
    {
        clientIdString = id;
    }

    /**
     * Gets the Hello packet Hash
     *
     * @return the Hello packet hash
     */
    public String getHelloHash()
    {
        if (zrtpEngine != null)
            return zrtpEngine.getHelloHash();
        else
            return new String();
    }

    /**
     * Get the ZRTP Hello Hash data - separate strings.
     * 
     * @return String array containing the version string at offset 0, the Hello 
     *         hash value as hex-digits at offset 1. Hello hash is available 
     *         immediately after class instantiation. Retruns <code>null</code>
     *         if ZRTP is not available.
     */
    public String[] getHelloHashSep() {
        if (zrtpEngine != null)
            return zrtpEngine.getHelloHashSep();
        else
            return null;
    }
    
    /**
     * Gets the multistream params
     *
     * @return the multistream params
     */
    public byte[] getMultiStrParams()
    {
        if (zrtpEngine != null)
            return zrtpEngine.getMultiStrParams();
        else
            return new byte[0];
    }

    /**
     * Sets the multistream params
     * (The multistream part needs further development)
     * @param parameters the multistream params
     */
    public void setMultiStrParams(byte[] parameters)
    {
        if (zrtpEngine != null) {
            zrtpEngine.setMultiStrParams(parameters);
        }
    }

    /**
     * Gets the multistream flag
     * (The multistream part needs further development)
     * @return the multistream flag
     */
    public boolean isMultiStream()
    {
        return ((zrtpEngine != null) ? zrtpEngine.isMultiStream() : false);
    }

    /**
     * Used to accept a PBX enrollment request
     * (The PBX part needs further development)
     * @param accepted The boolean value indicating if the request is accepted
     */
    public void acceptEnrollment(boolean accepted)
    {
        if (zrtpEngine != null)
            zrtpEngine.acceptEnrollment(accepted);
    }

    /**
     * Sets signature data for the Confirm packets
     *
     * @param data the signature data
     * @return true if signature data was successfully set
     */
    public boolean setSignatureData(byte[] data)
    {
        return ((zrtpEngine != null) ? zrtpEngine.setSignatureData(data)
                : false);
    }

    /**
     * Gets signature data
     *
     * @return the signature data
     */
    public byte[] getSignatureData()
    {
        if (zrtpEngine != null)
            return zrtpEngine.getSignatureData();
        else
            return new byte[0];
    }

    /**
     * Gets signature length
     *
     * @return the signature length
     */
    public int getSignatureLength()
    {
        return ((zrtpEngine != null) ? zrtpEngine.getSignatureLength() : 0);
    }

    /**
     * Sets the PBX enrollment flag (see chapter 8.3 of ZRTP standards)
     * (The PBX part needs further development)
     * @param yesNo The PBX enrollment flag
     */
    public void setPBXEnrollment(boolean yesNo)
    {
        if (zrtpEngine != null)
            zrtpEngine.setPBXEnrollment(yesNo);
    }

    /**
     * Method called by the Zrtp class as result of a GoClear request from the
     * other peer. An explicit user confirmation is needed before switching to
     * unsecured mode. This is asked through the user callback.
     */
    public void handleGoClear()
    {
        securityEventManager.confirmGoClear();
    }

    /**
     * Sets the RTP connector using this ZRTP engine
     * (This method should be changed to an addConnector to a connector array
     *  managed by the engine for implementing multistream mode)
     *
     * @param connector the connector to set
     */
    public void setConnector(RTPTransformConnector connector)
    {
        zrtpConnector = connector;
    }

    /**
     * Sets the user callback class used to maintain the GUI ZRTP part
     *
     * @param ub The user callback class
     */
    public void setUserCallback(SecurityEventManager ub)
    {
        securityEventManager = ub;
    }

    /**
     * Returns the current status of the ZRTP engine
     *
     * @return the current status of the ZRTP engine
     */
    public boolean isStarted()
    {
       return started;
    }

    /**
     * Gets the user callback used to manage the GUI part of ZRTP
     *
     * @return the user callback
     */
    public SecurityEventManager getUserCallback()
    {
        return securityEventManager;
    }

    /**
     * Get other party's ZID (ZRTP Identifier) data
     *
     * This functions returns the other party's ZID that was receivied
     * during ZRTP processing.
     *
     * The ZID data can be retrieved after ZRTP receive the first Hello
     * packet from the other party. The application may call this method
     * for example during SAS processing in showSAS(...) user callback
     * method.
     *
     * @return the ZID data as byte array.
     */
    public byte[] getZid()
    {
         return ((zrtpEngine != null) ? zrtpEngine.getZid() : null);
    }
}