* #36737: switch back to svn repo, remove assert in sip_transaction.c
diff --git a/jni/pjproject-android/.svn/pristine/db/db15d852bf6297ba83127f61ea10f365a6b45d98.svn-base b/jni/pjproject-android/.svn/pristine/db/db15d852bf6297ba83127f61ea10f365a6b45d98.svn-base
new file mode 100644
index 0000000..33d3f74
--- /dev/null
+++ b/jni/pjproject-android/.svn/pristine/db/db15d852bf6297ba83127f61ea10f365a6b45d98.svn-base
@@ -0,0 +1,652 @@
+
+   /******************************************************************
+
+       iLBC Speech Coder ANSI-C Source Code
+
+       iLBC_decode.c
+
+       Copyright (C) The Internet Society (2004).
+       All Rights Reserved.
+
+   ******************************************************************/
+
+   #include <math.h>
+   #include <stdlib.h>
+
+   #include "iLBC_define.h"
+   #include "StateConstructW.h"
+   #include "LPCdecode.h"
+   #include "iCBConstruct.h"
+   #include "doCPLC.h"
+   #include "helpfun.h"
+   #include "constants.h"
+   #include "packing.h"
+   #include "string.h"
+   #include "enhancer.h"
+   #include "hpOutput.h"
+   #include "syntFilter.h"
+
+   /*----------------------------------------------------------------*
+    *  Initiation of decoder instance.
+    *---------------------------------------------------------------*/
+
+   short initDecode(                   /* (o) Number of decoded
+                                              samples */
+       iLBC_Dec_Inst_t *iLBCdec_inst,  /* (i/o) Decoder instance */
+       int mode,                       /* (i) frame size mode */
+       int use_enhancer                /* (i) 1 to use enhancer
+                                              0 to run without
+                                                enhancer */
+   ){
+       int i;
+
+       iLBCdec_inst->mode = mode;
+
+
+
+
+
+       if (mode==30) {
+           iLBCdec_inst->blockl = BLOCKL_30MS;
+           iLBCdec_inst->nsub = NSUB_30MS;
+           iLBCdec_inst->nasub = NASUB_30MS;
+           iLBCdec_inst->lpc_n = LPC_N_30MS;
+           iLBCdec_inst->no_of_bytes = NO_OF_BYTES_30MS;
+           iLBCdec_inst->no_of_words = NO_OF_WORDS_30MS;
+           iLBCdec_inst->state_short_len=STATE_SHORT_LEN_30MS;
+           /* ULP init */
+           iLBCdec_inst->ULP_inst=&ULP_30msTbl;
+       }
+       else if (mode==20) {
+           iLBCdec_inst->blockl = BLOCKL_20MS;
+           iLBCdec_inst->nsub = NSUB_20MS;
+           iLBCdec_inst->nasub = NASUB_20MS;
+           iLBCdec_inst->lpc_n = LPC_N_20MS;
+           iLBCdec_inst->no_of_bytes = NO_OF_BYTES_20MS;
+           iLBCdec_inst->no_of_words = NO_OF_WORDS_20MS;
+           iLBCdec_inst->state_short_len=STATE_SHORT_LEN_20MS;
+           /* ULP init */
+           iLBCdec_inst->ULP_inst=&ULP_20msTbl;
+       }
+       else {
+           exit(2);
+       }
+
+       memset(iLBCdec_inst->syntMem, 0,
+           LPC_FILTERORDER*sizeof(float));
+       memcpy((*iLBCdec_inst).lsfdeqold, lsfmeanTbl,
+           LPC_FILTERORDER*sizeof(float));
+
+       memset(iLBCdec_inst->old_syntdenum, 0,
+           ((LPC_FILTERORDER + 1)*NSUB_MAX)*sizeof(float));
+       for (i=0; i<NSUB_MAX; i++)
+           iLBCdec_inst->old_syntdenum[i*(LPC_FILTERORDER+1)]=1.0;
+
+       iLBCdec_inst->last_lag = 20;
+
+       iLBCdec_inst->prevLag = 120;
+       iLBCdec_inst->per = 0.0;
+       iLBCdec_inst->consPLICount = 0;
+       iLBCdec_inst->prevPLI = 0;
+       iLBCdec_inst->prevLpc[0] = 1.0;
+       memset(iLBCdec_inst->prevLpc+1,0,
+           LPC_FILTERORDER*sizeof(float));
+       memset(iLBCdec_inst->prevResidual, 0, BLOCKL_MAX*sizeof(float));
+       iLBCdec_inst->seed=777;
+
+
+
+
+
+
+       memset(iLBCdec_inst->hpomem, 0, 4*sizeof(float));
+
+       iLBCdec_inst->use_enhancer = use_enhancer;
+       memset(iLBCdec_inst->enh_buf, 0, ENH_BUFL*sizeof(float));
+       for (i=0;i<ENH_NBLOCKS_TOT;i++)
+           iLBCdec_inst->enh_period[i]=(float)40.0;
+
+       iLBCdec_inst->prev_enh_pl = 0;
+
+       return (short)(iLBCdec_inst->blockl);
+   }
+
+   /*----------------------------------------------------------------*
+    *  frame residual decoder function (subrutine to iLBC_decode)
+    *---------------------------------------------------------------*/
+
+   void Decode(
+       iLBC_Dec_Inst_t *iLBCdec_inst,  /* (i/o) the decoder state
+                                                structure */
+       float *decresidual,             /* (o) decoded residual frame */
+       int start,                      /* (i) location of start
+                                              state */
+       int idxForMax,                  /* (i) codebook index for the
+                                              maximum value */
+       int *idxVec,                /* (i) codebook indexes for the
+                                              samples  in the start
+                                              state */
+       float *syntdenum,               /* (i) the decoded synthesis
+                                              filter coefficients */
+       int *cb_index,                  /* (i) the indexes for the
+                                              adaptive codebook */
+       int *gain_index,            /* (i) the indexes for the
+                                              corresponding gains */
+       int *extra_cb_index,        /* (i) the indexes for the
+                                              adaptive codebook part
+                                              of start state */
+       int *extra_gain_index,          /* (i) the indexes for the
+                                              corresponding gains */
+       int state_first                 /* (i) 1 if non adaptive part
+                                              of start state comes
+                                              first 0 if that part
+                                              comes last */
+   ){
+       float reverseDecresidual[BLOCKL_MAX], mem[CB_MEML];
+       int k, meml_gotten, Nfor, Nback, i;
+       int diff, start_pos;
+       int subcount, subframe;
+
+
+
+
+
+
+       diff = STATE_LEN - iLBCdec_inst->state_short_len;
+
+       if (state_first == 1) {
+           start_pos = (start-1)*SUBL;
+       } else {
+           start_pos = (start-1)*SUBL + diff;
+       }
+
+       /* decode scalar part of start state */
+
+       StateConstructW(idxForMax, idxVec,
+           &syntdenum[(start-1)*(LPC_FILTERORDER+1)],
+           &decresidual[start_pos], iLBCdec_inst->state_short_len);
+
+
+       if (state_first) { /* put adaptive part in the end */
+
+           /* setup memory */
+
+           memset(mem, 0,
+               (CB_MEML-iLBCdec_inst->state_short_len)*sizeof(float));
+           memcpy(mem+CB_MEML-iLBCdec_inst->state_short_len,
+               decresidual+start_pos,
+               iLBCdec_inst->state_short_len*sizeof(float));
+
+           /* construct decoded vector */
+
+           iCBConstruct(
+               &decresidual[start_pos+iLBCdec_inst->state_short_len],
+               extra_cb_index, extra_gain_index, mem+CB_MEML-stMemLTbl,
+               stMemLTbl, diff, CB_NSTAGES);
+
+       }
+       else {/* put adaptive part in the beginning */
+
+           /* create reversed vectors for prediction */
+
+           for (k=0; k<diff; k++) {
+               reverseDecresidual[k] =
+                   decresidual[(start+1)*SUBL-1-
+                           (k+iLBCdec_inst->state_short_len)];
+           }
+
+           /* setup memory */
+
+           meml_gotten = iLBCdec_inst->state_short_len;
+           for (k=0; k<meml_gotten; k++){
+               mem[CB_MEML-1-k] = decresidual[start_pos + k];
+
+
+
+
+
+           }
+           memset(mem, 0, (CB_MEML-k)*sizeof(float));
+
+           /* construct decoded vector */
+
+           iCBConstruct(reverseDecresidual, extra_cb_index,
+               extra_gain_index, mem+CB_MEML-stMemLTbl, stMemLTbl,
+               diff, CB_NSTAGES);
+
+           /* get decoded residual from reversed vector */
+
+           for (k=0; k<diff; k++) {
+               decresidual[start_pos-1-k] = reverseDecresidual[k];
+           }
+       }
+
+       /* counter for predicted sub-frames */
+
+       subcount=0;
+
+       /* forward prediction of sub-frames */
+
+       Nfor = iLBCdec_inst->nsub-start-1;
+
+       if ( Nfor > 0 ){
+
+           /* setup memory */
+
+           memset(mem, 0, (CB_MEML-STATE_LEN)*sizeof(float));
+           memcpy(mem+CB_MEML-STATE_LEN, decresidual+(start-1)*SUBL,
+               STATE_LEN*sizeof(float));
+
+           /* loop over sub-frames to encode */
+
+           for (subframe=0; subframe<Nfor; subframe++) {
+
+               /* construct decoded vector */
+
+               iCBConstruct(&decresidual[(start+1+subframe)*SUBL],
+                   cb_index+subcount*CB_NSTAGES,
+                   gain_index+subcount*CB_NSTAGES,
+                   mem+CB_MEML-memLfTbl[subcount],
+                   memLfTbl[subcount], SUBL, CB_NSTAGES);
+
+               /* update memory */
+
+               memcpy(mem, mem+SUBL, (CB_MEML-SUBL)*sizeof(float));
+               memcpy(mem+CB_MEML-SUBL,
+
+
+
+
+
+                   &decresidual[(start+1+subframe)*SUBL],
+                   SUBL*sizeof(float));
+
+               subcount++;
+
+           }
+
+       }
+
+       /* backward prediction of sub-frames */
+
+       Nback = start-1;
+
+       if ( Nback > 0 ) {
+
+           /* setup memory */
+
+           meml_gotten = SUBL*(iLBCdec_inst->nsub+1-start);
+
+           if ( meml_gotten > CB_MEML ) {
+               meml_gotten=CB_MEML;
+           }
+           for (k=0; k<meml_gotten; k++) {
+               mem[CB_MEML-1-k] = decresidual[(start-1)*SUBL + k];
+           }
+           memset(mem, 0, (CB_MEML-k)*sizeof(float));
+
+           /* loop over subframes to decode */
+
+           for (subframe=0; subframe<Nback; subframe++) {
+
+               /* construct decoded vector */
+
+               iCBConstruct(&reverseDecresidual[subframe*SUBL],
+                   cb_index+subcount*CB_NSTAGES,
+                   gain_index+subcount*CB_NSTAGES,
+                   mem+CB_MEML-memLfTbl[subcount], memLfTbl[subcount],
+                   SUBL, CB_NSTAGES);
+
+               /* update memory */
+
+               memcpy(mem, mem+SUBL, (CB_MEML-SUBL)*sizeof(float));
+               memcpy(mem+CB_MEML-SUBL,
+                   &reverseDecresidual[subframe*SUBL],
+                   SUBL*sizeof(float));
+
+               subcount++;
+           }
+
+
+
+
+
+           /* get decoded residual from reversed vector */
+
+           for (i=0; i<SUBL*Nback; i++)
+               decresidual[SUBL*Nback - i - 1] =
+               reverseDecresidual[i];
+       }
+   }
+
+   /*----------------------------------------------------------------*
+    *  main decoder function
+    *---------------------------------------------------------------*/
+
+   void iLBC_decode(
+       float *decblock,            /* (o) decoded signal block */
+       unsigned char *bytes,           /* (i) encoded signal bits */
+       iLBC_Dec_Inst_t *iLBCdec_inst,  /* (i/o) the decoder state
+                                                structure */
+       int mode                    /* (i) 0: bad packet, PLC,
+                                              1: normal */
+   ){
+       float data[BLOCKL_MAX];
+       float lsfdeq[LPC_FILTERORDER*LPC_N_MAX];
+       float PLCresidual[BLOCKL_MAX], PLClpc[LPC_FILTERORDER + 1];
+       float zeros[BLOCKL_MAX], one[LPC_FILTERORDER + 1];
+       int k, i, start, idxForMax, pos, lastpart, ulp;
+       int lag, ilag;
+       float cc, maxcc;
+       int idxVec[STATE_LEN];
+       int check;
+       int gain_index[NASUB_MAX*CB_NSTAGES],
+           extra_gain_index[CB_NSTAGES];
+       int cb_index[CB_NSTAGES*NASUB_MAX], extra_cb_index[CB_NSTAGES];
+       int lsf_i[LSF_NSPLIT*LPC_N_MAX];
+       int state_first;
+       int last_bit;
+       unsigned char *pbytes;
+       float weightdenum[(LPC_FILTERORDER + 1)*NSUB_MAX];
+       int order_plus_one;
+       float syntdenum[NSUB_MAX*(LPC_FILTERORDER+1)];
+       float decresidual[BLOCKL_MAX];
+
+       if (mode>0) { /* the data are good */
+
+           /* decode data */
+
+           pbytes=bytes;
+           pos=0;
+
+
+
+
+
+
+           /* Set everything to zero before decoding */
+
+           for (k=0; k<LSF_NSPLIT*LPC_N_MAX; k++) {
+               lsf_i[k]=0;
+           }
+           start=0;
+           state_first=0;
+           idxForMax=0;
+           for (k=0; k<iLBCdec_inst->state_short_len; k++) {
+               idxVec[k]=0;
+           }
+           for (k=0; k<CB_NSTAGES; k++) {
+               extra_cb_index[k]=0;
+           }
+           for (k=0; k<CB_NSTAGES; k++) {
+               extra_gain_index[k]=0;
+           }
+           for (i=0; i<iLBCdec_inst->nasub; i++) {
+               for (k=0; k<CB_NSTAGES; k++) {
+                   cb_index[i*CB_NSTAGES+k]=0;
+               }
+           }
+           for (i=0; i<iLBCdec_inst->nasub; i++) {
+               for (k=0; k<CB_NSTAGES; k++) {
+                   gain_index[i*CB_NSTAGES+k]=0;
+               }
+           }
+
+           /* loop over ULP classes */
+
+           for (ulp=0; ulp<3; ulp++) {
+
+               /* LSF */
+               for (k=0; k<LSF_NSPLIT*iLBCdec_inst->lpc_n; k++){
+                   unpack( &pbytes, &lastpart,
+                       iLBCdec_inst->ULP_inst->lsf_bits[k][ulp], &pos);
+                   packcombine(&lsf_i[k], lastpart,
+                       iLBCdec_inst->ULP_inst->lsf_bits[k][ulp]);
+               }
+
+               /* Start block info */
+
+               unpack( &pbytes, &lastpart,
+                   iLBCdec_inst->ULP_inst->start_bits[ulp], &pos);
+               packcombine(&start, lastpart,
+                   iLBCdec_inst->ULP_inst->start_bits[ulp]);
+
+               unpack( &pbytes, &lastpart,
+
+
+
+
+
+                   iLBCdec_inst->ULP_inst->startfirst_bits[ulp], &pos);
+               packcombine(&state_first, lastpart,
+                   iLBCdec_inst->ULP_inst->startfirst_bits[ulp]);
+
+               unpack( &pbytes, &lastpart,
+                   iLBCdec_inst->ULP_inst->scale_bits[ulp], &pos);
+               packcombine(&idxForMax, lastpart,
+                   iLBCdec_inst->ULP_inst->scale_bits[ulp]);
+
+               for (k=0; k<iLBCdec_inst->state_short_len; k++) {
+                   unpack( &pbytes, &lastpart,
+                       iLBCdec_inst->ULP_inst->state_bits[ulp], &pos);
+                   packcombine(idxVec+k, lastpart,
+                       iLBCdec_inst->ULP_inst->state_bits[ulp]);
+               }
+
+               /* 23/22 (20ms/30ms) sample block */
+
+               for (k=0; k<CB_NSTAGES; k++) {
+                   unpack( &pbytes, &lastpart,
+                       iLBCdec_inst->ULP_inst->extra_cb_index[k][ulp],
+                       &pos);
+                   packcombine(extra_cb_index+k, lastpart,
+                       iLBCdec_inst->ULP_inst->extra_cb_index[k][ulp]);
+               }
+               for (k=0; k<CB_NSTAGES; k++) {
+                   unpack( &pbytes, &lastpart,
+                       iLBCdec_inst->ULP_inst->extra_cb_gain[k][ulp],
+                       &pos);
+                   packcombine(extra_gain_index+k, lastpart,
+                       iLBCdec_inst->ULP_inst->extra_cb_gain[k][ulp]);
+               }
+
+               /* The two/four (20ms/30ms) 40 sample sub-blocks */
+
+               for (i=0; i<iLBCdec_inst->nasub; i++) {
+                   for (k=0; k<CB_NSTAGES; k++) {
+                       unpack( &pbytes, &lastpart,
+                       iLBCdec_inst->ULP_inst->cb_index[i][k][ulp],
+                           &pos);
+                       packcombine(cb_index+i*CB_NSTAGES+k, lastpart,
+                       iLBCdec_inst->ULP_inst->cb_index[i][k][ulp]);
+                   }
+               }
+
+               for (i=0; i<iLBCdec_inst->nasub; i++) {
+                   for (k=0; k<CB_NSTAGES; k++) {
+                       unpack( &pbytes, &lastpart,
+
+
+
+
+
+                       iLBCdec_inst->ULP_inst->cb_gain[i][k][ulp],
+                           &pos);
+                       packcombine(gain_index+i*CB_NSTAGES+k, lastpart,
+                           iLBCdec_inst->ULP_inst->cb_gain[i][k][ulp]);
+                   }
+               }
+           }
+           /* Extract last bit. If it is 1 this indicates an
+              empty/lost frame */
+           unpack( &pbytes, &last_bit, 1, &pos);
+
+           /* Check for bit errors or empty/lost frames */
+           if (start<1)
+               mode = 0;
+           if (iLBCdec_inst->mode==20 && start>3)
+               mode = 0;
+           if (iLBCdec_inst->mode==30 && start>5)
+               mode = 0;
+           if (last_bit==1)
+               mode = 0;
+
+           if (mode==1) { /* No bit errors was detected,
+                             continue decoding */
+
+               /* adjust index */
+               index_conv_dec(cb_index);
+
+               /* decode the lsf */
+
+               SimplelsfDEQ(lsfdeq, lsf_i, iLBCdec_inst->lpc_n);
+               check=LSF_check(lsfdeq, LPC_FILTERORDER,
+                   iLBCdec_inst->lpc_n);
+               DecoderInterpolateLSF(syntdenum, weightdenum,
+                   lsfdeq, LPC_FILTERORDER, iLBCdec_inst);
+
+               Decode(iLBCdec_inst, decresidual, start, idxForMax,
+                   idxVec, syntdenum, cb_index, gain_index,
+                   extra_cb_index, extra_gain_index,
+                   state_first);
+
+               /* preparing the plc for a future loss! */
+
+               doThePLC(PLCresidual, PLClpc, 0, decresidual,
+                   syntdenum +
+                   (LPC_FILTERORDER + 1)*(iLBCdec_inst->nsub - 1),
+                   (*iLBCdec_inst).last_lag, iLBCdec_inst);
+
+
+
+
+
+
+
+               memcpy(decresidual, PLCresidual,
+                   iLBCdec_inst->blockl*sizeof(float));
+           }
+
+       }
+
+       if (mode == 0) {
+           /* the data is bad (either a PLC call
+            * was made or a severe bit error was detected)
+            */
+
+           /* packet loss conceal */
+
+           memset(zeros, 0, BLOCKL_MAX*sizeof(float));
+
+           one[0] = 1;
+           memset(one+1, 0, LPC_FILTERORDER*sizeof(float));
+
+           start=0;
+
+           doThePLC(PLCresidual, PLClpc, 1, zeros, one,
+               (*iLBCdec_inst).last_lag, iLBCdec_inst);
+           memcpy(decresidual, PLCresidual,
+               iLBCdec_inst->blockl*sizeof(float));
+
+           order_plus_one = LPC_FILTERORDER + 1;
+           for (i = 0; i < iLBCdec_inst->nsub; i++) {
+               memcpy(syntdenum+(i*order_plus_one), PLClpc,
+                   order_plus_one*sizeof(float));
+           }
+       }
+
+       if (iLBCdec_inst->use_enhancer == 1) {
+
+           /* post filtering */
+
+           iLBCdec_inst->last_lag =
+               enhancerInterface(data, decresidual, iLBCdec_inst);
+
+           /* synthesis filtering */
+
+           if (iLBCdec_inst->mode==20) {
+               /* Enhancer has 40 samples delay */
+               i=0;
+               syntFilter(data + i*SUBL,
+                   iLBCdec_inst->old_syntdenum +
+                   (i+iLBCdec_inst->nsub-1)*(LPC_FILTERORDER+1),
+                   SUBL, iLBCdec_inst->syntMem);
+
+
+
+
+
+               for (i=1; i < iLBCdec_inst->nsub; i++) {
+                   syntFilter(data + i*SUBL,
+                       syntdenum + (i-1)*(LPC_FILTERORDER+1),
+                       SUBL, iLBCdec_inst->syntMem);
+               }
+           } else if (iLBCdec_inst->mode==30) {
+               /* Enhancer has 80 samples delay */
+               for (i=0; i < 2; i++) {
+                   syntFilter(data + i*SUBL,
+                       iLBCdec_inst->old_syntdenum +
+                       (i+iLBCdec_inst->nsub-2)*(LPC_FILTERORDER+1),
+                       SUBL, iLBCdec_inst->syntMem);
+               }
+               for (i=2; i < iLBCdec_inst->nsub; i++) {
+                   syntFilter(data + i*SUBL,
+                       syntdenum + (i-2)*(LPC_FILTERORDER+1), SUBL,
+                       iLBCdec_inst->syntMem);
+               }
+           }
+
+       } else {
+
+           /* Find last lag */
+           lag = 20;
+           maxcc = xCorrCoef(&decresidual[BLOCKL_MAX-ENH_BLOCKL],
+               &decresidual[BLOCKL_MAX-ENH_BLOCKL-lag], ENH_BLOCKL);
+
+           for (ilag=21; ilag<120; ilag++) {
+               cc = xCorrCoef(&decresidual[BLOCKL_MAX-ENH_BLOCKL],
+                   &decresidual[BLOCKL_MAX-ENH_BLOCKL-ilag],
+                   ENH_BLOCKL);
+
+               if (cc > maxcc) {
+                   maxcc = cc;
+                   lag = ilag;
+               }
+           }
+           iLBCdec_inst->last_lag = lag;
+
+           /* copy data and run synthesis filter */
+
+           memcpy(data, decresidual,
+               iLBCdec_inst->blockl*sizeof(float));
+           for (i=0; i < iLBCdec_inst->nsub; i++) {
+               syntFilter(data + i*SUBL,
+                   syntdenum + i*(LPC_FILTERORDER+1), SUBL,
+                   iLBCdec_inst->syntMem);
+           }
+
+
+
+
+
+       }
+
+       /* high pass filtering on output if desired, otherwise
+          copy to out */
+
+       hpOutput(data, iLBCdec_inst->blockl,
+                   decblock,iLBCdec_inst->hpomem);
+
+       /* memcpy(decblock,data,iLBCdec_inst->blockl*sizeof(float));*/
+
+       memcpy(iLBCdec_inst->old_syntdenum, syntdenum,
+
+           iLBCdec_inst->nsub*(LPC_FILTERORDER+1)*sizeof(float));
+
+       iLBCdec_inst->prev_enh_pl=0;
+
+       if (mode==0) { /* PLC was used */
+           iLBCdec_inst->prev_enh_pl=1;
+       }
+   }
+
diff --git a/jni/pjproject-android/.svn/pristine/db/db1f9e05360c01c45f2c1bd1d97ae7a537cf3ddc.svn-base b/jni/pjproject-android/.svn/pristine/db/db1f9e05360c01c45f2c1bd1d97ae7a537cf3ddc.svn-base
new file mode 100644
index 0000000..74ef08a
--- /dev/null
+++ b/jni/pjproject-android/.svn/pristine/db/db1f9e05360c01c45f2c1bd1d97ae7a537cf3ddc.svn-base
@@ -0,0 +1,4763 @@
+/* $Id$ */
+/* 
+ * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
+ * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
+ */
+#include <pjsip-ua/sip_inv.h>
+#include <pjsip-ua/sip_100rel.h>
+#include <pjsip-ua/sip_timer.h>
+#include <pjsip/sip_module.h>
+#include <pjsip/sip_endpoint.h>
+#include <pjsip/sip_event.h>
+#include <pjsip/sip_multipart.h>
+#include <pjsip/sip_transaction.h>
+#include <pjmedia/sdp.h>
+#include <pjmedia/sdp_neg.h>
+#include <pjmedia/errno.h>
+#include <pj/string.h>
+#include <pj/pool.h>
+#include <pj/assert.h>
+#include <pj/os.h>
+#include <pj/log.h>
+#include <pj/rand.h>
+
+/* 
+ * Note on offer/answer:
+ *
+ * The offer/answer framework in this implementation assumes the occurence
+ * of SDP in a particular request/response according to this table:
+
+		  offer   answer    Note:
+    ========================================================================
+    INVITE	    X		    INVITE may contain offer
+    18x/INVITE	    X	    X	    Response may contain offer or answer
+    2xx/INVITE	    X	    X	    Response may contain offer or answer
+    ACK			    X	    ACK may contain answer
+
+    PRACK		    X	    PRACK can only contain answer
+    2xx/PRACK	    		    Response may not have offer nor answer
+
+    UPDATE	    X		    UPDATE may only contain offer
+    2xx/UPDATE		    X	    Response may only contain answer
+    ========================================================================
+
+  *
+  */
+
+#define THIS_FILE	"sip_inv.c"
+
+static const char *inv_state_names[] =
+{
+    "NULL",
+    "CALLING",
+    "INCOMING",
+    "EARLY",
+    "CONNECTING",
+    "CONFIRMED",
+    "DISCONNCTD",
+    "TERMINATED",
+};
+
+/* UPDATE method */
+static const pjsip_method pjsip_update_method =
+{
+    PJSIP_OTHER_METHOD,
+    { "UPDATE", 6 }
+};
+
+#define POOL_INIT_SIZE	256
+#define POOL_INC_SIZE	256
+
+/*
+ * Static prototypes.
+ */
+static pj_status_t mod_inv_load(pjsip_endpoint *endpt);
+static pj_status_t mod_inv_unload(void);
+static pj_bool_t   mod_inv_on_rx_request(pjsip_rx_data *rdata);
+static pj_bool_t   mod_inv_on_rx_response(pjsip_rx_data *rdata);
+static void	   mod_inv_on_tsx_state(pjsip_transaction*, pjsip_event*);
+
+static void inv_on_state_null( pjsip_inv_session *inv, pjsip_event *e);
+static void inv_on_state_calling( pjsip_inv_session *inv, pjsip_event *e);
+static void inv_on_state_incoming( pjsip_inv_session *inv, pjsip_event *e);
+static void inv_on_state_early( pjsip_inv_session *inv, pjsip_event *e);
+static void inv_on_state_connecting( pjsip_inv_session *inv, pjsip_event *e);
+static void inv_on_state_confirmed( pjsip_inv_session *inv, pjsip_event *e);
+static void inv_on_state_disconnected( pjsip_inv_session *inv, pjsip_event *e);
+
+static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv,
+						  pjsip_transaction *tsx,
+						  pjsip_rx_data *rdata);
+static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv );
+static pjsip_msg_body *create_sdp_body(pj_pool_t *pool,
+				       const pjmedia_sdp_session *c_sdp);
+static pj_status_t process_answer( pjsip_inv_session *inv,
+				   int st_code,
+				   pjsip_tx_data *tdata,
+				   const pjmedia_sdp_session *local_sdp);
+
+static pj_status_t handle_timer_response(pjsip_inv_session *inv,
+				         const pjsip_rx_data *rdata,
+				         pj_bool_t end_sess_on_failure);
+
+static void (*inv_state_handler[])( pjsip_inv_session *inv, pjsip_event *e) = 
+{
+    &inv_on_state_null,
+    &inv_on_state_calling,
+    &inv_on_state_incoming,
+    &inv_on_state_early,
+    &inv_on_state_connecting,
+    &inv_on_state_confirmed,
+    &inv_on_state_disconnected,
+};
+
+static struct mod_inv
+{
+    pjsip_module	 mod;
+    pjsip_endpoint	*endpt;
+    pjsip_inv_callback	 cb;
+} mod_inv = 
+{
+    {
+	NULL, NULL,			    /* prev, next.		*/
+	{ "mod-invite", 10 },		    /* Name.			*/
+	-1,				    /* Id			*/
+	PJSIP_MOD_PRIORITY_DIALOG_USAGE,    /* Priority			*/
+	&mod_inv_load,			    /* load()			*/
+	NULL,				    /* start()			*/
+	NULL,				    /* stop()			*/
+	&mod_inv_unload,		    /* unload()			*/
+	&mod_inv_on_rx_request,		    /* on_rx_request()		*/
+	&mod_inv_on_rx_response,	    /* on_rx_response()		*/
+	NULL,				    /* on_tx_request.		*/
+	NULL,				    /* on_tx_response()		*/
+	&mod_inv_on_tsx_state,		    /* on_tsx_state()		*/
+    }
+};
+
+
+/* Invite session data to be attached to transaction. */
+struct tsx_inv_data
+{
+    pjsip_inv_session	*inv;	    /* The invite session		    */
+    pj_bool_t		 sdp_done;  /* SDP negotiation done for this tsx?   */
+    pj_bool_t		 retrying;  /* Resend (e.g. due to 401/407)         */
+    pj_str_t		 done_tag;  /* To tag in RX response with answer    */
+    pj_bool_t		 done_early;/* Negotiation was done for early med?  */
+};
+
+/*
+ * Module load()
+ */
+static pj_status_t mod_inv_load(pjsip_endpoint *endpt)
+{
+    pj_str_t allowed[] = {{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6},
+			    { "UPDATE", 6}};
+    pj_str_t accepted = { "application/sdp", 15 };
+
+    /* Register supported methods: INVITE, ACK, BYE, CANCEL, UPDATE */
+    pjsip_endpt_add_capability(endpt, &mod_inv.mod, PJSIP_H_ALLOW, NULL,
+			       PJ_ARRAY_SIZE(allowed), allowed);
+
+    /* Register "application/sdp" in Accept header */
+    pjsip_endpt_add_capability(endpt, &mod_inv.mod, PJSIP_H_ACCEPT, NULL,
+			       1, &accepted);
+
+    return PJ_SUCCESS;
+}
+
+/*
+ * Module unload()
+ */
+static pj_status_t mod_inv_unload(void)
+{
+    /* Should remove capability here */
+    return PJ_SUCCESS;
+}
+
+/*
+ * Set session state.
+ */
+void inv_set_state(pjsip_inv_session *inv, pjsip_inv_state state,
+		   pjsip_event *e)
+{
+    pjsip_inv_state prev_state = inv->state;
+    pj_bool_t dont_notify = PJ_FALSE;
+    pj_status_t status;
+
+    /* Prevent STATE_CALLING from being reported more than once because
+     * of authentication
+     * https://trac.pjsip.org/repos/ticket/1318
+     */
+    if (state==PJSIP_INV_STATE_CALLING && 
+	(inv->cb_called & (1 << PJSIP_INV_STATE_CALLING)) != 0)
+    {
+	dont_notify = PJ_TRUE;
+    }
+
+    /* If state is confirmed, check that SDP negotiation is done,
+     * otherwise disconnect the session.
+     */
+    if (state == PJSIP_INV_STATE_CONFIRMED) {
+	struct tsx_inv_data *tsx_inv_data = NULL;
+
+	if (inv->invite_tsx) {
+	    tsx_inv_data = (struct tsx_inv_data*)
+			   inv->invite_tsx->mod_data[mod_inv.mod.id];
+	}
+
+	if (pjmedia_sdp_neg_get_state(inv->neg)!=PJMEDIA_SDP_NEG_STATE_DONE &&
+	    (tsx_inv_data && !tsx_inv_data->sdp_done) )
+	{
+	    pjsip_tx_data *bye;
+
+	    PJ_LOG(4,(inv->obj_name, "SDP offer/answer incomplete, ending the "
+		      "session"));
+
+	    status = pjsip_inv_end_session(inv, PJSIP_SC_NOT_ACCEPTABLE, 
+					   NULL, &bye);
+	    if (status == PJ_SUCCESS && bye)
+		status = pjsip_inv_send_msg(inv, bye);
+
+	    return;
+	}
+    }
+
+    /* Set state. */
+    inv->state = state;
+
+    /* If state is DISCONNECTED, cause code MUST have been set. */
+    pj_assert(inv->state != PJSIP_INV_STATE_DISCONNECTED ||
+	      inv->cause != 0);
+
+    /* Mark the callback as called for this state */
+    inv->cb_called |= (1 << state);
+
+    /* Call on_state_changed() callback. */
+    if (mod_inv.cb.on_state_changed && inv->notify && !dont_notify)
+	(*mod_inv.cb.on_state_changed)(inv, e);
+
+    /* Only decrement when previous state is not already DISCONNECTED */
+    if (inv->state == PJSIP_INV_STATE_DISCONNECTED &&
+	prev_state != PJSIP_INV_STATE_DISCONNECTED) 
+    {
+	if (inv->last_ack) {
+	    pjsip_tx_data_dec_ref(inv->last_ack);
+	    inv->last_ack = NULL;
+	}
+	if (inv->invite_req) {
+	    pjsip_tx_data_dec_ref(inv->invite_req);
+	    inv->invite_req = NULL;
+	}
+	if (inv->pending_bye) {
+	    pjsip_tx_data_dec_ref(inv->pending_bye);
+	    inv->pending_bye = NULL;
+	}
+	pjsip_100rel_end_session(inv);
+	pjsip_timer_end_session(inv);
+	pjsip_dlg_dec_session(inv->dlg, &mod_inv.mod);
+
+	/* Release the flip-flop pools */
+	pj_pool_release(inv->pool_prov);
+	inv->pool_prov = NULL;
+	pj_pool_release(inv->pool_active);
+	inv->pool_active = NULL;
+    }
+}
+
+
+/*
+ * Set cause code.
+ */
+void inv_set_cause(pjsip_inv_session *inv, int cause_code,
+		   const pj_str_t *cause_text)
+{
+    if (cause_code > inv->cause) {
+	inv->cause = (pjsip_status_code) cause_code;
+	if (cause_text)
+	    pj_strdup(inv->pool, &inv->cause_text, cause_text);
+	else if (cause_code/100 == 2)
+	    inv->cause_text = pj_str("Normal call clearing");
+	else
+	    inv->cause_text = *pjsip_get_status_text(cause_code);
+    }
+}
+
+
+/*
+ * Check if outgoing request needs to have SDP answer.
+ * This applies for both ACK and PRACK requests.
+ */
+static const pjmedia_sdp_session *inv_has_pending_answer(pjsip_inv_session *inv,
+						         pjsip_transaction *tsx)
+{
+    pjmedia_sdp_neg_state neg_state;
+    const pjmedia_sdp_session *sdp = NULL;
+    pj_status_t status;
+
+    /* If SDP negotiator is ready, start negotiation. */
+
+    /* Start nego when appropriate. */
+    neg_state = inv->neg ? pjmedia_sdp_neg_get_state(inv->neg) :
+		PJMEDIA_SDP_NEG_STATE_NULL;
+
+    if (neg_state == PJMEDIA_SDP_NEG_STATE_DONE) {
+
+	/* Nothing to do */
+
+    } else if (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO &&
+	       pjmedia_sdp_neg_has_local_answer(inv->neg) )
+    {
+	struct tsx_inv_data *tsx_inv_data;
+	struct tsx_inv_data dummy;
+
+	/* Get invite session's transaction data.
+	 * Note that tsx may be NULL, for example when application sends
+	 * delayed ACK request (at this time, the original INVITE 
+	 * transaction may have been destroyed.
+	 */
+	if (tsx) {
+	    tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
+	} else {
+	    tsx_inv_data = &dummy;
+	    pj_bzero(&dummy, sizeof(dummy));
+	    dummy.inv = inv;
+	}
+
+	status = inv_negotiate_sdp(inv);
+	if (status != PJ_SUCCESS)
+	    return NULL;
+	
+	/* Mark this transaction has having SDP offer/answer done. */
+	tsx_inv_data->sdp_done = 1;
+
+	status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp);
+
+    } else {
+	/* This remark is only valid for ACK.
+	PJ_LOG(4,(inv->dlg->obj_name,
+		  "FYI, the SDP negotiator state (%s) is in a mess "
+		  "when sending this ACK/PRACK request",
+		  pjmedia_sdp_neg_state_str(neg_state)));
+	 */
+    }
+
+    return sdp;
+}
+
+/* Process pending disconnection
+ *  http://trac.pjsip.org/repos/ticket/1712
+ */
+static void inv_perform_pending_bye(pjsip_inv_session *inv)
+{
+    if (inv->pending_bye) {
+	pjsip_tx_data *bye = inv->pending_bye;
+	pj_status_t status;
+
+	PJ_LOG(4,(inv->dlg->obj_name, "Sending pending BYE"));
+
+	inv->pending_bye = NULL;
+	status = pjsip_inv_send_msg(inv, bye);
+
+	if (status != PJ_SUCCESS) {
+	    PJ_PERROR(1,(inv->dlg->obj_name, status,
+			 "Failed sending pending BYE"));
+	}
+    }
+}
+
+/*
+ * Send ACK for 2xx response.
+ */
+static pj_status_t inv_send_ack(pjsip_inv_session *inv, pjsip_event *e)
+{
+    pjsip_rx_data *rdata;
+    pjsip_event ack_e;
+    pj_status_t status;
+
+    if (e->type == PJSIP_EVENT_TSX_STATE)
+	rdata = e->body.tsx_state.src.rdata;
+    else if (e->type == PJSIP_EVENT_RX_MSG)
+	rdata = e->body.rx_msg.rdata;
+    else {
+	pj_assert(!"Unsupported event type");
+	return PJ_EBUG;
+    }
+
+    PJ_LOG(5,(inv->obj_name, "Received %s, sending ACK",
+	      pjsip_rx_data_get_info(rdata)));
+
+    /* Check if we have cached ACK request. Must not use the cached ACK
+     * if it's still marked as pending by transport (#1011)
+     */
+    if (inv->last_ack && rdata->msg_info.cseq->cseq == inv->last_ack_cseq &&
+	!inv->last_ack->is_pending)
+    {
+	pjsip_tx_data_add_ref(inv->last_ack);
+
+    } else if (mod_inv.cb.on_send_ack) {
+	/* If application handles ACK transmission manually, just notify the
+	 * callback
+	 */
+	PJ_LOG(5,(inv->obj_name, "Received %s, notifying application callback",
+		  pjsip_rx_data_get_info(rdata)));
+
+	(*mod_inv.cb.on_send_ack)(inv, rdata);
+	return PJ_SUCCESS;
+
+    } else {
+	status = pjsip_inv_create_ack(inv, rdata->msg_info.cseq->cseq,
+				      &inv->last_ack);
+	if (status != PJ_SUCCESS)
+	    return status;
+    }
+
+    PJSIP_EVENT_INIT_TX_MSG(ack_e, inv->last_ack);
+
+    /* Send ACK */
+    status = pjsip_dlg_send_request(inv->dlg, inv->last_ack, -1, NULL);
+    if (status != PJ_SUCCESS) {
+	/* Better luck next time */
+	pj_assert(!"Unable to send ACK!");
+	return status;
+    }
+
+
+    /* Set state to CONFIRMED (if we're not in CONFIRMED yet).
+     * But don't set it to CONFIRMED if we're already DISCONNECTED
+     * (this may have been a late 200/OK response.
+     */
+    if (inv->state < PJSIP_INV_STATE_CONFIRMED) {
+	inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &ack_e);
+    }
+
+    return PJ_SUCCESS;
+}
+
+/*
+ * Module on_rx_request()
+ *
+ * This callback is called for these events:
+ *  - endpoint receives request which was unhandled by higher priority
+ *    modules (e.g. transaction layer, dialog layer).
+ *  - dialog distributes incoming request to its usages.
+ */
+static pj_bool_t mod_inv_on_rx_request(pjsip_rx_data *rdata)
+{
+    pjsip_method *method;
+    pjsip_dialog *dlg;
+    pjsip_inv_session *inv;
+
+    /* Only wants to receive request from a dialog. */
+    dlg = pjsip_rdata_get_dlg(rdata);
+    if (dlg == NULL)
+	return PJ_FALSE;
+
+    inv = (pjsip_inv_session*) dlg->mod_data[mod_inv.mod.id];
+
+    /* Report to dialog that we handle INVITE, CANCEL, BYE, ACK. 
+     * If we need to send response, it will be sent in the state
+     * handlers.
+     */
+    method = &rdata->msg_info.msg->line.req.method;
+
+    if (method->id == PJSIP_INVITE_METHOD) {
+	return PJ_TRUE;
+    }
+
+    /* BYE and CANCEL must have existing invite session */
+    if (method->id == PJSIP_BYE_METHOD ||
+	method->id == PJSIP_CANCEL_METHOD)
+    {
+	if (inv == NULL)
+	    return PJ_FALSE;
+
+	return PJ_TRUE;
+    }
+
+    /* On receipt ACK request, when state is CONNECTING,
+     * move state to CONFIRMED.
+     */
+    if (method->id == PJSIP_ACK_METHOD && inv) {
+
+	/* Ignore if we don't have INVITE in progress */
+	if (!inv->invite_tsx) {
+	    return PJ_TRUE;
+	}
+
+	/* Ignore ACK if pending INVITE transaction has not finished. */
+	if (inv->invite_tsx->state < PJSIP_TSX_STATE_COMPLETED) {
+	    return PJ_TRUE;
+	}
+
+	/* Ignore ACK with different CSeq
+	 * https://trac.pjsip.org/repos/ticket/1391
+	 */
+	if (rdata->msg_info.cseq->cseq != inv->invite_tsx->cseq) {
+	    return PJ_TRUE;
+	}
+
+	/* Terminate INVITE transaction, if it's still present. */
+	if (inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED) {
+	    /* Before we terminate INVITE transaction, process the SDP
+	     * in the ACK request, if any. 
+	     * Only do this when invite state is not already disconnected
+	     * (http://trac.pjsip.org/repos/ticket/640).
+	     */
+	    if (inv->state < PJSIP_INV_STATE_DISCONNECTED) {
+		inv_check_sdp_in_incoming_msg(inv, inv->invite_tsx, rdata);
+
+		/* Check if local offer got no SDP answer and INVITE session
+		 * is in CONFIRMED state.
+		 */
+		if (pjmedia_sdp_neg_get_state(inv->neg)==
+		    PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER &&
+		    inv->state==PJSIP_INV_STATE_CONFIRMED)
+		{
+		    pjmedia_sdp_neg_cancel_offer(inv->neg);
+		}
+	    }
+
+	    /* Now we can terminate the INVITE transaction */
+	    pj_assert(inv->invite_tsx->status_code >= 200);
+	    pjsip_tsx_terminate(inv->invite_tsx, 
+				inv->invite_tsx->status_code);
+	    inv->invite_tsx = NULL;
+	    if (inv->last_answer) {
+		    pjsip_tx_data_dec_ref(inv->last_answer);
+		    inv->last_answer = NULL;
+	    }
+	}
+
+	/* On receipt of ACK, only set state to confirmed when state
+	 * is CONNECTING (e.g. we don't want to set the state to confirmed
+	 * when we receive ACK retransmission after sending non-2xx!)
+	 */
+	if (inv->state == PJSIP_INV_STATE_CONNECTING) {
+	    pjsip_event event;
+
+	    PJSIP_EVENT_INIT_RX_MSG(event, rdata);
+	    inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &event);
+
+	    /* Send pending BYE if any:
+	     *   http://trac.pjsip.org/repos/ticket/1712
+	     * Do this after setting the state to CONFIRMED, so that we
+	     * have consistent CONFIRMED state between caller and callee.
+	     */
+	    if (inv->pending_bye)
+		inv_perform_pending_bye(inv);
+	}
+    }
+
+    return PJ_FALSE;
+}
+
+/* This function will process Session Timer headers in received 
+ * 2xx or 422 response of INVITE/UPDATE request.
+ */
+static pj_status_t handle_timer_response(pjsip_inv_session *inv,
+				         const pjsip_rx_data *rdata,
+					 pj_bool_t end_sess_on_failure)
+{
+    pjsip_status_code st_code;
+    pj_status_t status;
+
+    status = pjsip_timer_process_resp(inv, rdata, &st_code);
+    if (status != PJ_SUCCESS && end_sess_on_failure) {
+	pjsip_tx_data *tdata;
+	pj_status_t status2;
+
+	status2 = pjsip_inv_end_session(inv, st_code, NULL, &tdata);
+	if (tdata && status2 == PJ_SUCCESS)
+	    pjsip_inv_send_msg(inv, tdata);
+    }
+
+    return status;
+}
+
+/*
+ * Module on_rx_response().
+ *
+ * This callback is called for these events:
+ *  - dialog distributes incoming 2xx response to INVITE (outside
+ *    transaction) to its usages.
+ *  - endpoint distributes strayed responses.
+ */
+static pj_bool_t mod_inv_on_rx_response(pjsip_rx_data *rdata)
+{
+    pjsip_dialog *dlg;
+    pjsip_inv_session *inv;
+    pjsip_msg *msg = rdata->msg_info.msg;
+
+    dlg = pjsip_rdata_get_dlg(rdata);
+
+    /* Ignore responses outside dialog */
+    if (dlg == NULL)
+	return PJ_FALSE;
+
+    /* Ignore responses not belonging to invite session */
+    inv = pjsip_dlg_get_inv_session(dlg);
+    if (inv == NULL)
+	return PJ_FALSE;
+
+    /* This MAY be retransmission of 2xx response to INVITE. 
+     * If it is, we need to send ACK.
+     */
+    if (msg->type == PJSIP_RESPONSE_MSG && msg->line.status.code/100==2 &&
+	rdata->msg_info.cseq->method.id == PJSIP_INVITE_METHOD &&
+	inv->invite_tsx == NULL) 
+    {
+	pjsip_event e;
+
+	PJSIP_EVENT_INIT_RX_MSG(e, rdata);
+	inv_send_ack(inv, &e);
+	return PJ_TRUE;
+
+    }
+
+    /* No other processing needs to be done here. */
+    return PJ_FALSE;
+}
+
+/*
+ * Module on_tsx_state()
+ *
+ * This callback is called by dialog framework for all transactions
+ * inside the dialog for all its dialog usages.
+ */
+static void mod_inv_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e)
+{
+    pjsip_dialog *dlg;
+    pjsip_inv_session *inv;
+
+    dlg = pjsip_tsx_get_dlg(tsx);
+    if (dlg == NULL)
+	return;
+
+    inv = pjsip_dlg_get_inv_session(dlg);
+    if (inv == NULL)
+	return;
+
+    /* Call state handler for the invite session. */
+    (*inv_state_handler[inv->state])(inv, e);
+
+    /* Call on_tsx_state. CANCEL request is a special case and has been
+     * reported earlier in inv_respond_incoming_cancel()
+     */
+    if (mod_inv.cb.on_tsx_state_changed && inv->notify &&
+        !(tsx->method.id==PJSIP_CANCEL_METHOD &&
+          e->body.tsx_state.type==PJSIP_EVENT_RX_MSG))
+    {
+	(*mod_inv.cb.on_tsx_state_changed)(inv, tsx, e);
+    }
+
+    /* Clear invite transaction when tsx is confirmed.
+     * Previously we set invite_tsx to NULL only when transaction has
+     * terminated, but this didn't work when ACK has the same Via branch
+     * value as the INVITE (see http://www.pjsip.org/trac/ticket/113)
+     */
+    if (tsx->state>=PJSIP_TSX_STATE_CONFIRMED && tsx == inv->invite_tsx) {
+        inv->invite_tsx = NULL;
+	if (inv->last_answer) {
+		pjsip_tx_data_dec_ref(inv->last_answer);
+		inv->last_answer = NULL;
+	}
+    }
+}
+
+
+/*
+ * Initialize the invite module.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_usage_init( pjsip_endpoint *endpt,
+					  const pjsip_inv_callback *cb)
+{
+    pj_status_t status;
+
+    /* Check arguments. */
+    PJ_ASSERT_RETURN(endpt && cb, PJ_EINVAL);
+
+    /* Some callbacks are mandatory */
+    PJ_ASSERT_RETURN(cb->on_state_changed && cb->on_new_session, PJ_EINVAL);
+
+    /* Check if module already registered. */
+    PJ_ASSERT_RETURN(mod_inv.mod.id == -1, PJ_EINVALIDOP);
+
+    /* Copy param. */
+    pj_memcpy(&mod_inv.cb, cb, sizeof(pjsip_inv_callback));
+
+    mod_inv.endpt = endpt;
+
+    /* Register the module. */
+    status = pjsip_endpt_register_module(endpt, &mod_inv.mod);
+    if (status != PJ_SUCCESS)
+	return status;
+
+    return PJ_SUCCESS;
+}
+
+/*
+ * Get the instance of invite module.
+ */
+PJ_DEF(pjsip_module*) pjsip_inv_usage_instance(void)
+{
+    return &mod_inv.mod;
+}
+
+
+
+/*
+ * Return the invite session for the specified dialog.
+ */
+PJ_DEF(pjsip_inv_session*) pjsip_dlg_get_inv_session(pjsip_dialog *dlg)
+{
+    return (pjsip_inv_session*) dlg->mod_data[mod_inv.mod.id];
+}
+
+
+/*
+ * Get INVITE state name.
+ */
+PJ_DEF(const char *) pjsip_inv_state_name(pjsip_inv_state state)
+{
+    PJ_ASSERT_RETURN(state >= PJSIP_INV_STATE_NULL && 
+		     state <= PJSIP_INV_STATE_DISCONNECTED,
+		     "??");
+
+    return inv_state_names[state];
+}
+
+/*
+ * Create UAC invite session.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_create_uac( pjsip_dialog *dlg,
+					  const pjmedia_sdp_session *local_sdp,
+					  unsigned options,
+					  pjsip_inv_session **p_inv)
+{
+    pjsip_inv_session *inv;
+    pj_status_t status;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(dlg && p_inv, PJ_EINVAL);
+
+    /* Must lock dialog first */
+    pjsip_dlg_inc_lock(dlg);
+
+    /* Normalize options */
+    if (options & PJSIP_INV_REQUIRE_100REL)
+	options |= PJSIP_INV_SUPPORT_100REL;
+    if (options & PJSIP_INV_REQUIRE_TIMER)
+	options |= PJSIP_INV_SUPPORT_TIMER;
+
+    /* Create the session */
+    inv = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_inv_session);
+    pj_assert(inv != NULL);
+
+    inv->pool = dlg->pool;
+    inv->role = PJSIP_ROLE_UAC;
+    inv->state = PJSIP_INV_STATE_NULL;
+    inv->dlg = dlg;
+    inv->options = options;
+    inv->notify = PJ_TRUE;
+    inv->cause = (pjsip_status_code) 0;
+
+    /* Create flip-flop pool (see ticket #877) */
+    /* (using inv->obj_name as temporary variable for pool names */
+    pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg->pool);
+    inv->pool_prov = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name,
+					     POOL_INIT_SIZE, POOL_INC_SIZE);
+    inv->pool_active = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name,
+					       POOL_INIT_SIZE, POOL_INC_SIZE);
+
+    /* Object name will use the same dialog pointer. */
+    pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg);
+
+    /* Create negotiator if local_sdp is specified. */
+    if (local_sdp) {
+	status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, 
+						      local_sdp, &inv->neg);
+	if (status != PJ_SUCCESS) {
+	    pjsip_dlg_dec_lock(dlg);
+	    return status;
+	}
+    }
+
+    /* Register invite as dialog usage. */
+    status = pjsip_dlg_add_usage(dlg, &mod_inv.mod, inv);
+    if (status != PJ_SUCCESS) {
+	pjsip_dlg_dec_lock(dlg);
+	return status;
+    }
+
+    /* Increment dialog session */
+    pjsip_dlg_inc_session(dlg, &mod_inv.mod);
+
+    /* Create 100rel handler */
+    pjsip_100rel_attach(inv);
+
+    /* Done */
+    *p_inv = inv;
+
+    pjsip_dlg_dec_lock(dlg);
+
+    PJ_LOG(5,(inv->obj_name, "UAC invite session created for dialog %s",
+	      dlg->obj_name));
+
+    return PJ_SUCCESS;
+}
+
+PJ_DEF(pjsip_rdata_sdp_info*) pjsip_rdata_get_sdp_info(pjsip_rx_data *rdata)
+{
+    pjsip_rdata_sdp_info *sdp_info;
+    pjsip_msg_body *body = rdata->msg_info.msg->body;
+    pjsip_ctype_hdr *ctype_hdr = rdata->msg_info.ctype;
+    pjsip_media_type app_sdp;
+
+    sdp_info = (pjsip_rdata_sdp_info*)
+	       rdata->endpt_info.mod_data[mod_inv.mod.id];
+    if (sdp_info)
+	return sdp_info;
+
+    sdp_info = PJ_POOL_ZALLOC_T(rdata->tp_info.pool,
+				pjsip_rdata_sdp_info);
+    PJ_ASSERT_RETURN(mod_inv.mod.id >= 0, sdp_info);
+    rdata->endpt_info.mod_data[mod_inv.mod.id] = sdp_info;
+
+    pjsip_media_type_init2(&app_sdp, "application", "sdp");
+
+    if (body && ctype_hdr &&
+	pj_stricmp(&ctype_hdr->media.type, &app_sdp.type)==0 &&
+	pj_stricmp(&ctype_hdr->media.subtype, &app_sdp.subtype)==0)
+    {
+	sdp_info->body.ptr = (char*)body->data;
+	sdp_info->body.slen = body->len;
+    } else if  (body && ctype_hdr &&
+	    	pj_stricmp2(&ctype_hdr->media.type, "multipart")==0 &&
+	    	(pj_stricmp2(&ctype_hdr->media.subtype, "mixed")==0 ||
+	    	 pj_stricmp2(&ctype_hdr->media.subtype, "alternative")==0))
+    {
+	pjsip_multipart_part *part;
+
+	part = pjsip_multipart_find_part(body, &app_sdp, NULL);
+	if (part) {
+	    sdp_info->body.ptr = (char*)part->body->data;
+	    sdp_info->body.slen = part->body->len;
+	}
+    }
+
+    if (sdp_info->body.ptr) {
+	pj_status_t status;
+	status = pjmedia_sdp_parse(rdata->tp_info.pool,
+				   sdp_info->body.ptr,
+				   sdp_info->body.slen,
+				   &sdp_info->sdp);
+	if (status == PJ_SUCCESS)
+	    status = pjmedia_sdp_validate2(sdp_info->sdp, PJ_FALSE);
+
+	if (status != PJ_SUCCESS) {
+	    sdp_info->sdp = NULL;
+	    PJ_PERROR(1,(THIS_FILE, status,
+			 "Error parsing/validating SDP body"));
+	}
+
+	sdp_info->sdp_err = status;
+    }
+
+    return sdp_info;
+}
+
+
+/*
+ * Verify incoming INVITE request.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata,
+                                              pj_pool_t *tmp_pool,
+					      unsigned *options,
+					      const pjmedia_sdp_session *r_sdp,
+					      const pjmedia_sdp_session *l_sdp,
+					      pjsip_dialog *dlg,
+					      pjsip_endpoint *endpt,
+					      pjsip_tx_data **p_tdata)
+{
+    pjsip_msg *msg = NULL;
+    pjsip_allow_hdr *allow = NULL;
+    pjsip_supported_hdr *sup_hdr = NULL;
+    pjsip_require_hdr *req_hdr = NULL;
+    pjsip_contact_hdr *c_hdr = NULL;
+    int code = 200;
+    unsigned rem_option = 0;
+    pj_status_t status = PJ_SUCCESS;
+    pjsip_hdr res_hdr_list;
+    pjsip_rdata_sdp_info *sdp_info;
+
+    /* Init return arguments. */
+    if (p_tdata) *p_tdata = NULL;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(tmp_pool != NULL && options != NULL, PJ_EINVAL);
+
+    /* Normalize options */
+    if (*options & PJSIP_INV_REQUIRE_100REL)
+	*options |= PJSIP_INV_SUPPORT_100REL;
+    if (*options & PJSIP_INV_REQUIRE_TIMER)
+	*options |= PJSIP_INV_SUPPORT_TIMER;
+    if (*options & PJSIP_INV_REQUIRE_ICE)
+	*options |= PJSIP_INV_SUPPORT_ICE;
+
+    if (rdata) {
+        /* Get the message in rdata */
+        msg = rdata->msg_info.msg;
+    
+        /* Must be INVITE request. */
+        PJ_ASSERT_RETURN(msg && msg->type == PJSIP_REQUEST_MSG &&
+		         msg->line.req.method.id == PJSIP_INVITE_METHOD,
+		         PJ_EINVAL);
+    }
+
+    /* If tdata is specified, then either dlg or endpt must be specified */
+    PJ_ASSERT_RETURN((!p_tdata) || (endpt || dlg), PJ_EINVAL);
+
+    /* Get the endpoint */
+    endpt = endpt ? endpt : dlg->endpt;
+
+    /* Init response header list */
+    pj_list_init(&res_hdr_list);
+
+    /* Check the Contact header */
+    if (msg) {
+        c_hdr = (pjsip_contact_hdr*)
+	        pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL);
+    }
+    if (msg && (!c_hdr || !c_hdr->uri)) {
+        /* Missing Contact header or Contact contains "*" */
+	pjsip_warning_hdr *w;
+	pj_str_t warn_text;
+
+	warn_text = pj_str("Bad/missing Contact header");
+	w = pjsip_warning_hdr_create(tmp_pool, 399,
+				     pjsip_endpt_name(endpt),
+				     &warn_text);
+	if (w) {
+	    pj_list_push_back(&res_hdr_list, w);
+	}
+
+	code = PJSIP_SC_BAD_REQUEST;
+	status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
+	goto on_return;
+    }
+
+    /* Check the request body, see if it's something that we support,
+     * only when the body hasn't been parsed before.
+     */
+    if (r_sdp == NULL && rdata) {
+	sdp_info = pjsip_rdata_get_sdp_info(rdata);
+    } else {
+	sdp_info = NULL;
+    }
+
+    if (r_sdp==NULL && msg && msg->body) {
+
+	/* Check if body really contains SDP. */
+	if (sdp_info->body.ptr == NULL) {
+	    /* Couldn't find "application/sdp" */
+	    code = PJSIP_SC_UNSUPPORTED_MEDIA_TYPE;
+	    status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
+
+	    if (p_tdata) {
+		/* Add Accept header to response */
+		pjsip_accept_hdr *acc;
+
+		acc = pjsip_accept_hdr_create(tmp_pool);
+		PJ_ASSERT_RETURN(acc, PJ_ENOMEM);
+		acc->values[acc->count++] = pj_str("application/sdp");
+		pj_list_push_back(&res_hdr_list, acc);
+	    }
+
+	    goto on_return;
+	}
+
+	if (sdp_info->sdp_err != PJ_SUCCESS) {
+	    /* Unparseable or invalid SDP */
+	    code = PJSIP_SC_BAD_REQUEST;
+
+	    if (p_tdata) {
+		/* Add Warning header. */
+		pjsip_warning_hdr *w;
+
+		w = pjsip_warning_hdr_create_from_status(tmp_pool,
+							 pjsip_endpt_name(endpt),
+							 sdp_info->sdp_err);
+		PJ_ASSERT_RETURN(w, PJ_ENOMEM);
+
+		pj_list_push_back(&res_hdr_list, w);
+	    }
+
+	    goto on_return;
+	}
+
+	r_sdp = sdp_info->sdp;
+    }
+
+    if (r_sdp) {
+	/* Negotiate with local SDP */
+	if (l_sdp) {
+	    pjmedia_sdp_neg *neg;
+
+	    /* Local SDP must be valid! */
+	    PJ_ASSERT_RETURN((status=pjmedia_sdp_validate(l_sdp))==PJ_SUCCESS,
+			     status);
+
+	    /* Create SDP negotiator */
+	    status = pjmedia_sdp_neg_create_w_remote_offer(
+			    tmp_pool, l_sdp, r_sdp, &neg);
+	    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
+
+	    /* Negotiate SDP */
+	    status = pjmedia_sdp_neg_negotiate(tmp_pool, neg, 0);
+	    if (status != PJ_SUCCESS) {
+
+		/* Incompatible media */
+		code = PJSIP_SC_NOT_ACCEPTABLE_HERE;
+
+		if (p_tdata) {
+		    pjsip_accept_hdr *acc;
+		    pjsip_warning_hdr *w;
+
+		    /* Add Warning header. */
+		    w = pjsip_warning_hdr_create_from_status(
+					    tmp_pool, 
+					    pjsip_endpt_name(endpt), status);
+		    PJ_ASSERT_RETURN(w, PJ_ENOMEM);
+
+		    pj_list_push_back(&res_hdr_list, w);
+
+		    /* Add Accept header to response */
+		    acc = pjsip_accept_hdr_create(tmp_pool);
+		    PJ_ASSERT_RETURN(acc, PJ_ENOMEM);
+		    acc->values[acc->count++] = pj_str("application/sdp");
+		    pj_list_push_back(&res_hdr_list, acc);
+
+		}
+
+		goto on_return;
+	    }
+	}
+    }
+
+    /* Check supported methods, see if peer supports UPDATE.
+     * We just assume that peer supports standard INVITE, ACK, CANCEL, and BYE
+     * implicitly by sending this INVITE.
+     */
+    if (msg) {
+        allow = (pjsip_allow_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_ALLOW,
+                                                      NULL);
+    }
+    if (allow) {
+	unsigned i;
+	const pj_str_t STR_UPDATE = { "UPDATE", 6 };
+
+	for (i=0; i<allow->count; ++i) {
+	    if (pj_stricmp(&allow->values[i], &STR_UPDATE)==0)
+		break;
+	}
+
+	if (i != allow->count) {
+	    /* UPDATE is present in Allow */
+	    rem_option |= PJSIP_INV_SUPPORT_UPDATE;
+	}
+
+    }
+
+    /* Check Supported header */
+    if (msg) {
+        sup_hdr = (pjsip_supported_hdr*)
+	          pjsip_msg_find_hdr(msg, PJSIP_H_SUPPORTED, NULL);
+    }
+    if (sup_hdr) {
+	unsigned i;
+	const pj_str_t STR_100REL = { "100rel", 6};
+	const pj_str_t STR_TIMER = { "timer", 5};
+	const pj_str_t STR_ICE = { "ice", 3 };
+
+	for (i=0; i<sup_hdr->count; ++i) {
+	    if (pj_stricmp(&sup_hdr->values[i], &STR_100REL)==0)
+		rem_option |= PJSIP_INV_SUPPORT_100REL;
+	    else if (pj_stricmp(&sup_hdr->values[i], &STR_TIMER)==0)
+		rem_option |= PJSIP_INV_SUPPORT_TIMER;
+	    else if (pj_stricmp(&sup_hdr->values[i], &STR_ICE)==0)
+		rem_option |= PJSIP_INV_SUPPORT_ICE;
+	}
+    }
+
+    /* Check Require header */
+    if (msg) {
+        req_hdr = (pjsip_require_hdr*)
+	          pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, NULL);
+    }
+    if (req_hdr) {
+	unsigned i;
+	const pj_str_t STR_100REL = { "100rel", 6};
+	const pj_str_t STR_REPLACES = { "replaces", 8 };
+	const pj_str_t STR_TIMER = { "timer", 5 };
+	const pj_str_t STR_ICE = { "ice", 3 };
+	unsigned unsupp_cnt = 0;
+	pj_str_t unsupp_tags[PJSIP_GENERIC_ARRAY_MAX_COUNT];
+	
+	for (i=0; i<req_hdr->count; ++i) {
+	    if ((*options & PJSIP_INV_SUPPORT_100REL) && 
+		pj_stricmp(&req_hdr->values[i], &STR_100REL)==0)
+	    {
+		rem_option |= PJSIP_INV_REQUIRE_100REL;
+
+	    } else if ((*options & PJSIP_INV_SUPPORT_TIMER) && 
+		pj_stricmp(&req_hdr->values[i], &STR_TIMER)==0)
+	    {
+		rem_option |= PJSIP_INV_REQUIRE_TIMER;
+
+	    } else if (pj_stricmp(&req_hdr->values[i], &STR_REPLACES)==0) {
+		pj_bool_t supp;
+		
+		supp = pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED, 
+						  NULL, &STR_REPLACES);
+		if (!supp)
+		    unsupp_tags[unsupp_cnt++] = req_hdr->values[i];
+	    } else if ((*options & PJSIP_INV_SUPPORT_ICE) &&
+		pj_stricmp(&req_hdr->values[i], &STR_ICE)==0)
+	    {
+		rem_option |= PJSIP_INV_REQUIRE_ICE;
+
+	    } else if (!pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED,
+						   NULL, &req_hdr->values[i]))
+	    {
+		/* Unknown/unsupported extension tag!  */
+		unsupp_tags[unsupp_cnt++] = req_hdr->values[i];
+	    }
+	}
+
+	/* Check if there are required tags that we don't support */
+	if (unsupp_cnt) {
+
+	    code = PJSIP_SC_BAD_EXTENSION;
+	    status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
+
+	    if (p_tdata) {
+		pjsip_unsupported_hdr *unsupp_hdr;
+		const pjsip_hdr *h;
+
+		/* Add Unsupported header. */
+		unsupp_hdr = pjsip_unsupported_hdr_create(tmp_pool);
+		PJ_ASSERT_RETURN(unsupp_hdr != NULL, PJ_ENOMEM);
+
+		unsupp_hdr->count = unsupp_cnt;
+		for (i=0; i<unsupp_cnt; ++i)
+		    unsupp_hdr->values[i] = unsupp_tags[i];
+
+		pj_list_push_back(&res_hdr_list, unsupp_hdr);
+
+		/* Add Supported header. */
+		h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, 
+					       NULL);
+		pj_assert(h);
+		if (h) {
+		    sup_hdr = (pjsip_supported_hdr*)
+			      pjsip_hdr_clone(tmp_pool, h);
+		    pj_list_push_back(&res_hdr_list, sup_hdr);
+		}
+	    }
+
+	    goto on_return;
+	}
+    }
+
+    /* Check if there are local requirements that are not supported
+     * by peer.
+     */
+    if ( msg && (((*options & PJSIP_INV_REQUIRE_100REL)!=0 && 
+	  (rem_option & PJSIP_INV_SUPPORT_100REL)==0) ||
+	 ((*options & PJSIP_INV_REQUIRE_TIMER)!=0 && 
+	  (rem_option & PJSIP_INV_SUPPORT_TIMER)==0)))
+    {
+	code = PJSIP_SC_EXTENSION_REQUIRED;
+	status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
+
+	if (p_tdata) {
+	    const pjsip_hdr *h;
+
+	    /* Add Require header. */
+	    req_hdr = pjsip_require_hdr_create(tmp_pool);
+	    PJ_ASSERT_RETURN(req_hdr != NULL, PJ_ENOMEM);
+
+	    if (*options & PJSIP_INV_REQUIRE_100REL)
+		req_hdr->values[req_hdr->count++] = pj_str("100rel");
+	    if (*options & PJSIP_INV_REQUIRE_TIMER)
+		req_hdr->values[req_hdr->count++] = pj_str("timer");
+
+	    pj_list_push_back(&res_hdr_list, req_hdr);
+
+	    /* Add Supported header. */
+	    h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, 
+					   NULL);
+	    pj_assert(h);
+	    if (h) {
+		sup_hdr = (pjsip_supported_hdr*)
+			  pjsip_hdr_clone(tmp_pool, h);
+		pj_list_push_back(&res_hdr_list, sup_hdr);
+	    }
+
+	}
+
+	goto on_return;
+    }
+
+    /* If remote Require something that we support, make us Require
+     * that feature too.
+     */
+    if (rem_option & PJSIP_INV_REQUIRE_100REL) {
+	    pj_assert(*options & PJSIP_INV_SUPPORT_100REL);
+	    *options |= PJSIP_INV_REQUIRE_100REL;
+    }
+    if (rem_option & PJSIP_INV_REQUIRE_TIMER) {
+	    pj_assert(*options & PJSIP_INV_SUPPORT_TIMER);
+	    *options |= PJSIP_INV_REQUIRE_TIMER;
+    }
+
+on_return:
+
+    /* Create response if necessary */
+    if (code != 200 && p_tdata) {
+	pjsip_tx_data *tdata;
+	const pjsip_hdr *h;
+
+        if (!rdata) {
+            return PJSIP_ERRNO_FROM_SIP_STATUS(code);
+        }
+
+	if (dlg) {
+	    status = pjsip_dlg_create_response(dlg, rdata, code, NULL, 
+					       &tdata);
+	} else {
+	    status = pjsip_endpt_create_response(endpt, rdata, code, NULL, 
+						 &tdata);
+	}
+
+	if (status != PJ_SUCCESS)
+	    return status;
+
+	/* Add response headers. */
+	h = res_hdr_list.next;
+	while (h != &res_hdr_list) {
+	    pjsip_hdr *cloned;
+
+	    cloned = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, h);
+	    PJ_ASSERT_RETURN(cloned, PJ_ENOMEM);
+
+	    pjsip_msg_add_hdr(tdata->msg, cloned);
+
+	    h = h->next;
+	}
+
+	*p_tdata = tdata;
+
+	/* Can not return PJ_SUCCESS when response message is produced.
+	 * Ref: PROTOS test ~#2490
+	 */
+	if (status == PJ_SUCCESS)
+	    status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
+
+    }
+
+    return status;
+}
+
+
+/*
+ * Verify incoming INVITE request.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_verify_request2(pjsip_rx_data *rdata,
+					      unsigned *options,
+					      const pjmedia_sdp_session *r_sdp,
+					      const pjmedia_sdp_session *l_sdp,
+					      pjsip_dialog *dlg,
+					      pjsip_endpoint *endpt,
+					      pjsip_tx_data **p_tdata)
+{
+    return pjsip_inv_verify_request3(rdata, rdata->tp_info.pool,
+                                     options, r_sdp, l_sdp, dlg, 
+				     endpt, p_tdata);
+}
+
+
+/*
+ * Verify incoming INVITE request.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_verify_request( pjsip_rx_data *rdata,
+					      unsigned *options,
+					      const pjmedia_sdp_session *l_sdp,
+					      pjsip_dialog *dlg,
+					      pjsip_endpoint *endpt,
+					      pjsip_tx_data **p_tdata)
+{
+    return pjsip_inv_verify_request3(rdata, rdata->tp_info.pool,
+                                     options, NULL, l_sdp, dlg, 
+				     endpt, p_tdata);
+}
+
+/*
+ * Create UAS invite session.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg,
+					  pjsip_rx_data *rdata,
+					  const pjmedia_sdp_session *local_sdp,
+					  unsigned options,
+					  pjsip_inv_session **p_inv)
+{
+    pjsip_inv_session *inv;
+    struct tsx_inv_data *tsx_inv_data;
+    pjsip_msg *msg;
+    pjsip_rdata_sdp_info *sdp_info;
+    pj_status_t status;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(dlg && rdata && p_inv, PJ_EINVAL);
+
+    /* Dialog MUST have been initialised. */
+    PJ_ASSERT_RETURN(pjsip_rdata_get_tsx(rdata) != NULL, PJ_EINVALIDOP);
+
+    msg = rdata->msg_info.msg;
+
+    /* rdata MUST contain INVITE request */
+    PJ_ASSERT_RETURN(msg->type == PJSIP_REQUEST_MSG &&
+		     msg->line.req.method.id == PJSIP_INVITE_METHOD,
+		     PJ_EINVALIDOP);
+
+    /* Lock dialog */
+    pjsip_dlg_inc_lock(dlg);
+
+    /* Normalize options */
+    if (options & PJSIP_INV_REQUIRE_100REL)
+	options |= PJSIP_INV_SUPPORT_100REL;
+    if (options & PJSIP_INV_REQUIRE_TIMER)
+	options |= PJSIP_INV_SUPPORT_TIMER;
+
+    /* Create the session */
+    inv = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_inv_session);
+    pj_assert(inv != NULL);
+
+    inv->pool = dlg->pool;
+    inv->role = PJSIP_ROLE_UAS;
+    inv->state = PJSIP_INV_STATE_NULL;
+    inv->dlg = dlg;
+    inv->options = options;
+    inv->notify = PJ_TRUE;
+    inv->cause = (pjsip_status_code) 0;
+
+    /* Create flip-flop pool (see ticket #877) */
+    /* (using inv->obj_name as temporary variable for pool names */
+    pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg->pool);
+    inv->pool_prov = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name,
+					     POOL_INIT_SIZE, POOL_INC_SIZE);
+    inv->pool_active = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name,
+					       POOL_INIT_SIZE, POOL_INC_SIZE);
+
+    /* Object name will use the same dialog pointer. */
+    pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg);
+
+    /* Process SDP in message body, if present. */
+    sdp_info = pjsip_rdata_get_sdp_info(rdata);
+    if (sdp_info->sdp_err) {
+	pjsip_dlg_dec_lock(dlg);
+	return sdp_info->sdp_err;
+    }
+
+    /* Create negotiator. */
+    if (sdp_info->sdp) {
+	status = pjmedia_sdp_neg_create_w_remote_offer(inv->pool, local_sdp,
+						       sdp_info->sdp,
+						       &inv->neg);
+						
+    } else if (local_sdp) {
+	status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, 
+						      local_sdp, &inv->neg);
+    } else {
+	status = PJ_SUCCESS;
+    }
+
+    if (status != PJ_SUCCESS) {
+	pjsip_dlg_dec_lock(dlg);
+	return status;
+    }
+
+    /* Register invite as dialog usage. */
+    status = pjsip_dlg_add_usage(dlg, &mod_inv.mod, inv);
+    if (status != PJ_SUCCESS) {
+	pjsip_dlg_dec_lock(dlg);
+	return status;
+    }
+
+    /* Increment session in the dialog. */
+    pjsip_dlg_inc_session(dlg, &mod_inv.mod);
+
+    /* Save the invite transaction. */
+    inv->invite_tsx = pjsip_rdata_get_tsx(rdata);
+
+    /* Attach our data to the transaction. */
+    tsx_inv_data = PJ_POOL_ZALLOC_T(inv->invite_tsx->pool, struct tsx_inv_data);
+    tsx_inv_data->inv = inv;
+    inv->invite_tsx->mod_data[mod_inv.mod.id] = tsx_inv_data;
+
+    /* Create 100rel handler */
+    if (inv->options & PJSIP_INV_REQUIRE_100REL) {
+	pjsip_100rel_attach(inv);
+    }
+
+    /* Done */
+    pjsip_dlg_dec_lock(dlg);
+    *p_inv = inv;
+
+    PJ_LOG(5,(inv->obj_name, "UAS invite session created for dialog %s",
+	      dlg->obj_name));
+
+    return PJ_SUCCESS;
+}
+
+/*
+ * Forcefully terminate the session.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_terminate( pjsip_inv_session *inv,
+				         int st_code,
+					 pj_bool_t notify)
+{
+    PJ_ASSERT_RETURN(inv, PJ_EINVAL);
+
+    /* Lock dialog. */
+    pjsip_dlg_inc_lock(inv->dlg);
+
+    /* Set callback notify flag. */
+    inv->notify = notify;
+
+    /* If there's pending transaction, terminate the transaction. 
+     * This may subsequently set the INVITE session state to
+     * disconnected.
+     */
+    if (inv->invite_tsx && 
+	inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED)
+    {
+	pjsip_tsx_terminate(inv->invite_tsx, st_code);
+
+    }
+
+    /* Set cause. */
+    inv_set_cause(inv, st_code, NULL);
+
+    /* Forcefully terminate the session if state is not DISCONNECTED */
+    if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {
+	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, NULL);
+    }
+
+    /* Done.
+     * The dec_lock() below will actually destroys the dialog if it
+     * has no other session.
+     */
+    pjsip_dlg_dec_lock(inv->dlg);
+
+    return PJ_SUCCESS;
+}
+
+
+/*
+ * Restart UAC session, possibly because app or us wants to re-send the 
+ * INVITE request due to 401/407 challenge or 3xx response.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_uac_restart(pjsip_inv_session *inv,
+					  pj_bool_t new_offer)
+{
+    PJ_ASSERT_RETURN(inv, PJ_EINVAL);
+
+    inv->state = PJSIP_INV_STATE_NULL;
+    inv->invite_tsx = NULL;
+    if (inv->last_answer) {
+	pjsip_tx_data_dec_ref(inv->last_answer);
+	inv->last_answer = NULL;
+    }
+
+    if (new_offer && inv->neg) {
+	pjmedia_sdp_neg_state neg_state;
+
+	neg_state = pjmedia_sdp_neg_get_state(inv->neg);
+	if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) {
+	    pjmedia_sdp_neg_cancel_offer(inv->neg);
+	}
+    }
+
+    return PJ_SUCCESS;
+}
+
+
+static void *clone_sdp(pj_pool_t *pool, const void *data, unsigned len)
+{
+    PJ_UNUSED_ARG(len);
+    return pjmedia_sdp_session_clone(pool, (const pjmedia_sdp_session*)data);
+}
+
+static int print_sdp(pjsip_msg_body *body, char *buf, pj_size_t len)
+{
+    return pjmedia_sdp_print((const pjmedia_sdp_session*)body->data, buf, len);
+}
+
+
+PJ_DEF(pj_status_t) pjsip_create_sdp_body( pj_pool_t *pool,
+					   pjmedia_sdp_session *sdp,
+					   pjsip_msg_body **p_body)
+{
+    const pj_str_t STR_APPLICATION = { "application", 11};
+    const pj_str_t STR_SDP = { "sdp", 3 };
+    pjsip_msg_body *body;
+
+    body = PJ_POOL_ZALLOC_T(pool, pjsip_msg_body);
+    PJ_ASSERT_RETURN(body != NULL, PJ_ENOMEM);
+
+    pjsip_media_type_init(&body->content_type, (pj_str_t*)&STR_APPLICATION,
+			  (pj_str_t*)&STR_SDP);
+    body->data = sdp;
+    body->len = 0;
+    body->clone_data = &clone_sdp;
+    body->print_body = &print_sdp;
+
+    *p_body = body;
+
+    return PJ_SUCCESS;
+}
+
+static pjsip_msg_body *create_sdp_body(pj_pool_t *pool,
+				       const pjmedia_sdp_session *c_sdp)
+{
+    pjsip_msg_body *body;
+    pj_status_t status;
+
+    status = pjsip_create_sdp_body(pool, 
+				   pjmedia_sdp_session_clone(pool, c_sdp),
+				   &body);
+
+    if (status != PJ_SUCCESS)
+	return NULL;
+
+    return body;
+}
+
+/*
+ * Create initial INVITE request.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_invite( pjsip_inv_session *inv,
+				      pjsip_tx_data **p_tdata )
+{
+    pjsip_tx_data *tdata;
+    const pjsip_hdr *hdr;
+    pj_bool_t has_sdp;
+    pj_status_t status;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
+
+    /* State MUST be NULL or CONFIRMED. */
+    PJ_ASSERT_RETURN(inv->state == PJSIP_INV_STATE_NULL ||
+		     inv->state == PJSIP_INV_STATE_CONFIRMED, 
+		     PJ_EINVALIDOP);
+
+    /* Lock dialog. */
+    pjsip_dlg_inc_lock(inv->dlg);
+
+    /* Create the INVITE request. */
+    status = pjsip_dlg_create_request(inv->dlg, pjsip_get_invite_method(), -1,
+				      &tdata);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+
+    /* If this is the first INVITE, then copy the headers from inv_hdr.
+     * These are the headers parsed from the request URI when the
+     * dialog was created.
+     */
+    if (inv->state == PJSIP_INV_STATE_NULL) {
+	hdr = inv->dlg->inv_hdr.next;
+
+	while (hdr != &inv->dlg->inv_hdr) {
+	    pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)
+			      pjsip_hdr_shallow_clone(tdata->pool, hdr));
+	    hdr = hdr->next;
+	}
+    }
+
+    /* See if we have SDP to send. */
+    if (inv->neg) {
+	pjmedia_sdp_neg_state neg_state;
+
+	neg_state = pjmedia_sdp_neg_get_state(inv->neg);
+
+	has_sdp = (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER ||
+		   (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO &&
+		    pjmedia_sdp_neg_has_local_answer(inv->neg)));
+
+
+    } else {
+	has_sdp = PJ_FALSE;
+    }
+
+    /* Add SDP, if any. */
+    if (has_sdp) {
+	const pjmedia_sdp_session *offer;
+
+	status = pjmedia_sdp_neg_get_neg_local(inv->neg, &offer);
+	if (status != PJ_SUCCESS) {
+	    pjsip_tx_data_dec_ref(tdata);
+	    goto on_return;
+	}
+
+	tdata->msg->body = create_sdp_body(tdata->pool, offer);
+    }
+
+    /* Add Allow header. */
+    if (inv->dlg->add_allow) {
+	hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_ALLOW, NULL);
+	if (hdr) {
+	    pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)
+			      pjsip_hdr_shallow_clone(tdata->pool, hdr));
+	}
+    }
+
+    /* Add Supported header */
+    hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_SUPPORTED, NULL);
+    if (hdr) {
+	pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)
+			  pjsip_hdr_shallow_clone(tdata->pool, hdr));
+    }
+
+    /* Add Require header. */
+    if ((inv->options & PJSIP_INV_REQUIRE_100REL) ||
+	(inv->options & PJSIP_INV_REQUIRE_TIMER)) 
+    {
+	pjsip_require_hdr *hreq;
+
+	hreq = pjsip_require_hdr_create(tdata->pool);
+
+	if (inv->options & PJSIP_INV_REQUIRE_100REL)
+	    hreq->values[hreq->count++] = pj_str("100rel");
+	if (inv->options & PJSIP_INV_REQUIRE_TIMER)
+	    hreq->values[hreq->count++] = pj_str("timer");
+
+	pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hreq);
+    }
+
+    status = pjsip_timer_update_req(inv, tdata);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Done. */
+    *p_tdata = tdata;
+
+
+on_return:
+    pjsip_dlg_dec_lock(inv->dlg);
+    return status;
+}
+
+
+/* Util: swap pool */
+static void swap_pool(pj_pool_t **p1, pj_pool_t **p2)
+{
+    pj_pool_t *tmp = *p1;
+    *p1 = *p2;
+    *p2 = tmp;
+}
+
+
+/*
+ * Initiate SDP negotiation in the SDP negotiator.
+ */
+static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv )
+{
+    pj_status_t status;
+
+    PJ_ASSERT_RETURN(pjmedia_sdp_neg_get_state(inv->neg) ==
+		     PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, 
+		     PJMEDIA_SDPNEG_EINSTATE);
+
+    status = pjmedia_sdp_neg_negotiate(inv->pool_prov, inv->neg, 0);
+
+    PJ_LOG(5,(inv->obj_name, "SDP negotiation done, status=%d", status));
+
+    if (mod_inv.cb.on_media_update && inv->notify)
+	(*mod_inv.cb.on_media_update)(inv, status);
+
+    /* Invite session may have been terminated by the application even 
+     * after a successful SDP negotiation, for example when no audio 
+     * codec is present in the offer (see ticket #1034).
+     */
+    if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {
+
+	/* Swap the flip-flop pool when SDP negotiation success. */
+	if (status == PJ_SUCCESS) {
+	    swap_pool(&inv->pool_prov, &inv->pool_active);
+	}
+
+	/* Reset the provisional pool regardless SDP negotiation result. */
+	pj_pool_reset(inv->pool_prov);
+
+    } else {
+
+	status = PJSIP_ERRNO_FROM_SIP_STATUS(inv->cause);
+    }
+
+    return status;
+}
+
+/*
+ * Check in incoming message for SDP offer/answer.
+ */
+static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv,
+						  pjsip_transaction *tsx,
+						  pjsip_rx_data *rdata)
+{
+    struct tsx_inv_data *tsx_inv_data;
+    pj_status_t status;
+    pjsip_msg *msg;
+    pjsip_rdata_sdp_info *sdp_info;
+
+    /* Check if SDP is present in the message. */
+
+    msg = rdata->msg_info.msg;
+    if (msg->body == NULL) {
+	/* Message doesn't have body. */
+	return PJ_SUCCESS;
+    }
+
+    sdp_info = pjsip_rdata_get_sdp_info(rdata);
+    if (sdp_info->body.ptr == NULL) {
+	/* Message body is not "application/sdp" */
+	return PJMEDIA_SDP_EINSDP;
+    }
+
+    /* Get/attach invite session's transaction data */
+    tsx_inv_data = (struct tsx_inv_data*) tsx->mod_data[mod_inv.mod.id];
+    if (tsx_inv_data == NULL) {
+	tsx_inv_data = PJ_POOL_ZALLOC_T(tsx->pool, struct tsx_inv_data);
+	tsx_inv_data->inv = inv;
+	tsx->mod_data[mod_inv.mod.id] = tsx_inv_data;
+    }
+
+    /* MUST NOT do multiple SDP offer/answer in a single transaction,
+     * EXCEPT if:
+     *	- this is an initial UAC INVITE transaction (i.e. not re-INVITE), and
+     *	- the previous negotiation was done on an early media (18x) and
+     *    this response is a final/2xx response, and
+     *  - the 2xx response has different To tag than the 18x response
+     *    (i.e. the request has forked).
+     *
+     * The exception above is to add a rudimentary support for early media
+     * forking (sample case: custom ringback). See this ticket for more
+     * info: http://trac.pjsip.org/repos/ticket/657
+     */
+    if (tsx_inv_data->sdp_done) {
+	pj_str_t res_tag;
+	int st_code;
+
+	res_tag = rdata->msg_info.to->tag;
+	st_code = rdata->msg_info.msg->line.status.code;
+
+	/* Allow final/early response after SDP has been negotiated in early
+	 * media, IF this response is a final/early response with different
+	 * tag.
+	 */
+	if (tsx->role == PJSIP_ROLE_UAC &&
+	    (st_code/100 == 2 ||
+	     (st_code==183 && pjsip_cfg()->endpt.follow_early_media_fork)) &&
+	    tsx_inv_data->done_early &&
+	    pj_stricmp(&tsx_inv_data->done_tag, &res_tag))
+	{
+	    const pjmedia_sdp_session *reoffer_sdp = NULL;
+
+	    PJ_LOG(4,(inv->obj_name, "Received forked %s response "
+		      "after SDP negotiation has been done in early "
+		      "media. Renegotiating SDP..",
+		      (st_code==183? "early" : "final" )));
+
+	    /* Retrieve original SDP offer from INVITE request */
+	    reoffer_sdp = (const pjmedia_sdp_session*) 
+			  tsx->last_tx->msg->body->data;
+
+	    /* Feed the original offer to negotiator */
+	    status = pjmedia_sdp_neg_modify_local_offer2(inv->pool_prov, 
+							 inv->neg,
+                                                         inv->sdp_neg_flags,
+						         reoffer_sdp);
+	    if (status != PJ_SUCCESS) {
+		PJ_LOG(1,(inv->obj_name, "Error updating local offer for "
+			  "forked 2xx/183 response (err=%d)", status));
+		return status;
+	    }
+
+	} else {
+
+	    if (rdata->msg_info.msg->body) {
+		PJ_LOG(4,(inv->obj_name, "SDP negotiation done, message "
+			  "body is ignored"));
+	    }
+	    return PJ_SUCCESS;
+	}
+    }
+
+    /* Process the SDP body. */
+    if (sdp_info->sdp_err) {
+	PJ_PERROR(4,(THIS_FILE, sdp_info->sdp_err,
+		     "Error parsing SDP in %s",
+		     pjsip_rx_data_get_info(rdata)));
+	return PJMEDIA_SDP_EINSDP;
+    }
+
+    pj_assert(sdp_info->sdp != NULL);
+
+    /* The SDP can be an offer or answer, depending on negotiator's state */
+
+    if (inv->neg == NULL ||
+	pjmedia_sdp_neg_get_state(inv->neg) == PJMEDIA_SDP_NEG_STATE_DONE) 
+    {
+
+	/* This is an offer. */
+
+	PJ_LOG(5,(inv->obj_name, "Got SDP offer in %s", 
+		  pjsip_rx_data_get_info(rdata)));
+
+	if (inv->neg == NULL) {
+	    status=pjmedia_sdp_neg_create_w_remote_offer(inv->pool, NULL,
+							 sdp_info->sdp,
+							 &inv->neg);
+	} else {
+	    status=pjmedia_sdp_neg_set_remote_offer(inv->pool_prov, inv->neg, 
+						    sdp_info->sdp);
+	}
+
+	if (status != PJ_SUCCESS) {
+	    PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP offer in %",
+		      pjsip_rx_data_get_info(rdata)));
+	    return PJMEDIA_SDP_EINSDP;
+	}
+
+	/* Inform application about remote offer. */
+	if (mod_inv.cb.on_rx_offer && inv->notify) {
+
+	    (*mod_inv.cb.on_rx_offer)(inv, sdp_info->sdp);
+
+	}
+
+	/* application must have supplied an answer at this point. */
+	if (pjmedia_sdp_neg_get_state(inv->neg) !=
+		PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)
+	{
+            if (mod_inv.cb.on_rx_reinvite && inv->notify &&
+                msg->type == PJSIP_REQUEST_MSG &&
+                msg->line.req.method.id == PJSIP_INVITE_METHOD)
+            {
+                /* Do not return failure first, allow the application
+                 * to set the answer in the on_rx_reinvite() callback.
+                 */
+        	PJ_LOG(5,(inv->obj_name, "Ignoring on_rx_offer() status "
+        		  "because on_rx_reinvite() is implemented"));
+                return PJ_SUCCESS;
+            }
+	    return PJ_EINVALIDOP;
+	}
+
+    } else if (pjmedia_sdp_neg_get_state(inv->neg) == 
+		PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) 
+    {
+	int status_code;
+
+	/* This is an answer. 
+	 * Process and negotiate remote answer.
+	 */
+
+	PJ_LOG(5,(inv->obj_name, "Got SDP answer in %s", 
+		  pjsip_rx_data_get_info(rdata)));
+
+	status = pjmedia_sdp_neg_set_remote_answer(inv->pool_prov, inv->neg,
+						   sdp_info->sdp);
+
+	if (status != PJ_SUCCESS) {
+	    PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP answer in %s",
+		      pjsip_rx_data_get_info(rdata)));
+	    return PJMEDIA_SDP_EINSDP;
+	}
+
+	/* Negotiate SDP */
+
+	inv_negotiate_sdp(inv);
+
+	/* Mark this transaction has having SDP offer/answer done, and
+	 * save the reference to the To tag
+	 */
+
+	tsx_inv_data->sdp_done = 1;
+	status_code = rdata->msg_info.msg->line.status.code;
+	tsx_inv_data->done_early = (status_code/100==1);
+	pj_strdup(tsx->pool, &tsx_inv_data->done_tag, 
+		  &rdata->msg_info.to->tag);
+
+    } else {
+	
+	PJ_LOG(5,(THIS_FILE, "Ignored SDP in %s: negotiator state is %s",
+	      pjsip_rx_data_get_info(rdata), 
+	      pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv->neg))));
+    }
+
+    return PJ_SUCCESS;
+}
+
+
+/*
+ * Process INVITE answer, for both initial and subsequent re-INVITE
+ */
+static pj_status_t process_answer( pjsip_inv_session *inv,
+				   int st_code,
+				   pjsip_tx_data *tdata,
+				   const pjmedia_sdp_session *local_sdp)
+{
+    pj_status_t status;
+    const pjmedia_sdp_session *sdp = NULL;
+
+    /* If local_sdp is specified, then we MUST NOT have answered the
+     * offer before. 
+     */
+    if (local_sdp && (st_code/100==1 || st_code/100==2)) {
+
+	if (inv->neg == NULL) {
+	    status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, 
+							  local_sdp,
+							  &inv->neg);
+	} else if (pjmedia_sdp_neg_get_state(inv->neg)==
+		   PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER)
+	{
+	    status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov, inv->neg,
+						      local_sdp);
+	} else {
+
+	    /* Can not specify local SDP at this state. */
+	    pj_assert(0);
+	    status = PJMEDIA_SDPNEG_EINSTATE;
+	}
+
+	if (status != PJ_SUCCESS)
+	    return status;
+
+    }
+
+
+     /* If SDP negotiator is ready, start negotiation. */
+    if (st_code/100==2 || (st_code/10==18 && st_code!=180)) {
+
+	pjmedia_sdp_neg_state neg_state;
+
+	/* Start nego when appropriate. */
+	neg_state = inv->neg ? pjmedia_sdp_neg_get_state(inv->neg) :
+		    PJMEDIA_SDP_NEG_STATE_NULL;
+
+	if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) {
+
+	    status = pjmedia_sdp_neg_get_neg_local(inv->neg, &sdp);
+
+	} else if (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO &&
+		   pjmedia_sdp_neg_has_local_answer(inv->neg) )
+	{
+	    struct tsx_inv_data *tsx_inv_data;
+
+	    /* Get invite session's transaction data */
+	    tsx_inv_data = (struct tsx_inv_data*) 
+		           inv->invite_tsx->mod_data[mod_inv.mod.id];
+
+	    status = inv_negotiate_sdp(inv);
+	    if (status != PJ_SUCCESS)
+		return status;
+	    
+	    /* Mark this transaction has having SDP offer/answer done. */
+	    tsx_inv_data->sdp_done = 1;
+
+	    status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp);
+	}
+    }
+
+    /* Include SDP when it's available for 2xx and 18x (but not 180) response.
+     * Subsequent response will include this SDP.
+     *
+     * Note note:
+     *	- When offer/answer has been completed in reliable 183, we MUST NOT
+     *	  send SDP in 2xx response. So if we don't have SDP to send, clear
+     *	  the SDP in the message body ONLY if 100rel is active in this 
+     *    session.
+     */
+    if (sdp) {
+	tdata->msg->body = create_sdp_body(tdata->pool, sdp);
+    } else {
+	if (inv->options & PJSIP_INV_REQUIRE_100REL) {
+	    tdata->msg->body = NULL;
+	}
+    }
+
+    /* Cancel SDP negotiation if this is a negative reply to a re-INVITE */
+    if (st_code >= 300 && inv->neg != NULL &&
+        inv->state == PJSIP_INV_STATE_CONFIRMED)
+    {
+        pjmedia_sdp_neg_state neg_state;
+        neg_state = pjmedia_sdp_neg_get_state(inv->neg);
+        if (neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER) {
+            pjmedia_sdp_neg_cancel_offer(inv->neg);
+        }
+    }
+
+    return PJ_SUCCESS;
+}
+
+
+/*
+ * Create first response to INVITE
+ */
+PJ_DEF(pj_status_t) pjsip_inv_initial_answer(	pjsip_inv_session *inv,
+						pjsip_rx_data *rdata,
+						int st_code,
+						const pj_str_t *st_text,
+						const pjmedia_sdp_session *sdp,
+						pjsip_tx_data **p_tdata)
+{
+    pjsip_tx_data *tdata;
+    pj_status_t status;
+    pjsip_status_code st_code2;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
+
+    /* Must have INVITE transaction. */
+    PJ_ASSERT_RETURN(inv->invite_tsx, PJ_EBUG);
+
+    pj_log_push_indent();
+
+    pjsip_dlg_inc_lock(inv->dlg);
+
+    /* Create response */
+    status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, st_text,
+				       &tdata);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Invoke Session Timers module */
+    status = pjsip_timer_process_req(inv, rdata, &st_code2);
+    if (status != PJ_SUCCESS) {
+	pj_status_t status2;
+
+	status2 = pjsip_dlg_modify_response(inv->dlg, tdata, st_code2, NULL);
+	if (status2 != PJ_SUCCESS) {
+	    pjsip_tx_data_dec_ref(tdata);
+	    goto on_return;
+	}
+	status2 = pjsip_timer_update_resp(inv, tdata);
+	if (status2 == PJ_SUCCESS)
+	    *p_tdata = tdata;
+	else
+	    pjsip_tx_data_dec_ref(tdata);
+
+	goto on_return;
+    }
+
+    /* Process SDP in answer */
+    status = process_answer(inv, st_code, tdata, sdp);
+    if (status != PJ_SUCCESS) {
+	pjsip_tx_data_dec_ref(tdata);
+	goto on_return;
+    }
+
+    /* Save this answer */
+    inv->last_answer = tdata;
+    pjsip_tx_data_add_ref(inv->last_answer);
+    PJ_LOG(5,(inv->dlg->obj_name, "Initial answer %s",
+	      pjsip_tx_data_get_info(inv->last_answer)));
+
+    /* Invoke Session Timers */
+    pjsip_timer_update_resp(inv, tdata);
+
+    *p_tdata = tdata;
+
+on_return:
+    pjsip_dlg_dec_lock(inv->dlg);
+    pj_log_pop_indent();
+    return status;
+}
+
+
+/*
+ * Answer INVITE request.
+ */ 
+PJ_DEF(pj_status_t) pjsip_inv_answer(	pjsip_inv_session *inv,
+					int st_code,
+					const pj_str_t *st_text,
+					const pjmedia_sdp_session *local_sdp,
+					pjsip_tx_data **p_tdata )
+{
+    pjsip_tx_data *last_res;
+    pj_status_t status;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
+
+    /* Must have INVITE transaction. */
+    PJ_ASSERT_RETURN(inv->invite_tsx, PJ_EBUG);
+
+    /* Must have created an answer before */
+    PJ_ASSERT_RETURN(inv->last_answer, PJ_EINVALIDOP);
+
+    pj_log_push_indent();
+
+    pjsip_dlg_inc_lock(inv->dlg);
+
+    /* Modify last response. */
+    last_res = inv->last_answer;
+    status = pjsip_dlg_modify_response(inv->dlg, last_res, st_code, st_text);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* For non-2xx final response, strip message body */
+    if (st_code >= 300) {
+	last_res->msg->body = NULL;
+    }
+
+    /* Process SDP in answer */
+    status = process_answer(inv, st_code, last_res, local_sdp);
+    if (status != PJ_SUCCESS) {
+	pjsip_tx_data_dec_ref(last_res);
+	goto on_return;
+    }
+
+    /* Invoke Session Timers */
+    pjsip_timer_update_resp(inv, last_res);
+
+    *p_tdata = last_res;
+
+on_return:
+    pjsip_dlg_dec_lock(inv->dlg);
+    pj_log_pop_indent();
+    return status;
+}
+
+
+/*
+ * Set local SDP offer/answer.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_set_local_sdp(pjsip_inv_session *inv,
+					    const pjmedia_sdp_session *sdp )
+{
+    const pjmedia_sdp_session *offer;
+    pj_status_t status;
+
+    PJ_ASSERT_RETURN(inv && sdp, PJ_EINVAL);
+
+    /* If we have remote SDP offer, set local answer to respond to the offer,
+     * otherwise we set/modify our local offer (and create an SDP negotiator
+     * if we don't have one yet).
+     */
+    if (inv->neg) {
+        pjmedia_sdp_neg_state neg_state = pjmedia_sdp_neg_get_state(inv->neg);
+
+        if ((neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER ||
+	     neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) &&
+            pjmedia_sdp_neg_get_neg_remote(inv->neg, &offer) == PJ_SUCCESS)
+        {
+            status = pjsip_inv_set_sdp_answer(inv, sdp);
+        }  else if (neg_state == PJMEDIA_SDP_NEG_STATE_DONE) {
+            status = pjmedia_sdp_neg_modify_local_offer2(inv->pool, inv->neg,
+                                                         inv->sdp_neg_flags,
+                                                         sdp);
+        } else
+            return PJMEDIA_SDPNEG_EINSTATE;
+    } else {
+	status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, 
+						      sdp, &inv->neg);
+    }
+
+    return status;
+}
+
+
+/*
+ * Set SDP answer.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_set_sdp_answer( pjsip_inv_session *inv,
+					      const pjmedia_sdp_session *sdp )
+{
+    pj_status_t status;
+
+    PJ_ASSERT_RETURN(inv && sdp, PJ_EINVAL);
+
+    pjsip_dlg_inc_lock(inv->dlg);
+    status = pjmedia_sdp_neg_set_local_answer( inv->pool_prov, inv->neg, sdp);
+    pjsip_dlg_dec_lock(inv->dlg);
+
+    return status;
+}
+
+
+/*
+ * End session.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_end_session(  pjsip_inv_session *inv,
+					    int st_code,
+					    const pj_str_t *st_text,
+					    pjsip_tx_data **p_tdata )
+{
+    pjsip_tx_data *tdata;
+    pj_status_t status;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
+
+    pj_log_push_indent();
+
+    /* Set cause code. */
+    inv_set_cause(inv, st_code, st_text);
+
+    /* Create appropriate message. */
+    switch (inv->state) {
+    case PJSIP_INV_STATE_CALLING:
+    case PJSIP_INV_STATE_EARLY:
+    case PJSIP_INV_STATE_INCOMING:
+
+	if (inv->role == PJSIP_ROLE_UAC) {
+
+	    /* For UAC when session has not been confirmed, create CANCEL. */
+
+	    /* MUST have the original UAC INVITE transaction. */
+	    PJ_ASSERT_RETURN(inv->invite_tsx != NULL, PJ_EBUG);
+
+	    /* But CANCEL should only be called when we have received a
+	     * provisional response. If we haven't received any responses,
+	     * just destroy the transaction.
+	     */
+	    if (inv->invite_tsx->status_code < 100) {
+
+		/* Do not stop INVITE retransmission, see ticket #506 */
+		//pjsip_tsx_stop_retransmit(inv->invite_tsx);
+		inv->cancelling = PJ_TRUE;
+		inv->pending_cancel = PJ_TRUE;
+		*p_tdata = NULL;
+		PJ_LOG(4, (inv->obj_name, "Delaying CANCEL since no "
+			   "provisional response is received yet"));
+		pj_log_pop_indent();
+		return PJ_SUCCESS;
+	    }
+
+	    /* The CSeq here assumes that the dialog is started with an
+	     * INVITE session. This may not be correct; dialog can be 
+	     * started as SUBSCRIBE session.
+	     * So fix this!
+	     */
+	    status = pjsip_endpt_create_cancel(inv->dlg->endpt, 
+					       inv->invite_tsx->last_tx,
+					       &tdata);
+	    if (status != PJ_SUCCESS) {
+		pj_log_pop_indent();
+		return status;
+	    }
+
+	    /* Set timeout for the INVITE transaction, in case UAS is not
+	     * able to respond the INVITE with 487 final response. The 
+	     * timeout value is 64*T1.
+	     */
+	    pjsip_tsx_set_timeout(inv->invite_tsx, 64 * pjsip_cfg()->tsx.t1);
+
+	} else {
+
+	    /* For UAS, send a final response. */
+	    tdata = inv->invite_tsx->last_tx;
+	    PJ_ASSERT_RETURN(tdata != NULL, PJ_EINVALIDOP);
+
+	    //status = pjsip_dlg_modify_response(inv->dlg, tdata, st_code,
+	    //				       st_text);
+	    status = pjsip_inv_answer(inv, st_code, st_text, NULL, &tdata);
+	}
+	break;
+
+    case PJSIP_INV_STATE_CONNECTING:
+    case PJSIP_INV_STATE_CONFIRMED:
+	/* End Session Timer */
+	pjsip_timer_end_session(inv);
+
+	/* For established dialog, send BYE */
+	status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(), 
+					  -1, &tdata);
+	break;
+
+    case PJSIP_INV_STATE_DISCONNECTED:
+	/* No need to do anything. */
+	pj_log_pop_indent();
+	return PJSIP_ESESSIONTERMINATED;
+
+    default:
+	pj_assert(!"Invalid operation!");
+	pj_log_pop_indent();
+	return PJ_EINVALIDOP;
+    }
+
+    if (status != PJ_SUCCESS) {
+	pj_log_pop_indent();
+	return status;
+    }
+
+
+    /* Done */
+
+    inv->cancelling = PJ_TRUE;
+    *p_tdata = tdata;
+
+    pj_log_pop_indent();
+    return PJ_SUCCESS;
+}
+
+/*
+ * Cancel re-INVITE transaction.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_cancel_reinvite( pjsip_inv_session *inv,
+                                               pjsip_tx_data **p_tdata )
+{
+    pjsip_tx_data *tdata;
+    pj_status_t status;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
+    
+    pj_log_push_indent();
+
+    /* Create appropriate message. */
+    switch (inv->state) {
+    case PJSIP_INV_STATE_CONFIRMED:
+        /* MUST have the original UAC INVITE transaction  */
+        PJ_ASSERT_RETURN(inv->invite_tsx != NULL, PJ_EBUG);
+
+        /* CANCEL should only be called when we have received a
+         * provisional response.
+         */
+        if (inv->invite_tsx->status_code < 100) {
+            inv->cancelling = PJ_TRUE;
+            inv->pending_cancel = PJ_TRUE;
+            *p_tdata = NULL;
+            PJ_LOG(4, (inv->obj_name, "Delaying CANCEL since no "
+                       "provisional response is received yet"));
+            pj_log_pop_indent();
+            return PJ_SUCCESS;
+        }
+
+        status = pjsip_endpt_create_cancel(inv->dlg->endpt, 
+                                           inv->invite_tsx->last_tx,
+                                           &tdata);
+        if (status != PJ_SUCCESS) {
+            pj_log_pop_indent();
+            return status;
+        }
+	break;
+
+    default:
+        /* We cannot send CANCEL to a re-INVITE if the INVITE session is
+         * not confirmed.
+         */
+        pj_log_pop_indent();
+        return PJ_EINVALIDOP;
+    }
+
+    pj_log_pop_indent();
+
+    *p_tdata = tdata;
+    return PJ_SUCCESS;
+}
+
+/* Following redirection recursion, get next target from the target set and
+ * notify user.
+ *
+ * Returns PJ_FALSE if recursion fails (either because there's no more target
+ * or user rejects the recursion). If we return PJ_FALSE, caller should
+ * disconnect the session.
+ *
+ * Note:
+ *   the event 'e' argument may be NULL.
+ */
+static pj_bool_t inv_uac_recurse(pjsip_inv_session *inv, int code,
+				 const pj_str_t *reason, pjsip_event *e)
+{
+    pjsip_redirect_op op;
+    pjsip_target *target;
+
+    /* Won't redirect if the callback is not implemented. */
+    if (mod_inv.cb.on_redirected == NULL)
+	return PJ_FALSE;
+
+    if (reason == NULL)
+	reason = pjsip_get_status_text(code);
+
+    /* Set status of current target */
+    pjsip_target_assign_status(inv->dlg->target_set.current, inv->dlg->pool,
+			       code, reason);
+
+    /* Fetch next target from the target set. We only want to
+     * process SIP/SIPS URI for now.
+     */
+    for (;;) {
+	target = pjsip_target_set_get_next(&inv->dlg->target_set);
+	if (target == NULL) {
+	    /* No more target. */
+	    return PJ_FALSE;
+	}
+
+	if (!PJSIP_URI_SCHEME_IS_SIP(target->uri) &&
+	    !PJSIP_URI_SCHEME_IS_SIPS(target->uri))
+	{
+	    code = PJSIP_SC_UNSUPPORTED_URI_SCHEME;
+	    reason = pjsip_get_status_text(code);
+
+	    /* Mark this target as unusable and fetch next target. */
+	    pjsip_target_assign_status(target, inv->dlg->pool, code, reason);
+	} else {
+	    /* Found a target */
+	    break;
+	}
+    }
+
+    /* We have target in 'target'. Set this target as current target
+     * and notify callback. 
+     */
+    pjsip_target_set_set_current(&inv->dlg->target_set, target);
+
+    op = (*mod_inv.cb.on_redirected)(inv, target->uri, e);
+
+
+    /* Check what the application wants to do now */
+    switch (op) {
+    case PJSIP_REDIRECT_ACCEPT:
+    case PJSIP_REDIRECT_ACCEPT_REPLACE:
+    case PJSIP_REDIRECT_STOP:
+	/* Must increment session counter, that's the convention of the 
+	 * pjsip_inv_process_redirect().
+	 */
+	pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod);
+
+	/* Act on the recursion */
+	pjsip_inv_process_redirect(inv, op, e);
+	return PJ_TRUE;
+
+    case PJSIP_REDIRECT_PENDING:
+	/* Increment session so that the dialog/session is not destroyed 
+	 * while we're waiting for user confirmation.
+	 */
+	pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod);
+
+	/* Also clear the invite_tsx variable, otherwise when this tsx is
+	 * terminated, it will also terminate the session.
+	 */
+	inv->invite_tsx = NULL;
+
+	/* Done. The processing will continue once the application calls
+	 * pjsip_inv_process_redirect().
+	 */
+	return PJ_TRUE;
+
+    case PJSIP_REDIRECT_REJECT:
+	/* Recursively call  this function again to fetch next target, if any.
+	 */
+	return inv_uac_recurse(inv, PJSIP_SC_REQUEST_TERMINATED, NULL, e);
+
+    }
+
+    pj_assert(!"Should not reach here");
+    return PJ_FALSE;
+}
+
+
+/* Process redirection/recursion */
+PJ_DEF(pj_status_t) pjsip_inv_process_redirect( pjsip_inv_session *inv,
+						pjsip_redirect_op op,
+						pjsip_event *e)
+{
+    const pjsip_status_code cancel_code = PJSIP_SC_REQUEST_TERMINATED;
+    pjsip_event usr_event;
+    pj_status_t status = PJ_SUCCESS;
+
+    PJ_ASSERT_RETURN(inv && op != PJSIP_REDIRECT_PENDING, PJ_EINVAL);
+
+    if (e == NULL) {
+	PJSIP_EVENT_INIT_USER(usr_event, NULL, NULL, NULL, NULL);
+	e = &usr_event;
+    }
+
+    pjsip_dlg_inc_lock(inv->dlg);
+
+    /* Decrement session. That's the convention here to prevent the dialog 
+     * or session from being destroyed while we're waiting for user
+     * confirmation.
+     */
+    pjsip_dlg_dec_session(inv->dlg, &mod_inv.mod);
+
+    /* See what the application wants to do now */
+    switch (op) {
+    case PJSIP_REDIRECT_ACCEPT:
+    case PJSIP_REDIRECT_ACCEPT_REPLACE:
+	/* User accept the redirection. Reset the session and resend the 
+	 * INVITE request.
+	 */
+	{
+	    pjsip_tx_data *tdata;
+	    pjsip_via_hdr *via;
+
+	    /* Get the original INVITE request. */
+	    tdata = inv->invite_req;
+	    pjsip_tx_data_add_ref(tdata);
+
+	    /* Restore strict route set.
+	     * See http://trac.pjsip.org/repos/ticket/492
+	     */
+	    pjsip_restore_strict_route_set(tdata);
+
+	    /* Set target */
+	    tdata->msg->line.req.uri = (pjsip_uri*)
+	       pjsip_uri_clone(tdata->pool, inv->dlg->target_set.current->uri);
+
+	    /* Remove branch param in Via header. */
+	    via = (pjsip_via_hdr*) 
+		  pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL);
+	    via->branch_param.slen = 0;
+
+	    /* Process PJSIP_REDIRECT_ACCEPT_REPLACE */
+	    if (op == PJSIP_REDIRECT_ACCEPT_REPLACE) {
+		pjsip_to_hdr *to;
+		pjsip_dialog *dlg = inv->dlg;
+		enum { TMP_LEN = 128 };
+		char tmp[TMP_LEN];
+		int len;
+
+		/* Replace To header */
+		to = PJSIP_MSG_TO_HDR(tdata->msg);
+		to->uri = (pjsip_uri*)
+			  pjsip_uri_clone(tdata->pool,
+				          dlg->target_set.current->uri);
+		to->tag.slen = 0;
+		pj_list_init(&to->other_param);
+		
+		/* Re-init dialog remote info */
+		dlg->remote.info = (pjsip_to_hdr*)
+				   pjsip_hdr_clone(dlg->pool, to);
+
+		/* Remove header param from remote info */
+		if (PJSIP_URI_SCHEME_IS_SIP(dlg->remote.info->uri) ||
+		    PJSIP_URI_SCHEME_IS_SIPS(dlg->remote.info->uri))
+		{
+		    pjsip_sip_uri *sip_uri = (pjsip_sip_uri *) 
+				   pjsip_uri_get_uri(dlg->remote.info->uri);
+		    if (!pj_list_empty(&sip_uri->header_param)) {
+			/* Remove all header param */
+			pj_list_init(&sip_uri->header_param);
+		    }
+		}
+
+		/* Print the remote info. */
+		len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR,
+				      dlg->remote.info->uri, tmp, TMP_LEN);
+		if (len < 1) {
+		    pj_ansi_strcpy(tmp, "<-error: uri too long->");
+		    len = (int)pj_ansi_strlen(tmp);
+		}
+		pj_strdup2_with_null(dlg->pool, &dlg->remote.info_str, tmp);
+
+		/* Secure? */
+		dlg->secure = PJSIP_URI_SCHEME_IS_SIPS(to->uri);
+	    }
+
+	    /* Reset message destination info (see #1248). */
+	    pj_bzero(&tdata->dest_info, sizeof(tdata->dest_info));
+
+	    /* Must invalidate the message! */
+	    pjsip_tx_data_invalidate_msg(tdata);
+
+	    /* Reset the session */
+	    pjsip_inv_uac_restart(inv, PJ_FALSE);
+
+	    /* (re)Send the INVITE request */
+	    status = pjsip_inv_send_msg(inv, tdata);
+	}
+	break;
+
+    case PJSIP_REDIRECT_STOP:
+	/* User doesn't want the redirection. Disconnect the session now. */
+	inv_set_cause(inv, cancel_code, pjsip_get_status_text(cancel_code));
+	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+
+	/* Caller should expect that the invite session is gone now, so
+	 * we don't need to set status to PJSIP_ESESSIONTERMINATED here.
+	 */
+	break;
+
+    case PJSIP_REDIRECT_REJECT:
+	/* Current target is rejected. Fetch next target if any. */
+	if (inv_uac_recurse(inv, cancel_code, NULL, NULL) == PJ_FALSE) {
+	    inv_set_cause(inv, cancel_code, 
+			  pjsip_get_status_text(cancel_code));
+	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+
+	    /* Tell caller that the invite session is gone now */
+	    status = PJSIP_ESESSIONTERMINATED;
+	}
+	break;
+
+
+    case PJSIP_REDIRECT_PENDING:
+	pj_assert(!"Should not happen");
+	break;
+    }
+
+
+    pjsip_dlg_dec_lock(inv->dlg);
+
+    return status;
+}
+
+
+/*
+ * Create re-INVITE.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_reinvite( pjsip_inv_session *inv,
+					const pj_str_t *new_contact,
+					const pjmedia_sdp_session *new_offer,
+					pjsip_tx_data **p_tdata )
+{
+    pj_status_t status;
+    pjsip_contact_hdr *contact_hdr = NULL;
+
+    /* Check arguments. */
+    PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
+
+    /* Must NOT have a pending INVITE transaction */
+    if (inv->invite_tsx!=NULL)
+	return PJ_EINVALIDOP;
+
+    pj_log_push_indent();
+
+    pjsip_dlg_inc_lock(inv->dlg);
+
+    if (new_contact) {
+	pj_str_t tmp;
+	const pj_str_t STR_CONTACT = { "Contact", 7 };
+
+	pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact);
+	contact_hdr = (pjsip_contact_hdr*)
+		      pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT, 
+				      tmp.ptr, tmp.slen, NULL);
+	if (!contact_hdr) {
+	    status = PJSIP_EINVALIDURI;
+	    goto on_return;
+	}
+    }
+
+
+    if (new_offer) {
+	if (!inv->neg) {
+	    status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, 
+							  new_offer,
+							  &inv->neg);
+	    if (status != PJ_SUCCESS)
+		goto on_return;
+
+	} else switch (pjmedia_sdp_neg_get_state(inv->neg)) {
+
+	    case PJMEDIA_SDP_NEG_STATE_NULL:
+		pj_assert(!"Unexpected SDP neg state NULL");
+		status = PJ_EBUG;
+		goto on_return;
+
+	    case PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER:
+		PJ_LOG(4,(inv->obj_name, 
+			  "pjsip_inv_reinvite: already have an offer, new "
+			  "offer is ignored"));
+		break;
+
+	    case PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER:
+		status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov, 
+							  inv->neg,
+							  new_offer);
+		if (status != PJ_SUCCESS)
+		    goto on_return;
+		break;
+
+	    case PJMEDIA_SDP_NEG_STATE_WAIT_NEGO:
+		PJ_LOG(4,(inv->obj_name, 
+			  "pjsip_inv_reinvite: SDP in WAIT_NEGO state, new "
+			  "offer is ignored"));
+		break;
+
+	    case PJMEDIA_SDP_NEG_STATE_DONE:
+		status = pjmedia_sdp_neg_modify_local_offer2(
+                             inv->pool_prov, inv->neg,
+                             inv->sdp_neg_flags, new_offer);
+		if (status != PJ_SUCCESS)
+		    goto on_return;
+		break;
+	}
+    }
+
+    if (contact_hdr)
+	inv->dlg->local.contact = contact_hdr;
+
+    status = pjsip_inv_invite(inv, p_tdata);
+
+on_return:
+    pjsip_dlg_dec_lock(inv->dlg);
+    pj_log_pop_indent();
+    return status;
+}
+
+/*
+ * Create UPDATE.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_update (	pjsip_inv_session *inv,
+					const pj_str_t *new_contact,
+					const pjmedia_sdp_session *offer,
+					pjsip_tx_data **p_tdata )
+{
+    pjsip_contact_hdr *contact_hdr = NULL;
+    pjsip_tx_data *tdata = NULL;
+    pjmedia_sdp_session *sdp_copy;
+    const pjsip_hdr *hdr;
+    pj_status_t status = PJ_SUCCESS;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
+
+    /* Dialog must have been established */
+    PJ_ASSERT_RETURN(inv->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED,
+		     PJ_EINVALIDOP);
+
+    /* Invite session must not have been disconnected */
+    PJ_ASSERT_RETURN(inv->state < PJSIP_INV_STATE_DISCONNECTED,
+		     PJ_EINVALIDOP);
+
+    pj_log_push_indent();
+
+    /* Lock dialog. */
+    pjsip_dlg_inc_lock(inv->dlg);
+
+    /* Process offer, if any */
+    if (offer) {
+	if (pjmedia_sdp_neg_get_state(inv->neg)!=PJMEDIA_SDP_NEG_STATE_DONE) {
+	    PJ_LOG(4,(inv->dlg->obj_name,
+		      "Invalid SDP offer/answer state for UPDATE"));
+	    status = PJ_EINVALIDOP;
+	    goto on_error;
+	}
+
+	/* Notify negotiator about the new offer. This will fix the offer
+	 * with correct SDP origin.
+	 */
+	status = pjmedia_sdp_neg_modify_local_offer2(inv->pool_prov, inv->neg,
+						     inv->sdp_neg_flags, offer);
+	if (status != PJ_SUCCESS)
+	    goto on_error;
+
+	/* Retrieve the "fixed" offer from negotiator */
+	pjmedia_sdp_neg_get_neg_local(inv->neg, &offer);
+    }
+
+    /* Update Contact if required */
+    if (new_contact) {
+	pj_str_t tmp;
+	const pj_str_t STR_CONTACT = { "Contact", 7 };
+
+	pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact);
+	contact_hdr = (pjsip_contact_hdr*)
+		      pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT, 
+				      tmp.ptr, tmp.slen, NULL);
+	if (!contact_hdr) {
+	    status = PJSIP_EINVALIDURI;
+	    goto on_error;
+	}
+
+	inv->dlg->local.contact = contact_hdr;
+    }
+
+    /* Create request */
+    status = pjsip_dlg_create_request(inv->dlg, &pjsip_update_method,
+				      -1, &tdata);
+    if (status != PJ_SUCCESS)
+	    goto on_error;
+
+    /* Attach SDP body */
+    if (offer) {
+	sdp_copy = pjmedia_sdp_session_clone(tdata->pool, offer);
+	pjsip_create_sdp_body(tdata->pool, sdp_copy, &tdata->msg->body);
+    }
+
+    /* Session Timers spec (RFC 4028) says that Supported header MUST be put
+     * in refresh requests. So here we'll just put the Supported header in
+     * all cases regardless of whether session timers is used or not, just
+     * in case this is a common behavior.
+     */
+    hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_SUPPORTED, NULL);
+    if (hdr) {
+	pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)
+			  pjsip_hdr_shallow_clone(tdata->pool, hdr));
+    }
+
+    status = pjsip_timer_update_req(inv, tdata);
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Unlock dialog. */
+    pjsip_dlg_dec_lock(inv->dlg);
+
+    *p_tdata = tdata;
+
+    pj_log_pop_indent();
+    return PJ_SUCCESS;
+
+on_error:
+    if (tdata)
+	pjsip_tx_data_dec_ref(tdata);
+
+    /* Unlock dialog. */
+    pjsip_dlg_dec_lock(inv->dlg);
+
+    pj_log_pop_indent();
+    return status;
+}
+
+/*
+ * Create an ACK request.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_create_ack(pjsip_inv_session *inv,
+					 int cseq,
+					 pjsip_tx_data **p_tdata)
+{
+    const pjmedia_sdp_session *sdp = NULL;
+    pj_status_t status;
+
+    PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
+
+    /* Lock dialog. */
+    pjsip_dlg_inc_lock(inv->dlg);
+
+    /* Destroy last_ack */
+    if (inv->last_ack) {
+	pjsip_tx_data_dec_ref(inv->last_ack);
+	inv->last_ack = NULL;
+    }
+
+    /* Create new ACK request */
+    status = pjsip_dlg_create_request(inv->dlg, pjsip_get_ack_method(), 
+				      cseq, &inv->last_ack);
+    if (status != PJ_SUCCESS) {
+	pjsip_dlg_dec_lock(inv->dlg);
+	return status;
+    }
+
+    /* See if we have pending SDP answer to send */
+    sdp = inv_has_pending_answer(inv, inv->invite_tsx);
+    if (sdp) {
+	inv->last_ack->msg->body = create_sdp_body(inv->last_ack->pool, sdp);
+    }
+
+    /* Keep this for subsequent response retransmission */
+    inv->last_ack_cseq = cseq;
+    pjsip_tx_data_add_ref(inv->last_ack);
+
+    /* Done */
+    *p_tdata = inv->last_ack;
+
+    /* Unlock dialog. */
+    pjsip_dlg_dec_lock(inv->dlg);
+
+    return PJ_SUCCESS;
+}
+
+/*
+ * Send a request or response message.
+ */
+PJ_DEF(pj_status_t) pjsip_inv_send_msg( pjsip_inv_session *inv,
+					pjsip_tx_data *tdata)
+{
+    pj_status_t status;
+
+    /* Verify arguments. */
+    PJ_ASSERT_RETURN(inv && tdata, PJ_EINVAL);
+
+    pj_log_push_indent();
+
+    PJ_LOG(5,(inv->obj_name, "Sending %s", 
+	      pjsip_tx_data_get_info(tdata)));
+
+    if (tdata->msg->type == PJSIP_REQUEST_MSG) {
+	struct tsx_inv_data *tsx_inv_data;
+
+	pjsip_dlg_inc_lock(inv->dlg);
+
+	/* Check again that we didn't receive incoming re-INVITE */
+	if (tdata->msg->line.req.method.id==PJSIP_INVITE_METHOD && 
+	    inv->invite_tsx) 
+	{
+	    pjsip_tx_data_dec_ref(tdata);
+	    pjsip_dlg_dec_lock(inv->dlg);
+	    status = PJ_EINVALIDOP;
+	    goto on_error;
+	}
+
+	/* Don't send BYE before ACK is received
+	 * http://trac.pjsip.org/repos/ticket/1712
+	 */
+	if (tdata->msg->line.req.method.id == PJSIP_BYE_METHOD &&
+	    inv->role == PJSIP_ROLE_UAS &&
+	    inv->state == PJSIP_INV_STATE_CONNECTING)
+	{
+	    if (inv->pending_bye)
+		pjsip_tx_data_dec_ref(inv->pending_bye);
+
+	    inv->pending_bye = tdata;
+	    PJ_LOG(4, (inv->obj_name, "Delaying BYE request until "
+		       "ACK is received"));
+	    pjsip_dlg_dec_lock(inv->dlg);
+	    goto on_return;
+	}
+
+	/* Associate our data in outgoing invite transaction */
+	tsx_inv_data = PJ_POOL_ZALLOC_T(inv->pool, struct tsx_inv_data);
+	tsx_inv_data->inv = inv;
+
+	pjsip_dlg_dec_lock(inv->dlg);
+
+	status = pjsip_dlg_send_request(inv->dlg, tdata, mod_inv.mod.id, 
+					tsx_inv_data);
+	if (status != PJ_SUCCESS) {
+	    goto on_error;
+	}
+
+    } else {
+	pjsip_cseq_hdr *cseq;
+
+	/* Can only do this to send response to original INVITE
+	 * request.
+	 */
+	PJ_ASSERT_RETURN((cseq=(pjsip_cseq_hdr*)pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL))!=NULL
+			  && (cseq->cseq == inv->invite_tsx->cseq),
+			 PJ_EINVALIDOP);
+
+	if (inv->options & PJSIP_INV_REQUIRE_100REL) {
+	    status = pjsip_100rel_tx_response(inv, tdata);
+	} else 
+	{
+	    status = pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata);
+	}
+
+	if (status != PJ_SUCCESS) {
+	    goto on_error;
+	}
+    }
+
+    /* Done */
+on_return:
+    pj_log_pop_indent();
+    return PJ_SUCCESS;
+
+on_error:
+    pj_log_pop_indent();
+    return status;
+}
+
+
+/*
+ * Respond to incoming CANCEL request.
+ */
+static void inv_respond_incoming_cancel(pjsip_inv_session *inv,
+					pjsip_transaction *cancel_tsx,
+					pjsip_event *e)
+{
+    pjsip_tx_data *tdata;
+    pjsip_transaction *invite_tsx;
+    pjsip_rx_data *rdata;
+    pj_str_t key;
+    pj_status_t status;
+
+    pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
+    rdata = e->body.tsx_state.src.rdata;
+
+    /* https://trac.pjsip.org/repos/ticket/1651
+     * Special treatment for CANCEL. Since here we're responding to CANCEL
+     * automatically (including 487 to INVITE), application will see the
+     * 200/OK response to CANCEL first in the callback, and then 487 to
+     * INVITE, before the CANCEL request itself. And worse, pjsua application
+     * may not see the CANCEL request at all because by the time the CANCEL
+     * request is reported, call has been disconnected and further events
+     * from the INVITE session has been suppressed.
+     */
+    if (mod_inv.cb.on_tsx_state_changed && inv->notify)
+	(*mod_inv.cb.on_tsx_state_changed)(inv, cancel_tsx, e);
+
+    /* See if we have matching INVITE server transaction: */
+
+    pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS,
+			 pjsip_get_invite_method(), rdata);
+    invite_tsx = pjsip_tsx_layer_find_tsx(&key, PJ_TRUE);
+
+    if (invite_tsx == NULL) {
+
+	/* Invite transaction not found! 
+	 * Respond CANCEL with 481 (RFC 3261 Section 9.2 page 55)
+	 */
+	status = pjsip_dlg_create_response( inv->dlg, rdata, 481, NULL, 
+					    &tdata);
+
+    } else {
+	/* Always answer CANCEL will 200 (OK) regardless of
+	 * the state of the INVITE transaction.
+	 */
+	status = pjsip_dlg_create_response( inv->dlg, rdata, 200, NULL, 
+					    &tdata);
+    }
+
+    /* See if we have created the response successfully. */
+    if (status != PJ_SUCCESS) return;
+
+    /* Send the CANCEL response */
+    status = pjsip_dlg_send_response(inv->dlg, cancel_tsx, tdata);
+    if (status != PJ_SUCCESS) return;
+
+
+    /* See if we need to terminate the UAS INVITE transaction
+     * with 487 (Request Terminated) response. 
+     */
+    if (invite_tsx && invite_tsx->status_code < 200) {
+
+	pj_assert(invite_tsx->last_tx != NULL);
+
+	tdata = invite_tsx->last_tx;
+
+	status = pjsip_dlg_modify_response(inv->dlg, tdata, 487, NULL);
+	if (status == PJ_SUCCESS) {
+	    /* Remove the message body */
+	    tdata->msg->body = NULL;
+	    if (inv->options & PJSIP_INV_REQUIRE_100REL) {
+		status = pjsip_100rel_tx_response(inv, tdata);
+	    } else {
+		status = pjsip_dlg_send_response(inv->dlg, invite_tsx, 
+						 tdata);
+	    }
+	}
+    }
+
+    if (invite_tsx)
+	pj_grp_lock_release(invite_tsx->grp_lock);
+}
+
+
+/*
+ * Respond to incoming BYE request.
+ */
+static void inv_respond_incoming_bye( pjsip_inv_session *inv,
+				      pjsip_transaction *bye_tsx,
+				      pjsip_rx_data *rdata,
+				      pjsip_event *e )
+{
+    pj_status_t status;
+    pjsip_tx_data *tdata;
+
+    /* Respond BYE with 200: */
+
+    status = pjsip_dlg_create_response(inv->dlg, rdata, 200, NULL, &tdata);
+    if (status != PJ_SUCCESS) return;
+
+    status = pjsip_dlg_send_response(inv->dlg, bye_tsx, tdata);
+    if (status != PJ_SUCCESS) return;
+
+    /* Terminate session: */
+
+    if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {
+	inv_set_cause(inv, PJSIP_SC_OK, NULL);
+	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+    }
+}
+
+/*
+ * Respond to BYE request.
+ */
+static void inv_handle_bye_response( pjsip_inv_session *inv,
+				     pjsip_transaction *tsx,
+				     pjsip_rx_data *rdata,
+				     pjsip_event *e )
+{
+    pj_status_t status;
+    
+    if (e->body.tsx_state.type != PJSIP_EVENT_RX_MSG) {
+	inv_set_cause(inv, PJSIP_SC_OK, NULL);
+	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	return;
+    }
+
+    /* Handle 401/407 challenge. */
+    if (tsx->status_code == 401 || tsx->status_code == 407) {
+
+	pjsip_tx_data *tdata;
+	
+	status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, 
+					    rdata,
+					    tsx->last_tx,
+					    &tdata);
+	
+	if (status != PJ_SUCCESS) {
+	    
+	    /* Does not have proper credentials. 
+	     * End the session anyway.
+	     */
+	    inv_set_cause(inv, PJSIP_SC_OK, NULL);
+	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	    
+	} else {
+	    struct tsx_inv_data *tsx_inv_data;
+
+	    tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
+	    if (tsx_inv_data)
+		tsx_inv_data->retrying = PJ_TRUE;
+
+	    /* Re-send BYE. */
+	    status = pjsip_inv_send_msg(inv, tdata);
+	}
+
+    } else {
+
+	/* End the session. */
+	inv_set_cause(inv, PJSIP_SC_OK, NULL);
+	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+    }
+
+}
+
+/*
+ * Respond to incoming UPDATE request.
+ */
+static void inv_respond_incoming_update(pjsip_inv_session *inv,
+					pjsip_rx_data *rdata)
+{
+    pjmedia_sdp_neg_state neg_state;
+    pj_status_t status;
+    pjsip_tx_data *tdata = NULL;
+    pjsip_status_code st_code;
+
+    /* Invoke Session Timers module */
+    status = pjsip_timer_process_req(inv, rdata, &st_code);
+    if (status != PJ_SUCCESS) {
+	status = pjsip_dlg_create_response(inv->dlg, rdata, st_code,
+					   NULL, &tdata);
+	goto on_return;
+    }
+
+    neg_state = pjmedia_sdp_neg_get_state(inv->neg);
+
+    /* If UPDATE doesn't contain SDP, just respond with 200/OK.
+     * This is a valid scenario according to session-timer draft.
+     */
+    if (rdata->msg_info.msg->body == NULL) {
+
+	status = pjsip_dlg_create_response(inv->dlg, rdata, 
+					   200, NULL, &tdata);
+    }
+    /* Send 491 if we receive UPDATE while we're waiting for an answer */
+    else if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) {
+	status = pjsip_dlg_create_response(inv->dlg, rdata, 
+					   PJSIP_SC_REQUEST_PENDING, NULL,
+					   &tdata);
+    }
+    /* Send 500 with Retry-After header set randomly between 0 and 10 if we 
+     * receive UPDATE while we haven't sent answer.
+     */
+    else if (neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER ||
+	     neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)
+    {
+        pjsip_retry_after_hdr *ra_hdr;
+	int val;
+
+        status = pjsip_dlg_create_response(inv->dlg, rdata, 
+					   PJSIP_SC_INTERNAL_SERVER_ERROR,
+					   NULL, &tdata);
+
+        val = (pj_rand() % 10);
+        ra_hdr = pjsip_retry_after_hdr_create(tdata->pool, val);
+        pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)ra_hdr);
+
+    } else {
+	/* We receive new offer from remote */
+	inv_check_sdp_in_incoming_msg(inv, pjsip_rdata_get_tsx(rdata), rdata);
+
+	/* Application MUST have supplied the answer by now.
+	 * If so, negotiate the SDP.
+	 */
+	neg_state = pjmedia_sdp_neg_get_state(inv->neg);
+	if (neg_state != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO ||
+	    (status=inv_negotiate_sdp(inv)) != PJ_SUCCESS)
+	{
+	    /* Negotiation has failed. If negotiator is still
+	     * stuck at non-DONE state, cancel any ongoing offer.
+	     */
+	    neg_state = pjmedia_sdp_neg_get_state(inv->neg);
+	    if (neg_state != PJMEDIA_SDP_NEG_STATE_DONE) {
+		pjmedia_sdp_neg_cancel_offer(inv->neg);
+	    }
+
+	    status = pjsip_dlg_create_response(inv->dlg, rdata, 
+					       PJSIP_SC_NOT_ACCEPTABLE_HERE,
+					       NULL, &tdata);
+	} else {
+	    /* New media has been negotiated successfully, send 200/OK */
+	    status = pjsip_dlg_create_response(inv->dlg, rdata, 
+					       PJSIP_SC_OK, NULL, &tdata);
+	    if (status == PJ_SUCCESS) {
+		const pjmedia_sdp_session *sdp;
+		status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp);
+		if (status == PJ_SUCCESS)
+		    tdata->msg->body = create_sdp_body(tdata->pool, sdp);
+	    }
+	}
+    }
+
+on_return:
+    /* Invoke Session Timers */
+    if (status == PJ_SUCCESS)
+	status = pjsip_timer_update_resp(inv, tdata);
+
+    if (status != PJ_SUCCESS) {
+	if (tdata != NULL) {
+	    pjsip_tx_data_dec_ref(tdata);
+	    tdata = NULL;
+	}
+	return;
+    }
+
+    pjsip_dlg_send_response(inv->dlg, pjsip_rdata_get_tsx(rdata), tdata);
+}
+
+
+/*
+ * Handle incoming response to UAC UPDATE request.
+ */
+static pj_bool_t inv_handle_update_response( pjsip_inv_session *inv,
+                                             pjsip_event *e)
+{
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+    struct tsx_inv_data *tsx_inv_data;
+    pj_bool_t handled = PJ_FALSE;
+    pj_status_t status = -1;
+
+    tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
+    pj_assert(tsx_inv_data);
+
+    /* Handle 401/407 challenge. */
+    if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
+	(tsx->status_code == 401 || tsx->status_code == 407))
+    {
+	pjsip_tx_data *tdata;
+
+	status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, 
+					    e->body.tsx_state.src.rdata,
+					    tsx->last_tx,
+					    &tdata);
+	
+	if (status != PJ_SUCCESS) {
+	    
+	    /* Somehow failed. Probably it's not a good idea to terminate
+	     * the session since this is just a request within dialog. And
+	     * even if we terminate we should send BYE.
+	     */
+	    /*
+	    inv_set_cause(inv, PJSIP_SC_OK, NULL);
+	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	    */
+	    
+	} else {
+	    if (tsx_inv_data)
+		tsx_inv_data->retrying = PJ_TRUE;
+
+	    /* Re-send request. */
+	    status = pjsip_inv_send_msg(inv, tdata);
+	}
+
+	handled = PJ_TRUE;
+    }
+
+    /* Process 422 response */
+    else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
+	     tsx->status_code == 422)
+    {
+	status = handle_timer_response(inv, e->body.tsx_state.src.rdata,
+				       PJ_FALSE);
+	handled = PJ_TRUE;
+    }
+
+    /* Process 2xx response */
+    else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
+	tsx->status_code/100 == 2 &&
+	e->body.tsx_state.src.rdata->msg_info.msg->body)
+    {
+	status = handle_timer_response(inv, e->body.tsx_state.src.rdata,
+				       PJ_FALSE);
+	status = inv_check_sdp_in_incoming_msg(inv, tsx, 
+					     e->body.tsx_state.src.rdata);
+	handled = PJ_TRUE;
+    }
+    
+    /* Get/attach invite session's transaction data */
+    else 
+    {
+	/* Session-Timer needs to see any error responses, to determine
+	 * whether peer supports UPDATE with empty body.
+	 */
+	if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
+	    tsx->role == PJSIP_ROLE_UAC)
+	{
+	    status = handle_timer_response(inv, e->body.tsx_state.src.rdata,
+					   PJ_FALSE);
+	    handled = PJ_TRUE;
+	}
+    }
+
+    /* Cancel the negotiation if we don't get successful negotiation by now,
+     * unless it's authentication challenge and the request is being retried.
+     */
+    if (pjmedia_sdp_neg_get_state(inv->neg) ==
+		PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER &&
+	tsx_inv_data && tsx_inv_data->sdp_done == PJ_FALSE &&
+	!tsx_inv_data->retrying)
+    {
+	pjmedia_sdp_neg_cancel_offer(inv->neg);
+
+	/* Prevent from us cancelling different offer! */
+	tsx_inv_data->sdp_done = PJ_TRUE;
+    }
+
+    return handled;
+}
+
+
+/*
+ * Handle incoming reliable response.
+ */
+static void inv_handle_incoming_reliable_response(pjsip_inv_session *inv,
+						  pjsip_rx_data *rdata)
+{
+    pjsip_tx_data *tdata;
+    const pjmedia_sdp_session *sdp;
+    pj_status_t status;
+
+    /* Create PRACK */
+    status = pjsip_100rel_create_prack(inv, rdata, &tdata);
+    if (status != PJ_SUCCESS)
+	return;
+
+    /* See if we need to attach SDP answer on the PRACK request */
+    sdp = inv_has_pending_answer(inv, pjsip_rdata_get_tsx(rdata));
+    if (sdp) {
+	tdata->msg->body = create_sdp_body(tdata->pool, sdp);
+    }
+
+    /* Send PRACK (must be using 100rel module!) */
+    pjsip_100rel_send_prack(inv, tdata);
+}
+
+
+/*
+ * Handle incoming PRACK.
+ */
+static void inv_respond_incoming_prack(pjsip_inv_session *inv,
+				       pjsip_rx_data *rdata)
+{
+    pj_status_t status;
+
+    /* Run through 100rel module to see if we can accept this
+     * PRACK request. The 100rel will send 200/OK to PRACK request.
+     */
+    status = pjsip_100rel_on_rx_prack(inv, rdata);
+    if (status != PJ_SUCCESS)
+	return;
+
+    /* Now check for SDP answer in the PRACK request */
+    if (rdata->msg_info.msg->body) {
+	status = inv_check_sdp_in_incoming_msg(inv, 
+					pjsip_rdata_get_tsx(rdata), rdata);
+    } else {
+	/* No SDP body */
+	status = -1;
+    }
+
+    /* If SDP negotiation has been successful, also mark the
+     * SDP negotiation flag in the invite transaction to be
+     * done too.
+     */
+    if (status == PJ_SUCCESS && inv->invite_tsx) {
+	struct tsx_inv_data *tsx_inv_data;
+
+	/* Get/attach invite session's transaction data */
+	tsx_inv_data = (struct tsx_inv_data*) 
+		       inv->invite_tsx->mod_data[mod_inv.mod.id];
+	if (tsx_inv_data == NULL) {
+	    tsx_inv_data = PJ_POOL_ZALLOC_T(inv->invite_tsx->pool, 
+					    struct tsx_inv_data);
+	    tsx_inv_data->inv = inv;
+	    inv->invite_tsx->mod_data[mod_inv.mod.id] = tsx_inv_data;
+	}
+	
+	tsx_inv_data->sdp_done = PJ_TRUE;
+    }
+}
+
+
+/*
+ * State NULL is before anything is sent/received.
+ */
+static void inv_on_state_null( pjsip_inv_session *inv, pjsip_event *e)
+{
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+    pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
+
+    PJ_ASSERT_ON_FAIL(tsx && dlg, return);
+
+    if (tsx->method.id == PJSIP_INVITE_METHOD) {
+
+	/* Keep the initial INVITE transaction. */
+	if (inv->invite_tsx == NULL)
+	    inv->invite_tsx = tsx;
+
+	if (dlg->role == PJSIP_ROLE_UAC) {
+
+	    /* Save the original INVITE request.
+             * We may need to resend the INVITE if we receive redirection
+             * or session timer too small response.
+	     */
+	    if (1) {
+		if (inv->invite_req) {
+		    pjsip_tx_data_dec_ref(inv->invite_req);
+		    inv->invite_req = NULL;
+		}
+		inv->invite_req = tsx->last_tx;
+		pjsip_tx_data_add_ref(inv->invite_req);
+	    }
+
+	    switch (tsx->state) {
+	    case PJSIP_TSX_STATE_CALLING:
+		inv_set_state(inv, PJSIP_INV_STATE_CALLING, e);
+		break;
+	    default:
+		inv_on_state_calling(inv, e);
+		break;
+	    }
+
+	} else {
+	    switch (tsx->state) {
+	    case PJSIP_TSX_STATE_TRYING:
+		inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e);
+		break;
+	    case PJSIP_TSX_STATE_PROCEEDING:
+		inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e);
+		if (tsx->status_code > 100)
+		    inv_set_state(inv, PJSIP_INV_STATE_EARLY, e);
+		break;
+	    case PJSIP_TSX_STATE_TERMINATED:
+		/* there is a failure in sending response. */
+		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+		break;
+	    default:
+		inv_on_state_incoming(inv, e);
+		break;
+	    }
+	}
+
+    } else {
+	pj_assert(!"Unexpected transaction type");
+    }
+}
+
+/*
+ * Generic UAC transaction handler:
+ *  - resend request on 401 or 407 response.
+ *  - terminate dialog on 408 and 481 response.
+ *  - resend request on 422 response.
+ */
+static pj_bool_t handle_uac_tsx_response(pjsip_inv_session *inv, 
+					 pjsip_event *e)
+{
+    /* RFC 3261 Section 12.2.1.2:
+     *  If the response for a request within a dialog is a 481
+     *  (Call/Transaction Does Not Exist) or a 408 (Request Timeout), the UAC
+     *  SHOULD terminate the dialog.  A UAC SHOULD also terminate a dialog if
+     *  no response at all is received for the request (the client
+     *  transaction would inform the TU about the timeout.)
+     * 
+     *  For INVITE initiated dialogs, terminating the dialog consists of
+     *  sending a BYE.
+     *
+     * Note:
+     *  according to X, this should terminate dialog usage only, not the 
+     *  dialog.
+     */
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+
+    pj_assert(tsx->role == PJSIP_UAC_ROLE);
+
+    /* Note that 481 response to CANCEL does not terminate dialog usage,
+     * but only the transaction.
+     */
+    if (inv->state != PJSIP_INV_STATE_DISCONNECTED &&
+	((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST &&
+	    tsx->method.id != PJSIP_CANCEL_METHOD) ||
+	 tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT ||
+	 tsx->status_code == PJSIP_SC_TSX_TIMEOUT))
+    {
+	pjsip_tx_data *bye;
+	pj_status_t status;
+
+	inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+
+	/* Send BYE */
+	status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(), 
+					  -1, &bye);
+	if (status == PJ_SUCCESS) {
+	    pjsip_inv_send_msg(inv, bye);
+	}
+
+	return PJ_TRUE; /* Handled */
+
+    } 
+    /* Handle 401/407 challenge. */
+    else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
+	     (tsx->status_code == PJSIP_SC_UNAUTHORIZED ||
+	      tsx->status_code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED)) 
+    {
+	pjsip_tx_data *tdata;
+	pj_status_t status;
+
+	if (tsx->method.id == PJSIP_INVITE_METHOD)
+	    inv->invite_tsx = NULL;
+
+	status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, 
+					    e->body.tsx_state.src.rdata,
+					    tsx->last_tx, &tdata);
+    
+	if (status != PJ_SUCCESS) {
+	    /* Somehow failed. Probably it's not a good idea to terminate
+	     * the session since this is just a request within dialog. And
+	     * even if we terminate we should send BYE.
+	     */
+	    /*
+	    inv_set_cause(inv, PJSIP_SC_OK, NULL);
+	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	    */
+	    
+	} else {
+	    struct tsx_inv_data *tsx_inv_data;
+
+	    tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
+	    if (tsx_inv_data)
+		tsx_inv_data->retrying = PJ_TRUE;
+
+	    /* Re-send request. */
+	    status = pjsip_inv_send_msg(inv, tdata);
+	}
+
+	return PJ_TRUE;	/* Handled */
+    }
+
+    /* Handle session timer 422 response. */
+    else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
+	     tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) 
+    {
+	handle_timer_response(inv, e->body.tsx_state.src.rdata, 
+			      PJ_FALSE);
+
+	return PJ_TRUE;	/* Handled */
+
+    } else {
+	return PJ_FALSE; /* Unhandled */
+    }
+}
+
+
+/* Handle call rejection, especially with regard to processing call
+ * redirection. We need to handle the following scenarios:
+ *  - 3xx response is received -- see if on_redirected() callback is
+ *    implemented. If so, add the Contact URIs in the response to the
+ *    target set and notify user.
+ *  - 4xx - 6xx resposne is received -- see if we're currently recursing,
+ *    if so fetch the next target if any and notify the on_redirected()
+ *    callback.
+ *  - for other cases -- disconnect the session.
+ */
+static void handle_uac_call_rejection(pjsip_inv_session *inv, pjsip_event *e)
+{
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+    pj_status_t status;
+    
+    if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 300)) {
+
+	if (mod_inv.cb.on_redirected == NULL) {
+
+	    /* Redirection callback is not implemented, disconnect the
+	     * call.
+	     */
+	    goto terminate_session;
+
+	} else {
+	    const pjsip_msg *res_msg;
+
+	    res_msg = e->body.tsx_state.src.rdata->msg_info.msg;
+
+	    /* Gather all Contact URI's in the response and add them
+	     * to target set. The function will take care of removing
+	     * duplicate URI's.
+	     */
+	    pjsip_target_set_add_from_msg(&inv->dlg->target_set, 
+					  inv->dlg->pool, res_msg);
+
+	    /* Recurse to alternate targets if application allows us */
+	    if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e))
+	    {
+		/* Recursion fails, terminate session now */
+		goto terminate_session;
+	    }
+
+	    /* Done */
+	}
+
+    } else if ((tsx->status_code==401 || tsx->status_code==407) &&
+		!inv->cancelling) 
+    {
+
+	/* Handle authentication failure:
+	 * Resend the request with Authorization header.
+	 */
+	pjsip_tx_data *tdata;
+
+	status = pjsip_auth_clt_reinit_req(&inv->dlg->auth_sess, 
+					   e->body.tsx_state.src.rdata,
+					   tsx->last_tx,
+					   &tdata);
+
+	if (status != PJ_SUCCESS) {
+
+	    /* Does not have proper credentials. If we are currently 
+	     * recursing, try the next target. Otherwise end the session.
+	     */
+	    if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e))
+	    {
+		/* Recursion fails, terminate session now */
+		goto terminate_session;
+	    }
+
+	} else {
+
+	    /* Restart session. */
+	    pjsip_inv_uac_restart(inv, PJ_FALSE);
+
+	    /* Send the request. */
+	    status = pjsip_inv_send_msg(inv, tdata);
+	}
+
+    } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
+	       tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) 
+    {
+	/* Handle session timer 422 response:
+	 * Resend the request with requested session timer setting.
+	 */
+	status = handle_timer_response(inv, e->body.tsx_state.src.rdata,
+				       PJ_TRUE);
+
+    } else if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 600)) {
+	/* Global error */
+	goto terminate_session;
+
+    } else {
+	/* See if we have alternate target to try */
+	if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) {
+	    /* Recursion fails, terminate session now */
+	    goto terminate_session;
+	}
+    }
+    return;
+
+terminate_session:
+    inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+}
+
+
+/*
+ * State CALLING is after sending initial INVITE request but before
+ * any response (with tag) is received.
+ */
+static void inv_on_state_calling( pjsip_inv_session *inv, pjsip_event *e)
+{
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+    pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
+    pj_status_t status;
+
+    PJ_ASSERT_ON_FAIL(tsx && dlg, return);
+    
+    if (tsx == inv->invite_tsx) {
+
+	switch (tsx->state) {
+
+	case PJSIP_TSX_STATE_CALLING:
+	    inv_set_state(inv, PJSIP_INV_STATE_CALLING, e);
+	    break;
+
+	case PJSIP_TSX_STATE_PROCEEDING:
+	    if (inv->pending_cancel) {
+		pjsip_tx_data *cancel;
+
+		inv->pending_cancel = PJ_FALSE;
+
+		status = pjsip_inv_end_session(inv, 487, NULL, &cancel);
+		if (status == PJ_SUCCESS && cancel)
+		    status = pjsip_inv_send_msg(inv, cancel);
+	    }
+
+	    if (dlg->remote.info->tag.slen) {
+
+		inv_set_state(inv, PJSIP_INV_STATE_EARLY, e);
+
+		inv_check_sdp_in_incoming_msg(inv, tsx, 
+					      e->body.tsx_state.src.rdata);
+
+		if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) {
+		    inv_handle_incoming_reliable_response(
+			inv, e->body.tsx_state.src.rdata);
+		}
+
+	    } else {
+		/* Ignore 100 (Trying) response, as it doesn't change
+		 * session state. It only ceases retransmissions.
+		 */
+	    }
+	    break;
+
+	case PJSIP_TSX_STATE_COMPLETED:
+	    if (tsx->status_code/100 == 2) {
+
+		/* This should not happen.
+		 * When transaction receives 2xx, it should be terminated
+		 */
+		pj_assert(0);
+
+		/* Process session timer response. */
+		status = handle_timer_response(inv,
+					       e->body.tsx_state.src.rdata,
+					       PJ_TRUE);
+		if (status != PJ_SUCCESS)
+		    break;
+
+		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
+    
+		inv_check_sdp_in_incoming_msg(inv, tsx, 
+					      e->body.tsx_state.src.rdata);
+
+	    } else {
+		handle_uac_call_rejection(inv, e);
+	    }
+	    break;
+
+	case PJSIP_TSX_STATE_TERMINATED:
+	    /* INVITE transaction can be terminated either because UAC
+	     * transaction received 2xx response or because of transport
+	     * error.
+	     */
+	    if (tsx->status_code/100 == 2) {
+		/* This must be receipt of 2xx response */
+
+		/* Process session timer response. */
+		status = handle_timer_response(inv,
+					       e->body.tsx_state.src.rdata,
+					       PJ_TRUE);
+		if (status != PJ_SUCCESS)
+		    break;
+
+		/* Set state to CONNECTING */
+		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
+
+		inv_check_sdp_in_incoming_msg(inv, tsx, 
+					      e->body.tsx_state.src.rdata);
+
+		/* Send ACK */
+		pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
+
+		inv_send_ack(inv, e);
+
+	    } else  {
+		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	    }
+	    break;
+
+	default:
+	    break;
+	}
+
+    } else if (tsx->role == PJSIP_ROLE_UAC) {
+	/*
+	 * Handle case when outgoing request is answered with 481 (Call/
+	 * Transaction Does Not Exist), 408, or when it's timed out. In these
+	 * cases, disconnect session (i.e. dialog usage only).
+	 * Note that 481 response to CANCEL does not terminate dialog usage,
+	 * but only the transaction.
+	 */
+	if ((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST &&
+		tsx->method.id != PJSIP_CANCEL_METHOD) ||
+	    tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT ||
+	    tsx->status_code == PJSIP_SC_TSX_TIMEOUT ||
+	    tsx->status_code == PJSIP_SC_TSX_TRANSPORT_ERROR)
+	{
+	    inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	}
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->state == PJSIP_TSX_STATE_TRYING &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
+    {
+	/*
+	 * Handle a very early UPDATE
+	 */
+	inv_respond_incoming_update(inv, e->body.tsx_state.src.rdata);
+
+
+    }
+}
+
+/*
+ * State INCOMING is after we received the request, but before
+ * responses with tag are sent.
+ */
+static void inv_on_state_incoming( pjsip_inv_session *inv, pjsip_event *e)
+{
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+    pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
+
+    PJ_ASSERT_ON_FAIL(tsx && dlg, return);
+
+    if (tsx == inv->invite_tsx) {
+
+	/*
+	 * Handle the INVITE state transition.
+	 */
+
+	switch (tsx->state) {
+
+	case PJSIP_TSX_STATE_TRYING:
+	    inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e);
+	    break;
+
+	case PJSIP_TSX_STATE_PROCEEDING:
+	    /*
+	     * Transaction sent provisional response.
+	     */
+	    if (tsx->status_code > 100)
+		inv_set_state(inv, PJSIP_INV_STATE_EARLY, e);
+	    break;
+
+	case PJSIP_TSX_STATE_COMPLETED:
+	    /*
+	     * Transaction sent final response.
+	     */
+	    if (tsx->status_code/100 == 2) {
+		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
+	    } else {
+		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	    }
+	    break;
+
+	case PJSIP_TSX_STATE_TERMINATED:
+	    /* 
+	     * This happens on transport error (e.g. failed to send
+	     * response)
+	     */
+	    inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	    break;
+
+	default:
+	    pj_assert(!"Unexpected INVITE state");
+	    break;
+	}
+
+    } else if (tsx->method.id == PJSIP_CANCEL_METHOD &&
+	       tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->state < PJSIP_TSX_STATE_COMPLETED &&
+	       e->body.tsx_state.type == PJSIP_EVENT_RX_MSG )
+    {
+
+	/*
+	 * Handle incoming CANCEL request.
+	 */
+
+	inv_respond_incoming_cancel(inv, tsx, e);
+
+    }
+}
+
+/*
+ * State EARLY is for both UAS and UAC, after response with To tag
+ * is sent/received.
+ */
+static void inv_on_state_early( pjsip_inv_session *inv, pjsip_event *e)
+{
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+    pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
+
+    PJ_ASSERT_ON_FAIL(tsx && dlg, return);
+
+    if (tsx == inv->invite_tsx) {
+
+	/*
+	 * Handle the INVITE state progress.
+	 */
+
+	switch (tsx->state) {
+
+	case PJSIP_TSX_STATE_PROCEEDING:
+	    /* Send/received another provisional response. */
+	    inv_set_state(inv, PJSIP_INV_STATE_EARLY, e);
+
+	    if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
+		inv_check_sdp_in_incoming_msg(inv, tsx, 
+					      e->body.tsx_state.src.rdata);
+
+		if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) {
+		    inv_handle_incoming_reliable_response(
+			inv, e->body.tsx_state.src.rdata);
+		}
+	    }
+	    break;
+
+	case PJSIP_TSX_STATE_COMPLETED:
+	    if (tsx->status_code/100 == 2) {
+		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
+		if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
+		    pj_status_t status;
+
+		    /* Process session timer response. */
+		    status = handle_timer_response(inv, 
+						   e->body.tsx_state.src.rdata,
+						   PJ_TRUE);
+		    if (status != PJ_SUCCESS)
+			break;
+
+		    inv_check_sdp_in_incoming_msg(inv, tsx, 
+						  e->body.tsx_state.src.rdata);
+		}
+
+	    } else if (tsx->role == PJSIP_ROLE_UAC) {
+
+		handle_uac_call_rejection(inv, e);
+
+	    } else {
+		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	    }
+	    break;
+
+	case PJSIP_TSX_STATE_CONFIRMED:
+	    /* For some reason can go here (maybe when ACK for 2xx has
+	     * the same branch value as the INVITE transaction) */
+
+	case PJSIP_TSX_STATE_TERMINATED:
+	    /* INVITE transaction can be terminated either because UAC
+	     * transaction received 2xx response or because of transport
+	     * error.
+	     */
+	    if (tsx->status_code/100 == 2) {
+
+		/* This must be receipt of 2xx response */
+
+		/* Set state to CONNECTING */
+		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
+
+		if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
+		    pj_status_t status;
+		    
+		    /* Process session timer response. */
+		    status = handle_timer_response(inv, 
+						   e->body.tsx_state.src.rdata,
+						   PJ_TRUE);
+		    if (status != PJ_SUCCESS)
+			break;
+
+		    inv_check_sdp_in_incoming_msg(inv, tsx, 
+						  e->body.tsx_state.src.rdata);
+		}
+
+		/* if UAC, send ACK and move state to confirmed. */
+		if (tsx->role == PJSIP_ROLE_UAC) {
+		    pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
+
+		    inv_send_ack(inv, e);
+		}
+
+	    } else  {
+		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+	    }
+	    break;
+
+	default:
+	    pj_assert(!"Unexpected INVITE tsx state");
+	    break;
+	}
+
+    } else if (inv->role == PJSIP_ROLE_UAS &&
+	       tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->method.id == PJSIP_CANCEL_METHOD &&
+	       tsx->state < PJSIP_TSX_STATE_COMPLETED &&
+	       e->body.tsx_state.type == PJSIP_EVENT_RX_MSG )
+    {
+
+	/*
+	 * Handle incoming CANCEL request.
+	 */
+
+	inv_respond_incoming_cancel(inv, tsx, e);
+
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->state == PJSIP_TSX_STATE_TRYING &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
+    {
+	/*
+	 * Handle incoming UPDATE
+	 */
+	inv_respond_incoming_update(inv, e->body.tsx_state.src.rdata);
+
+
+    } else if (tsx->role == PJSIP_ROLE_UAC &&
+	       (tsx->state == PJSIP_TSX_STATE_COMPLETED ||
+	        tsx->state == PJSIP_TSX_STATE_TERMINATED) &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
+    {
+	/*
+	 * Handle response to outgoing UPDATE request.
+	 */
+	inv_handle_update_response(inv, e);
+
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->state == PJSIP_TSX_STATE_TRYING &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0)
+    {
+	/*
+	 * Handle incoming PRACK
+	 */
+	inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata);
+
+    } else if (tsx->role == PJSIP_ROLE_UAC) {
+	
+	/* Generic handling for UAC tsx completion */
+	handle_uac_tsx_response(inv, e);
+
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->method.id == PJSIP_BYE_METHOD &&
+	       tsx->status_code < 200 &&
+	       e->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
+    {
+	/* Received BYE before the 2xx/OK response to INVITE.
+	 * Assume that the 2xx/OK response is lost and the BYE
+	 * arrives earlier.
+	 */
+	inv_respond_incoming_bye(inv, tsx, e->body.tsx_state.src.rdata, e);
+
+	if (inv->invite_tsx->role == PJSIP_ROLE_UAC) {
+	    /* Set timer just in case we will never get the final response
+	     * for INVITE.
+	     */
+	    pjsip_tsx_set_timeout(inv->invite_tsx, 64*pjsip_cfg()->tsx.t1);
+	} else if (inv->invite_tsx->status_code < 200) {
+	    pjsip_tx_data *tdata;
+	    pjsip_msg *msg;
+
+	    /* For UAS, send a final response. */
+	    tdata = inv->invite_tsx->last_tx;
+	    PJ_ASSERT_ON_FAIL(tdata != NULL, return);
+
+	    msg = tdata->msg;
+	    msg->line.status.code = PJSIP_SC_REQUEST_TERMINATED;
+	    msg->line.status.reason =
+		    *pjsip_get_status_text(PJSIP_SC_REQUEST_TERMINATED);
+	    msg->body = NULL;
+
+	    pjsip_tx_data_invalidate_msg(tdata);
+	    pjsip_tx_data_add_ref(tdata);
+
+	    pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata);
+	}
+    }
+}
+
+/*
+ * State CONNECTING is after 2xx response to INVITE is sent/received.
+ */
+static void inv_on_state_connecting( pjsip_inv_session *inv, pjsip_event *e)
+{
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+    pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
+
+    PJ_ASSERT_ON_FAIL(tsx && dlg, return);
+
+    if (tsx == inv->invite_tsx) {
+
+	/*
+	 * Handle INVITE state progression.
+	 */
+	switch (tsx->state) {
+
+	case PJSIP_TSX_STATE_CONFIRMED:
+	    /* It can only go here if incoming ACK request has the same Via
+	     * branch parameter as the INVITE transaction.
+	     */
+	    if (tsx->status_code/100 == 2) {
+		if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
+		    inv_check_sdp_in_incoming_msg(inv, tsx,
+						  e->body.tsx_state.src.rdata);
+		}
+
+		inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, e);
+
+		/* Send pending BYE if any:
+		 *   http://trac.pjsip.org/repos/ticket/1712
+		 * Do this after setting the state to CONFIRMED, so that we
+		 * have consistent CONFIRMED state between caller and callee.
+		 */
+		if (inv->pending_bye)
+		    inv_perform_pending_bye(inv);
+
+	    }
+	    break;
+
+	case PJSIP_TSX_STATE_TERMINATED:
+	    /* INVITE transaction can be terminated either because UAC
+	     * transaction received 2xx response or because of transport
+	     * error.
+	     */
+	    if (tsx->status_code/100 != 2) {
+		if (tsx->role == PJSIP_ROLE_UAC) {
+		    inv_set_cause(inv, tsx->status_code, &tsx->status_text);
+		    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
+		} else {
+		    pjsip_tx_data *bye;
+		    pj_status_t status;
+
+		    /* Send BYE */
+		    status = pjsip_dlg_create_request(inv->dlg,
+						      pjsip_get_bye_method(),
+						      -1, &bye);
+		    if (status == PJ_SUCCESS) {
+			pjsip_inv_send_msg(inv, bye);
+		    }
+		}
+	    }
+	    break;
+
+	case PJSIP_TSX_STATE_DESTROYED:
+	    /* Do nothing. */
+	    break;
+
+	default:
+	    pj_assert(!"Unexpected state");
+	    break;
+	}
+
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->method.id == PJSIP_BYE_METHOD &&
+	       tsx->status_code < 200 &&
+	       e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) 
+    {
+
+	/*
+	 * Handle incoming BYE.
+	 */
+
+	inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e );
+
+    } else if (tsx->method.id == PJSIP_BYE_METHOD &&
+	       tsx->role == PJSIP_ROLE_UAC &&
+	       (tsx->state == PJSIP_TSX_STATE_COMPLETED ||
+	        tsx->state == PJSIP_TSX_STATE_TERMINATED))
+    {
+
+	/*
+	 * Outgoing BYE
+	 */
+	inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e);
+
+    }
+    else if (tsx->method.id == PJSIP_CANCEL_METHOD &&
+	     tsx->role == PJSIP_ROLE_UAS &&
+	     tsx->status_code < 200 &&
+	     e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) 
+    {
+
+	/*
+	 * Handle strandled incoming CANCEL or CANCEL for re-INVITE
+	 */
+        inv_respond_incoming_cancel(inv, tsx, e);
+
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->state == PJSIP_TSX_STATE_TRYING &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_invite_method)==0)
+    {
+	pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
+	pjsip_tx_data *tdata;
+	pj_status_t status;
+
+	/* See https://trac.pjsip.org/repos/ticket/1455
+	 * Handle incoming re-INVITE before current INVITE is confirmed.
+	 * According to RFC 5407:
+	 *  - answer with 200 if we don't have pending offer-answer
+	 *  - answer with 491 if we *have* pending offer-answer
+	 *
+	 *  But unfortunately accepting the re-INVITE would mean we have
+	 *  two outstanding INVITEs, and we don't support that because
+	 *  we will get confused when we handle the ACK.
+	 */
+	status = pjsip_dlg_create_response(inv->dlg, rdata,
+					   PJSIP_SC_REQUEST_PENDING,
+					   NULL, &tdata);
+	if (status != PJ_SUCCESS)
+	    return;
+	pjsip_timer_update_resp(inv, tdata);
+	status = pjsip_dlg_send_response(dlg, tsx, tdata);
+
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->state == PJSIP_TSX_STATE_TRYING &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
+    {
+	/*
+	 * Handle incoming UPDATE
+	 */
+	inv_respond_incoming_update(inv, e->body.tsx_state.src.rdata);
+
+
+    } else if (tsx->role == PJSIP_ROLE_UAC &&
+	       (tsx->state == PJSIP_TSX_STATE_COMPLETED ||
+	        tsx->state == PJSIP_TSX_STATE_TERMINATED) &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
+    {
+	/*
+	 * Handle response to outgoing UPDATE request.
+	 */
+	if (inv_handle_update_response(inv, e) == PJ_FALSE)
+	    handle_uac_tsx_response(inv, e);
+
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->state == PJSIP_TSX_STATE_TRYING &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0)
+    {
+	/*
+	 * Handle incoming PRACK
+	 */
+	inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata);
+
+    } else if (tsx->role == PJSIP_ROLE_UAC) {
+	
+	/* Generic handling for UAC tsx completion */
+	handle_uac_tsx_response(inv, e);
+
+    }
+
+}
+
+/*
+ * State CONFIRMED is after ACK is sent/received.
+ */
+static void inv_on_state_confirmed( pjsip_inv_session *inv, pjsip_event *e)
+{
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+    pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
+
+    PJ_ASSERT_ON_FAIL(tsx && dlg, return);
+
+
+    if (tsx->method.id == PJSIP_BYE_METHOD &&
+	tsx->role == PJSIP_ROLE_UAC &&
+	(tsx->state == PJSIP_TSX_STATE_COMPLETED ||
+	 tsx->state == PJSIP_TSX_STATE_TERMINATED))
+    {
+
+	/*
+	 * Outgoing BYE
+	 */
+
+	inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e);
+
+    }
+    else if (tsx->method.id == PJSIP_BYE_METHOD &&
+	     tsx->role == PJSIP_ROLE_UAS &&
+	     tsx->status_code < 200 &&
+	     e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) 
+    {
+
+	/*
+	 * Handle incoming BYE.
+	 */
+
+	inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e );
+
+    }
+    else if (tsx->method.id == PJSIP_CANCEL_METHOD &&
+	     tsx->role == PJSIP_ROLE_UAS &&
+	     tsx->status_code < 200 &&
+	     e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) 
+    {
+
+	/*
+	 * Handle strandled incoming CANCEL or CANCEL for re-INVITE
+	 */
+        inv_respond_incoming_cancel(inv, tsx, e);
+    }
+    else if (tsx->method.id == PJSIP_INVITE_METHOD &&
+	     tsx->role == PJSIP_ROLE_UAS)
+    {
+
+	/*
+	 * Handle incoming re-INVITE
+	 */
+	if (tsx->state == PJSIP_TSX_STATE_TRYING) {
+	    
+	    pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
+	    pjsip_tx_data *tdata;
+	    pj_status_t status;
+	    pjsip_rdata_sdp_info *sdp_info = NULL;
+	    pjsip_status_code st_code;
+
+	    /* Check if we have INVITE pending. */
+	    if (inv->invite_tsx && inv->invite_tsx!=tsx) {
+		int code;
+		pj_str_t reason;
+
+		reason = pj_str("Another INVITE transaction in progress");
+
+		if (inv->invite_tsx->role == PJSIP_ROLE_UAC)
+		    code = 491;
+		else
+		    code = 500;
+
+		/* Can not receive re-INVITE while another one is pending. */
+		status = pjsip_dlg_create_response( inv->dlg, rdata, code,
+						    &reason, &tdata);
+		if (status != PJ_SUCCESS)
+		    return;
+
+		if (code == 500) {
+		    /* MUST include Retry-After header with random value
+		     * between 0-10.
+		     */
+		    pjsip_retry_after_hdr *ra_hdr;
+		    int val = (pj_rand() % 10);
+
+		    ra_hdr = pjsip_retry_after_hdr_create(tdata->pool, val);
+		    pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)ra_hdr);
+		}
+
+		status = pjsip_dlg_send_response( inv->dlg, tsx, tdata);
+		
+
+		return;
+	    }
+
+	    /* Save the invite transaction. */
+	    inv->invite_tsx = tsx;
+
+	    /* Process session timers headers in the re-INVITE */
+	    status = pjsip_timer_process_req(inv, rdata, &st_code);
+	    if (status != PJ_SUCCESS) {
+		status = pjsip_dlg_create_response(inv->dlg, rdata, st_code,
+						   NULL, &tdata);
+		if (status != PJ_SUCCESS)
+		    return;
+
+		pjsip_timer_update_resp(inv, tdata);
+		status = pjsip_dlg_send_response(dlg, tsx, tdata);
+		return;
+	    }
+
+	    /* Send 491 if we receive re-INVITE while another offer/answer
+	     * negotiation is in progress
+	     */
+	    if (pjmedia_sdp_neg_get_state(inv->neg) !=
+		    PJMEDIA_SDP_NEG_STATE_DONE)
+	    {
+		status = pjsip_dlg_create_response(inv->dlg, rdata,
+						   PJSIP_SC_REQUEST_PENDING,
+						   NULL, &tdata);
+		if (status != PJ_SUCCESS)
+		    return;
+		pjsip_timer_update_resp(inv, tdata);
+		status = pjsip_dlg_send_response(dlg, tsx, tdata);
+		return;
+	    }
+
+	    /* Process SDP in incoming message. */
+	    status = inv_check_sdp_in_incoming_msg(inv, tsx, rdata);
+
+            if (status == PJ_SUCCESS && mod_inv.cb.on_rx_reinvite &&
+                inv->notify)
+            {
+        	pj_status_t rc;
+
+	        sdp_info = pjsip_rdata_get_sdp_info(rdata);
+                rc = (*mod_inv.cb.on_rx_reinvite)(inv, sdp_info->sdp,
+                				  rdata);
+                if (rc == PJ_SUCCESS) {
+                    /* Application will send its own response.
+                     * Our job is done. */
+		    PJ_LOG(5,(inv->obj_name, "on_rx_reinvite() returns %d",
+			      rc));
+                    return;
+                }
+
+                /* If application lets us answer the re-INVITE,
+                 * application must set the SDP answer with
+                 * #pjsip_inv_set_sdp_answer().
+                 */
+                if (pjmedia_sdp_neg_get_state(inv->neg) !=
+		    PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)
+                {
+                    status = PJ_EINVALIDOP;
+                }
+            }
+
+	    if (status != PJ_SUCCESS) {
+
+		/* Not Acceptable */
+		const pjsip_hdr *accept;
+
+		/* The incoming SDP is unacceptable. If the SDP negotiator
+		 * state has just been changed, i.e: DONE -> REMOTE_OFFER,
+		 * revert it back.
+		 */
+		if (pjmedia_sdp_neg_get_state(inv->neg) ==
+		    PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER)
+		{
+		    pjmedia_sdp_neg_cancel_offer(inv->neg);
+		}
+
+		status = pjsip_dlg_create_response(inv->dlg, rdata, 
+						   488, NULL, &tdata);
+		if (status != PJ_SUCCESS)
+		    return;
+
+
+		accept = pjsip_endpt_get_capability(dlg->endpt, PJSIP_H_ACCEPT,
+						    NULL);
+		if (accept) {
+		    pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)
+				      pjsip_hdr_clone(tdata->pool, accept));
+		}
+
+		status = pjsip_dlg_send_response(dlg, tsx, tdata);
+
+		return;
+	    }
+
+	    /* Create 2xx ANSWER */
+	    status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata);
+	    if (status != PJ_SUCCESS)
+		return;
+
+	    /* If the INVITE request has SDP body, send answer.
+	     * Otherwise generate offer from local active SDP.
+	     */
+            if (!sdp_info)
+                sdp_info = pjsip_rdata_get_sdp_info(rdata);
+	    if (sdp_info->sdp != NULL) {
+		status = process_answer(inv, 200, tdata, NULL);
+	    } else {
+		/* INVITE does not have SDP. 
+		 * If on_create_offer() callback is implemented, ask app.
+		 * to generate an offer, otherwise just send active local
+		 * SDP to signal that nothing gets modified.
+		 */
+		pjmedia_sdp_session *sdp = NULL;
+
+		if (mod_inv.cb.on_create_offer)  {
+		    (*mod_inv.cb.on_create_offer)(inv, &sdp);
+		    if (sdp) {
+			/* Notify negotiator about the new offer. This will
+			 * fix the offer with correct SDP origin.
+			 */
+			status = 
+			    pjmedia_sdp_neg_modify_local_offer2(
+                                inv->pool_prov, inv->neg,
+                                inv->sdp_neg_flags, sdp);
+
+			/* Retrieve the "fixed" offer from negotiator */
+			if (status==PJ_SUCCESS) {
+			    const pjmedia_sdp_session *lsdp = NULL;
+			    pjmedia_sdp_neg_get_neg_local(inv->neg, &lsdp);
+			    sdp = (pjmedia_sdp_session*)lsdp;
+			}
+		    }
+		} 
+		
+		if (sdp == NULL) {
+		    const pjmedia_sdp_session *active_sdp = NULL;
+		    status = pjmedia_sdp_neg_send_local_offer(inv->pool_prov,
+							      inv->neg, 
+							      &active_sdp);
+		    if (status == PJ_SUCCESS)
+			sdp = (pjmedia_sdp_session*) active_sdp;
+		}
+
+		if (sdp) {
+		    tdata->msg->body = create_sdp_body(tdata->pool, sdp);
+		}
+	    }
+
+	    if (status != PJ_SUCCESS) {
+		/*
+		 * SDP negotiation has failed.
+		 */
+		pj_status_t rc;
+		pj_str_t reason;
+
+		/* Delete the 2xx answer */
+		pjsip_tx_data_dec_ref(tdata);
+		
+		/* Create 500 response */
+		reason = pj_str("SDP negotiation failed");
+		rc = pjsip_dlg_create_response(dlg, rdata, 500, &reason, 
+					       &tdata);
+		if (rc == PJ_SUCCESS) {
+		    pjsip_warning_hdr *w;
+		    const pj_str_t *endpt_name;
+
+		    endpt_name = pjsip_endpt_name(dlg->endpt);
+		    w = pjsip_warning_hdr_create_from_status(tdata->pool, 
+							     endpt_name,
+							     status);
+		    if (w)
+			pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)w);
+
+		    pjsip_inv_send_msg(inv, tdata);
+		}
+		return;
+	    }
+
+	    /* Invoke Session Timers */
+	    pjsip_timer_update_resp(inv, tdata);
+
+	    /* Send 2xx regardless of the status of negotiation */
+	    status = pjsip_inv_send_msg(inv, tdata);
+
+	} else if (tsx->state == PJSIP_TSX_STATE_CONFIRMED) {
+	    /* This is the case where ACK has the same branch as
+	     * the INVITE request.
+	     */
+	    if (tsx->status_code/100 == 2 &&
+		e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) 
+	    {
+		inv_check_sdp_in_incoming_msg(inv, tsx,
+					      e->body.tsx_state.src.rdata);
+
+		/* Check if local offer got no SDP answer */
+		if (pjmedia_sdp_neg_get_state(inv->neg)==
+		    PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER)
+		{
+		    pjmedia_sdp_neg_cancel_offer(inv->neg);
+		}
+	    }
+
+	}
+
+    }
+    else if (tsx->method.id == PJSIP_INVITE_METHOD &&
+	     tsx->role == PJSIP_ROLE_UAC)
+    {
+
+	/*
+	 * Handle outgoing re-INVITE
+	 */
+	if (tsx->state == PJSIP_TSX_STATE_CALLING) {
+
+	    /* Must not have other pending INVITE transaction */
+	    pj_assert(inv->invite_tsx==NULL || tsx==inv->invite_tsx);
+
+	    /* Save pending invite transaction */
+	    inv->invite_tsx = tsx;
+
+        } else if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) {
+            
+            /* CANCEL the re-INVITE if necessary */
+            if (inv->pending_cancel) {
+	        pj_status_t status;
+		pjsip_tx_data *cancel;
+
+		inv->pending_cancel = PJ_FALSE;
+
+		status = pjsip_inv_cancel_reinvite(inv, &cancel);
+		if (status == PJ_SUCCESS && cancel)
+		    status = pjsip_inv_send_msg(inv, cancel);
+            }
+
+	} else if (tsx->state == PJSIP_TSX_STATE_TERMINATED &&
+		   tsx->status_code/100 == 2) 
+	{
+	    pj_status_t status;
+
+	    /* Re-INVITE was accepted. */
+
+	    /* Process session timer response. */
+	    status = handle_timer_response(inv, 
+					   e->body.tsx_state.src.rdata,
+					   PJ_TRUE);
+	    if (status != PJ_SUCCESS)
+		return;
+
+	    /* Process SDP */
+	    inv_check_sdp_in_incoming_msg(inv, tsx, 
+					  e->body.tsx_state.src.rdata);
+
+	    /* Check if local offer got no SDP answer */
+	    if (pjmedia_sdp_neg_get_state(inv->neg)==
+		PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER)
+	    {
+		pjmedia_sdp_neg_cancel_offer(inv->neg);
+	    }
+
+	    /* Send ACK */
+	    inv_send_ack(inv, e);
+
+	} else if (handle_uac_tsx_response(inv, e)) {
+
+	    /* Handle response that terminates dialog */
+	    /* Nothing to do (already handled) */
+
+	} else if (tsx->status_code >= 300 && tsx->status_code < 700 &&
+		   e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED)
+	{
+	    /* Ticket #1654: do not cancel SDP offer when tsx state changing
+	     * from 'completed' to 'terminated', as it should have already
+	     * been cancelled when tsx state is 'completed'.
+	     */
+
+	    pjmedia_sdp_neg_state neg_state;
+	    struct tsx_inv_data *tsx_inv_data;
+
+	    tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
+
+	    /* Outgoing INVITE transaction has failed, cancel SDP nego */
+	    neg_state = pjmedia_sdp_neg_get_state(inv->neg);
+	    if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER &&
+		tsx_inv_data->retrying == PJ_FALSE)
+	    {
+		pjmedia_sdp_neg_cancel_offer(inv->neg);
+	    }
+
+	    if (tsx == inv->invite_tsx)
+		inv->invite_tsx = NULL;
+	}
+
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->state == PJSIP_TSX_STATE_TRYING &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
+    {
+	/*
+	 * Handle incoming UPDATE
+	 */
+	inv_respond_incoming_update(inv, e->body.tsx_state.src.rdata);
+
+    } else if (tsx->role == PJSIP_ROLE_UAC &&
+	       (tsx->state == PJSIP_TSX_STATE_COMPLETED ||
+	        tsx->state == PJSIP_TSX_STATE_TERMINATED) &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
+    {
+	/*
+	 * Handle response to outgoing UPDATE request.
+	 */
+	if (inv_handle_update_response(inv, e) == PJ_FALSE)
+	    handle_uac_tsx_response(inv, e);
+
+    } else if (tsx->role == PJSIP_ROLE_UAS &&
+	       tsx->state == PJSIP_TSX_STATE_TRYING &&
+	       pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0)
+    {
+	/*
+	 * Handle strandled incoming PRACK
+	 */
+	inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata);
+
+    } else if (tsx->role == PJSIP_ROLE_UAC) {
+	/*
+	 * Handle 401/407/408/481/422 response
+	 */
+	handle_uac_tsx_response(inv, e);
+    }
+
+}
+
+/*
+ * After session has been terminated, but before dialog is destroyed
+ * (because dialog has other usages, or because dialog is waiting for
+ * the last transaction to terminate).
+ */
+static void inv_on_state_disconnected( pjsip_inv_session *inv, pjsip_event *e)
+{
+    pjsip_transaction *tsx = e->body.tsx_state.tsx;
+    pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
+
+    PJ_ASSERT_ON_FAIL(tsx && dlg, return);
+
+    if (tsx->role == PJSIP_ROLE_UAS &&
+	tsx->status_code < 200 &&
+	e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) 
+    {
+	pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
+
+	/*
+	 * Respond BYE with 200/OK
+	 */
+	if (tsx->method.id == PJSIP_BYE_METHOD) {
+	    inv_respond_incoming_bye( inv, tsx, rdata, e );
+	} else if (tsx->method.id == PJSIP_CANCEL_METHOD) {
+	    /*
+	     * Respond CANCEL with 200/OK too.
+	     */
+	    pjsip_tx_data *tdata;
+	    pj_status_t status;
+
+	    status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata);
+	    if (status != PJ_SUCCESS) return;
+
+	    status = pjsip_dlg_send_response(dlg, tsx, tdata);
+	    if (status != PJ_SUCCESS) return;
+
+	}
+
+    } else if (tsx->role == PJSIP_ROLE_UAC) {
+	/*
+	 * Handle 401/407/408/481/422 response
+	 */
+	handle_uac_tsx_response(inv, e);
+    }
+}
+
diff --git a/jni/pjproject-android/.svn/pristine/db/db3642dc8d87ef95b4abaf1b45cfd7f0c5d417d4.svn-base b/jni/pjproject-android/.svn/pristine/db/db3642dc8d87ef95b4abaf1b45cfd7f0c5d417d4.svn-base
new file mode 100644
index 0000000..c3c776b
--- /dev/null
+++ b/jni/pjproject-android/.svn/pristine/db/db3642dc8d87ef95b4abaf1b45cfd7f0c5d417d4.svn-base
@@ -0,0 +1,193 @@
+/* $Id$ */
+/* 
+ * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
+ * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
+ */
+#include <pjlib-util/dns.h>
+#include <pj/assert.h>
+#include <pj/log.h>
+#include <pj/string.h>
+
+#define THIS_FILE   "dns_dump.c"
+#define LEVEL	    3
+
+static const char *spell_ttl(char *buf, int size, unsigned ttl)
+{
+#define DAY	(3600*24)
+#define HOUR	(3600)
+#define MINUTE	(60)
+
+    char *p = buf;
+    int len;
+
+    if (ttl > DAY) {
+	len = pj_ansi_snprintf(p, size, "%dd ", ttl/DAY);
+	if (len < 1 || len >= size)
+	    return "-err-";
+	size -= len;
+	p += len;
+	ttl %= DAY;
+    }
+
+    if (ttl > HOUR) {
+	len = pj_ansi_snprintf(p, size, "%dh ", ttl/HOUR);
+	if (len < 1 || len >= size)
+	    return "-err-";
+	size -= len;
+	p += len;
+	ttl %= HOUR;
+    }
+
+    if (ttl > MINUTE) {
+	len = pj_ansi_snprintf(p, size, "%dm ", ttl/MINUTE);
+	if (len < 1 || len >= size)
+	    return "-err-";
+	size -= len;
+	p += len;
+	ttl %= MINUTE;
+    }
+
+    if (ttl > 0) {
+	len = pj_ansi_snprintf(p, size, "%ds ", ttl);
+	if (len < 1 || len >= size)
+	    return "-err-";
+	size -= len;
+	p += len;
+	ttl = 0;
+    }
+
+    *p = '\0';
+    return buf;
+}
+
+
+static void dump_query(unsigned index, const pj_dns_parsed_query *q)
+{
+    PJ_LOG(3,(THIS_FILE, " %d. Name: %.*s", 
+			 index, (int)q->name.slen, q->name.ptr));
+    PJ_LOG(3,(THIS_FILE, "    Type: %s (%d)", 
+			 pj_dns_get_type_name(q->type), q->type));
+    PJ_LOG(3,(THIS_FILE, "    Class: %s (%d)", 
+		         (q->dnsclass==1 ? "IN" : "<Unknown>"), q->dnsclass));
+}
+
+static void dump_answer(unsigned index, const pj_dns_parsed_rr *rr)
+{
+    const pj_str_t root_name = { "<Root>", 6 };
+    const pj_str_t *name = &rr->name;
+    char ttl_words[32];
+
+    if (name->slen == 0)
+	name = &root_name;
+
+    PJ_LOG(3,(THIS_FILE, " %d. %s record (type=%d)", 
+			 index, pj_dns_get_type_name(rr->type),
+			rr->type));
+    PJ_LOG(3,(THIS_FILE, "    Name: %.*s", (int)name->slen, name->ptr));
+    PJ_LOG(3,(THIS_FILE, "    TTL: %u (%s)", rr->ttl, 
+			  spell_ttl(ttl_words, sizeof(ttl_words), rr->ttl)));
+    PJ_LOG(3,(THIS_FILE, "    Data length: %u", rr->rdlength));
+
+    if (rr->type == PJ_DNS_TYPE_SRV) {
+	PJ_LOG(3,(THIS_FILE, "    SRV: prio=%d, weight=%d %.*s:%d", 
+			     rr->rdata.srv.prio, rr->rdata.srv.weight,
+			     (int)rr->rdata.srv.target.slen, 
+			     rr->rdata.srv.target.ptr,
+			     rr->rdata.srv.port));
+    } else if (rr->type == PJ_DNS_TYPE_CNAME ||
+	       rr->type == PJ_DNS_TYPE_NS ||
+	       rr->type == PJ_DNS_TYPE_PTR) 
+    {
+	PJ_LOG(3,(THIS_FILE, "    Name: %.*s",
+		  (int)rr->rdata.cname.name.slen,
+		  rr->rdata.cname.name.ptr));
+    } else if (rr->type == PJ_DNS_TYPE_A) {
+	PJ_LOG(3,(THIS_FILE, "    IP address: %s",
+		  pj_inet_ntoa(rr->rdata.a.ip_addr)));
+    } else if (rr->type == PJ_DNS_TYPE_AAAA) {
+	char addr[PJ_INET6_ADDRSTRLEN];
+	PJ_LOG(3,(THIS_FILE, "    IPv6 address: %s",
+		  pj_inet_ntop2(pj_AF_INET6(), &rr->rdata.aaaa.ip_addr,
+			        addr, sizeof(addr))));
+    }
+}
+
+
+PJ_DEF(void) pj_dns_dump_packet(const pj_dns_parsed_packet *res)
+{
+    unsigned i;
+
+    PJ_ASSERT_ON_FAIL(res != NULL, return);
+
+    /* Header part */
+    PJ_LOG(3,(THIS_FILE, "Domain Name System packet (%s):",
+		(PJ_DNS_GET_QR(res->hdr.flags) ? "response" : "query")));
+    PJ_LOG(3,(THIS_FILE, " Transaction ID: %d", res->hdr.id));
+    PJ_LOG(3,(THIS_FILE, 
+	      " Flags: opcode=%d, authoritative=%d, truncated=%d, rcode=%d",
+		 PJ_DNS_GET_OPCODE(res->hdr.flags),
+		 PJ_DNS_GET_AA(res->hdr.flags),
+		 PJ_DNS_GET_TC(res->hdr.flags),
+		 PJ_DNS_GET_RCODE(res->hdr.flags)));
+    PJ_LOG(3,(THIS_FILE, " Nb of queries: %d", res->hdr.qdcount));
+    PJ_LOG(3,(THIS_FILE, " Nb of answer RR: %d", res->hdr.anscount));
+    PJ_LOG(3,(THIS_FILE, " Nb of authority RR: %d", res->hdr.nscount));
+    PJ_LOG(3,(THIS_FILE, " Nb of additional RR: %d", res->hdr.arcount));
+    PJ_LOG(3,(THIS_FILE, ""));
+
+    /* Dump queries */
+    if (res->hdr.qdcount) {
+	PJ_LOG(3,(THIS_FILE, " Queries:"));
+
+	for (i=0; i<res->hdr.qdcount; ++i) {
+	    dump_query(i, &res->q[i]);
+	}
+	PJ_LOG(3,(THIS_FILE, ""));
+    }
+
+    /* Dump answers */
+    if (res->hdr.anscount) {
+	PJ_LOG(3,(THIS_FILE, " Answers RR:"));
+
+	for (i=0; i<res->hdr.anscount; ++i) {
+	    dump_answer(i, &res->ans[i]);
+	}
+	PJ_LOG(3,(THIS_FILE, ""));
+    }
+
+    /* Dump NS sections */
+    if (res->hdr.anscount) {
+	PJ_LOG(3,(THIS_FILE, " NS Authority RR:"));
+
+	for (i=0; i<res->hdr.nscount; ++i) {
+	    dump_answer(i, &res->ns[i]);
+	}
+	PJ_LOG(3,(THIS_FILE, ""));
+    }
+
+    /* Dump Additional info sections */
+    if (res->hdr.arcount) {
+	PJ_LOG(3,(THIS_FILE, " Additional Info RR:"));
+
+	for (i=0; i<res->hdr.arcount; ++i) {
+	    dump_answer(i, &res->arr[i]);
+	}
+	PJ_LOG(3,(THIS_FILE, ""));
+    }
+
+}
+
diff --git a/jni/pjproject-android/.svn/pristine/db/db5cf203487e3817a3166bd8b59c84ede2e9d0ff.svn-base b/jni/pjproject-android/.svn/pristine/db/db5cf203487e3817a3166bd8b59c84ede2e9d0ff.svn-base
new file mode 100644
index 0000000..7129f21
--- /dev/null
+++ b/jni/pjproject-android/.svn/pristine/db/db5cf203487e3817a3166bd8b59c84ede2e9d0ff.svn-base
@@ -0,0 +1,2578 @@
+/* $Id$ */
+/* 
+ * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
+ */
+#include <pj/ssl_sock.h>
+#include <pj/activesock.h>
+#include <pj/compat/socket.h>
+#include <pj/assert.h>
+#include <pj/errno.h>
+#include <pj/list.h>
+#include <pj/lock.h>
+#include <pj/log.h>
+#include <pj/math.h>
+#include <pj/os.h>
+#include <pj/pool.h>
+#include <pj/string.h>
+#include <pj/timer.h>
+
+
+/* Only build when PJ_HAS_SSL_SOCK is enabled */
+#if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK!=0
+
+#define THIS_FILE		"ssl_sock_ossl.c"
+
+/* Workaround for ticket #985 */
+#define DELAYED_CLOSE_TIMEOUT	200
+
+/* Maximum ciphers */
+#define MAX_CIPHERS		100
+
+/* 
+ * Include OpenSSL headers 
+ */
+#include <openssl/bio.h>
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <openssl/x509v3.h>
+
+
+#ifdef _MSC_VER
+#  pragma comment( lib, "libeay32")
+#  pragma comment( lib, "ssleay32")
+#endif
+
+
+/*
+ * SSL/TLS state enumeration.
+ */
+enum ssl_state {
+    SSL_STATE_NULL,
+    SSL_STATE_HANDSHAKING,
+    SSL_STATE_ESTABLISHED
+};
+
+/*
+ * Internal timer types.
+ */
+enum timer_id
+{
+    TIMER_NONE,
+    TIMER_HANDSHAKE_TIMEOUT,
+    TIMER_CLOSE
+};
+
+/*
+ * Structure of SSL socket read buffer.
+ */
+typedef struct read_data_t
+{
+    void		 *data;
+    pj_size_t		  len;
+} read_data_t;
+
+/*
+ * Get the offset of pointer to read-buffer of SSL socket from read-buffer
+ * of active socket. Note that both SSL socket and active socket employ 
+ * different but correlated read-buffers (as much as async_cnt for each),
+ * and to make it easier/faster to find corresponding SSL socket's read-buffer
+ * from known active socket's read-buffer, the pointer of corresponding 
+ * SSL socket's read-buffer is stored right after the end of active socket's
+ * read-buffer.
+ */
+#define OFFSET_OF_READ_DATA_PTR(ssock, asock_rbuf) \
+					(read_data_t**) \
+					((pj_int8_t*)(asock_rbuf) + \
+					ssock->param.read_buffer_size)
+
+/*
+ * Structure of SSL socket write data.
+ */
+typedef struct write_data_t {
+    PJ_DECL_LIST_MEMBER(struct write_data_t);
+    pj_ioqueue_op_key_t	 key;
+    pj_size_t 	 	 record_len;
+    pj_ioqueue_op_key_t	*app_key;
+    pj_size_t 	 	 plain_data_len;
+    pj_size_t 	 	 data_len;
+    unsigned		 flags;
+    union {
+	char		 content[1];
+	const char	*ptr;
+    } data;
+} write_data_t;
+
+/*
+ * Structure of SSL socket write buffer (circular buffer).
+ */
+typedef struct send_buf_t {
+    char		*buf;
+    pj_size_t		 max_len;    
+    char		*start;
+    pj_size_t		 len;
+} send_buf_t;
+
+/*
+ * Secure socket structure definition.
+ */
+struct pj_ssl_sock_t
+{
+    pj_pool_t		 *pool;
+    pj_ssl_sock_t	 *parent;
+    pj_ssl_sock_param	  param;
+    pj_ssl_cert_t	 *cert;
+    
+    pj_ssl_cert_info	  local_cert_info;
+    pj_ssl_cert_info	  remote_cert_info;
+
+    pj_bool_t		  is_server;
+    enum ssl_state	  ssl_state;
+    pj_ioqueue_op_key_t	  handshake_op_key;
+    pj_timer_entry	  timer;
+    pj_status_t		  verify_status;
+
+    unsigned long	  last_err;
+
+    pj_sock_t		  sock;
+    pj_activesock_t	 *asock;
+
+    pj_sockaddr		  local_addr;
+    pj_sockaddr		  rem_addr;
+    int			  addr_len;
+    
+    pj_bool_t		  read_started;
+    pj_size_t		  read_size;
+    pj_uint32_t		  read_flags;
+    void		**asock_rbuf;
+    read_data_t		 *ssock_rbuf;
+
+    write_data_t	  write_pending;/* list of pending write to OpenSSL */
+    write_data_t	  write_pending_empty; /* cache for write_pending   */
+    pj_bool_t		  flushing_write_pend; /* flag of flushing is ongoing*/
+    send_buf_t		  send_buf;
+    write_data_t	  send_pending;	/* list of pending write to network */
+    pj_lock_t		 *write_mutex;	/* protect write BIO and send_buf   */
+
+    SSL_CTX		 *ossl_ctx;
+    SSL			 *ossl_ssl;
+    BIO			 *ossl_rbio;
+    BIO			 *ossl_wbio;
+};
+
+
+/*
+ * Certificate/credential structure definition.
+ */
+struct pj_ssl_cert_t
+{
+    pj_str_t CA_file;
+    pj_str_t cert_file;
+    pj_str_t privkey_file;
+    pj_str_t privkey_pass;
+};
+
+
+static write_data_t* alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len);
+static void free_send_data(pj_ssl_sock_t *ssock, write_data_t *wdata);
+static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock);
+
+/*
+ *******************************************************************
+ * Static/internal functions.
+ *******************************************************************
+ */
+
+/**
+ * Mapping from OpenSSL error codes to pjlib error space.
+ */
+
+#define PJ_SSL_ERRNO_START		(PJ_ERRNO_START_USER + \
+					 PJ_ERRNO_SPACE_SIZE*6)
+
+#define PJ_SSL_ERRNO_SPACE_SIZE		PJ_ERRNO_SPACE_SIZE
+
+/* Expected maximum value of reason component in OpenSSL error code */
+#define MAX_OSSL_ERR_REASON		1200
+
+static pj_status_t STATUS_FROM_SSL_ERR(pj_ssl_sock_t *ssock,
+				       unsigned long err)
+{
+    pj_status_t status;
+
+    /* General SSL error, dig more from OpenSSL error queue */
+    if (err == SSL_ERROR_SSL)
+	err = ERR_get_error();
+
+    /* OpenSSL error range is much wider than PJLIB errno space, so
+     * if it exceeds the space, only the error reason will be kept.
+     * Note that the last native error will be kept as is and can be
+     * retrieved via SSL socket info.
+     */
+    status = ERR_GET_LIB(err)*MAX_OSSL_ERR_REASON + ERR_GET_REASON(err);
+    if (status > PJ_SSL_ERRNO_SPACE_SIZE)
+	status = ERR_GET_REASON(err);
+
+    status += PJ_SSL_ERRNO_START;
+    ssock->last_err = err;
+    return status;
+}
+
+static pj_status_t GET_SSL_STATUS(pj_ssl_sock_t *ssock)
+{
+    return STATUS_FROM_SSL_ERR(ssock, ERR_get_error());
+}
+
+
+/*
+ * Get error string of OpenSSL.
+ */
+static pj_str_t ssl_strerror(pj_status_t status, 
+			     char *buf, pj_size_t bufsize)
+{
+    pj_str_t errstr;
+    unsigned long ssl_err = status;
+
+    if (ssl_err) {
+	unsigned long l, r;
+	ssl_err -= PJ_SSL_ERRNO_START;
+	l = ssl_err / MAX_OSSL_ERR_REASON;
+	r = ssl_err % MAX_OSSL_ERR_REASON;
+	ssl_err = ERR_PACK(l, 0, r);
+    }
+
+#if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0)
+
+    {
+	const char *tmp = NULL;
+	tmp = ERR_reason_error_string(ssl_err);
+	if (tmp) {
+	    pj_ansi_strncpy(buf, tmp, bufsize);
+	    errstr = pj_str(buf);
+	    return errstr;
+	}
+    }
+
+#endif	/* PJ_HAS_ERROR_STRING */
+
+    errstr.ptr = buf;
+    errstr.slen = pj_ansi_snprintf(buf, bufsize, 
+				   "Unknown OpenSSL error %lu",
+				   ssl_err);
+    if (errstr.slen < 1 || errstr.slen >= (int)bufsize)
+	errstr.slen = bufsize - 1;
+    return errstr;
+}
+
+
+/* OpenSSL library initialization counter */
+static int openssl_init_count;
+
+/* OpenSSL available ciphers */
+static unsigned openssl_cipher_num;
+static struct openssl_ciphers_t {
+    pj_ssl_cipher    id;
+    const char	    *name;
+} openssl_ciphers[MAX_CIPHERS];
+
+/* OpenSSL application data index */
+static int sslsock_idx;
+
+
+/* Initialize OpenSSL */
+static pj_status_t init_openssl(void)
+{
+    pj_status_t status;
+
+    if (openssl_init_count)
+	return PJ_SUCCESS;
+
+    openssl_init_count = 1;
+
+    /* Register error subsystem */
+    status = pj_register_strerror(PJ_SSL_ERRNO_START, 
+				  PJ_SSL_ERRNO_SPACE_SIZE, 
+				  &ssl_strerror);
+    pj_assert(status == PJ_SUCCESS);
+
+    /* Init OpenSSL lib */
+    SSL_library_init();
+    SSL_load_error_strings();
+    OpenSSL_add_all_algorithms();
+
+    /* Init available ciphers */
+    if (openssl_cipher_num == 0) {
+	SSL_METHOD *meth = NULL;
+	SSL_CTX *ctx;
+	SSL *ssl;
+	STACK_OF(SSL_CIPHER) *sk_cipher;
+	unsigned i, n;
+
+	meth = (SSL_METHOD*)SSLv23_server_method();
+	if (!meth)
+	    meth = (SSL_METHOD*)TLSv1_server_method();
+	if (!meth)
+	    meth = (SSL_METHOD*)SSLv3_server_method();
+#ifndef OPENSSL_NO_SSL2
+	if (!meth)
+	    meth = (SSL_METHOD*)SSLv2_server_method();
+#endif
+	pj_assert(meth);
+
+	ctx=SSL_CTX_new(meth);
+	SSL_CTX_set_cipher_list(ctx, "ALL");
+
+	ssl = SSL_new(ctx);
+	sk_cipher = SSL_get_ciphers(ssl);
+
+	n = sk_SSL_CIPHER_num(sk_cipher);
+	if (n > PJ_ARRAY_SIZE(openssl_ciphers))
+	    n = PJ_ARRAY_SIZE(openssl_ciphers);
+
+	for (i = 0; i < n; ++i) {
+	    SSL_CIPHER *c;
+	    c = sk_SSL_CIPHER_value(sk_cipher,i);
+	    openssl_ciphers[i].id = (pj_ssl_cipher)
+				    (pj_uint32_t)c->id & 0x00FFFFFF;
+	    openssl_ciphers[i].name = SSL_CIPHER_get_name(c);
+	}
+
+	SSL_free(ssl);
+	SSL_CTX_free(ctx);
+
+	openssl_cipher_num = n;
+    }
+
+    /* Create OpenSSL application data index for SSL socket */
+    sslsock_idx = SSL_get_ex_new_index(0, "SSL socket", NULL, NULL, NULL);
+
+    return PJ_SUCCESS;
+}
+
+
+/* Shutdown OpenSSL */
+static void shutdown_openssl(void)
+{
+    PJ_UNUSED_ARG(openssl_init_count);
+}
+
+
+/* SSL password callback. */
+static int password_cb(char *buf, int num, int rwflag, void *user_data)
+{
+    pj_ssl_cert_t *cert = (pj_ssl_cert_t*) user_data;
+
+    PJ_UNUSED_ARG(rwflag);
+
+    if(num < cert->privkey_pass.slen)
+	return 0;
+    
+    pj_memcpy(buf, cert->privkey_pass.ptr, cert->privkey_pass.slen);
+    return (int)cert->privkey_pass.slen;
+}
+
+
+/* SSL password callback. */
+static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
+{
+    pj_ssl_sock_t *ssock;
+    SSL *ossl_ssl;
+    int err;
+
+    /* Get SSL instance */
+    ossl_ssl = X509_STORE_CTX_get_ex_data(x509_ctx, 
+				    SSL_get_ex_data_X509_STORE_CTX_idx());
+    pj_assert(ossl_ssl);
+
+    /* Get SSL socket instance */
+    ssock = SSL_get_ex_data(ossl_ssl, sslsock_idx);
+    pj_assert(ssock);
+
+    /* Store verification status */
+    err = X509_STORE_CTX_get_error(x509_ctx);
+    switch (err) {
+    case X509_V_OK:
+	break;
+
+    case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
+	ssock->verify_status |= PJ_SSL_CERT_EISSUER_NOT_FOUND;
+	break;
+
+    case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
+    case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
+    case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
+    case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
+	ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
+	break;
+
+    case X509_V_ERR_CERT_NOT_YET_VALID:
+    case X509_V_ERR_CERT_HAS_EXPIRED:
+	ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
+	break;
+
+    case X509_V_ERR_UNABLE_TO_GET_CRL:
+    case X509_V_ERR_CRL_NOT_YET_VALID:
+    case X509_V_ERR_CRL_HAS_EXPIRED:
+    case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
+    case X509_V_ERR_CRL_SIGNATURE_FAILURE:
+    case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
+    case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
+	ssock->verify_status |= PJ_SSL_CERT_ECRL_FAILURE;
+	break;	
+
+    case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
+    case X509_V_ERR_CERT_UNTRUSTED:
+    case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
+    case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
+	ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
+	break;	
+
+    case X509_V_ERR_CERT_SIGNATURE_FAILURE:
+    case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
+    case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
+    case X509_V_ERR_AKID_SKID_MISMATCH:
+    case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
+    case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
+	ssock->verify_status |= PJ_SSL_CERT_EISSUER_MISMATCH;
+	break;
+
+    case X509_V_ERR_CERT_REVOKED:
+	ssock->verify_status |= PJ_SSL_CERT_EREVOKED;
+	break;	
+
+    case X509_V_ERR_INVALID_PURPOSE:
+    case X509_V_ERR_CERT_REJECTED:
+    case X509_V_ERR_INVALID_CA:
+	ssock->verify_status |= PJ_SSL_CERT_EINVALID_PURPOSE;
+	break;
+
+    case X509_V_ERR_CERT_CHAIN_TOO_LONG: /* not really used */
+    case X509_V_ERR_PATH_LENGTH_EXCEEDED:
+	ssock->verify_status |= PJ_SSL_CERT_ECHAIN_TOO_LONG;
+	break;
+
+    /* Unknown errors */
+    case X509_V_ERR_OUT_OF_MEM:
+    default:
+	ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN;
+	break;
+    }
+
+    /* When verification is not requested just return ok here, however
+     * application can still get the verification status.
+     */
+    if (PJ_FALSE == ssock->param.verify_peer)
+	preverify_ok = 1;
+
+    return preverify_ok;
+}
+
+/* Setting SSL sock cipher list */
+static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock);
+
+
+/* Create and initialize new SSL context and instance */
+static pj_status_t create_ssl(pj_ssl_sock_t *ssock)
+{
+    SSL_METHOD *ssl_method;
+    SSL_CTX *ctx;
+    pj_ssl_cert_t *cert;
+    int mode, rc;
+    pj_status_t status;
+        
+    pj_assert(ssock);
+
+    cert = ssock->cert;
+
+    /* Make sure OpenSSL library has been initialized */
+    init_openssl();
+
+    /* Determine SSL method to use */
+    switch (ssock->param.proto) {
+    case PJ_SSL_SOCK_PROTO_DEFAULT:
+    case PJ_SSL_SOCK_PROTO_TLS1:
+	ssl_method = (SSL_METHOD*)TLSv1_method();
+	break;
+#ifndef OPENSSL_NO_SSL2
+    case PJ_SSL_SOCK_PROTO_SSL2:
+	ssl_method = (SSL_METHOD*)SSLv2_method();
+	break;
+#endif
+    case PJ_SSL_SOCK_PROTO_SSL3:
+	ssl_method = (SSL_METHOD*)SSLv3_method();
+	break;
+    case PJ_SSL_SOCK_PROTO_SSL23:
+	ssl_method = (SSL_METHOD*)SSLv23_method();
+	break;
+    //case PJ_SSL_SOCK_PROTO_DTLS1:
+	//ssl_method = (SSL_METHOD*)DTLSv1_method();
+	//break;
+    default:
+	return PJ_EINVAL;
+    }
+
+    /* Create SSL context */
+    ctx = SSL_CTX_new(ssl_method);
+    if (ctx == NULL) {
+	return GET_SSL_STATUS(ssock);
+    }
+
+    /* Apply credentials */
+    if (cert) {
+	/* Load CA list if one is specified. */
+	if (cert->CA_file.slen) {
+
+	    rc = SSL_CTX_load_verify_locations(ctx, cert->CA_file.ptr, NULL);
+
+	    if (rc != 1) {
+		status = GET_SSL_STATUS(ssock);
+		PJ_LOG(1,(ssock->pool->obj_name, "Error loading CA list file "
+			  "'%s'", cert->CA_file.ptr));
+		SSL_CTX_free(ctx);
+		return status;
+	    }
+	}
+    
+	/* Set password callback */
+	if (cert->privkey_pass.slen) {
+	    SSL_CTX_set_default_passwd_cb(ctx, password_cb);
+	    SSL_CTX_set_default_passwd_cb_userdata(ctx, cert);
+	}
+
+
+	/* Load certificate if one is specified */
+	if (cert->cert_file.slen) {
+
+	    /* Load certificate chain from file into ctx */
+	    rc = SSL_CTX_use_certificate_chain_file(ctx, cert->cert_file.ptr);
+
+	    if(rc != 1) {
+		status = GET_SSL_STATUS(ssock);
+		PJ_LOG(1,(ssock->pool->obj_name, "Error loading certificate "
+			  "chain file '%s'", cert->cert_file.ptr));
+		SSL_CTX_free(ctx);
+		return status;
+	    }
+	}
+
+
+	/* Load private key if one is specified */
+	if (cert->privkey_file.slen) {
+	    /* Adds the first private key found in file to ctx */
+	    rc = SSL_CTX_use_PrivateKey_file(ctx, cert->privkey_file.ptr, 
+					     SSL_FILETYPE_PEM);
+
+	    if(rc != 1) {
+		status = GET_SSL_STATUS(ssock);
+		PJ_LOG(1,(ssock->pool->obj_name, "Error adding private key "
+			  "from '%s'", cert->privkey_file.ptr));
+		SSL_CTX_free(ctx);
+		return status;
+	    }
+	}
+    }
+
+    /* Create SSL instance */
+    ssock->ossl_ctx = ctx;
+    ssock->ossl_ssl = SSL_new(ssock->ossl_ctx);
+    if (ssock->ossl_ssl == NULL) {
+	return GET_SSL_STATUS(ssock);
+    }
+
+    /* Set SSL sock as application data of SSL instance */
+    SSL_set_ex_data(ssock->ossl_ssl, sslsock_idx, ssock);
+
+    /* SSL verification options */
+    mode = SSL_VERIFY_PEER;
+    if (ssock->is_server && ssock->param.require_client_cert)
+	mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
+
+    SSL_set_verify(ssock->ossl_ssl, mode, &verify_cb);
+
+    /* Set cipher list */
+    status = set_cipher_list(ssock);
+    if (status != PJ_SUCCESS)
+	return status;
+
+    /* Setup SSL BIOs */
+    ssock->ossl_rbio = BIO_new(BIO_s_mem());
+    ssock->ossl_wbio = BIO_new(BIO_s_mem());
+    (void)BIO_set_close(ssock->ossl_rbio, BIO_CLOSE);
+    (void)BIO_set_close(ssock->ossl_wbio, BIO_CLOSE);
+    SSL_set_bio(ssock->ossl_ssl, ssock->ossl_rbio, ssock->ossl_wbio);
+
+    return PJ_SUCCESS;
+}
+
+
+/* Destroy SSL context and instance */
+static void destroy_ssl(pj_ssl_sock_t *ssock)
+{
+    /* Destroy SSL instance */
+    if (ssock->ossl_ssl) {
+	SSL_shutdown(ssock->ossl_ssl);
+	SSL_free(ssock->ossl_ssl); /* this will also close BIOs */
+	ssock->ossl_ssl = NULL;
+    }
+
+    /* Destroy SSL context */
+    if (ssock->ossl_ctx) {
+	SSL_CTX_free(ssock->ossl_ctx);
+	ssock->ossl_ctx = NULL;
+    }
+
+    /* Potentially shutdown OpenSSL library if this is the last
+     * context exists.
+     */
+    shutdown_openssl();
+}
+
+
+/* Reset SSL socket state */
+static void reset_ssl_sock_state(pj_ssl_sock_t *ssock)
+{
+    ssock->ssl_state = SSL_STATE_NULL;
+
+    destroy_ssl(ssock);
+
+    if (ssock->asock) {
+	pj_activesock_close(ssock->asock);
+	ssock->asock = NULL;
+	ssock->sock = PJ_INVALID_SOCKET;
+    }
+    if (ssock->sock != PJ_INVALID_SOCKET) {
+	pj_sock_close(ssock->sock);
+	ssock->sock = PJ_INVALID_SOCKET;
+    }
+
+    /* Upon error, OpenSSL may leave any error description in the thread 
+     * error queue, which sometime may cause next call to SSL API returning
+     * false error alarm, e.g: in Linux, SSL_CTX_use_certificate_chain_file()
+     * returning false error after a handshake error (in different SSL_CTX!).
+     * For now, just clear thread error queue here.
+     */
+    ERR_clear_error();
+}
+
+
+/* Generate cipher list with user preference order in OpenSSL format */
+static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock)
+{
+    char buf[1024];
+    pj_str_t cipher_list;
+    STACK_OF(SSL_CIPHER) *sk_cipher;
+    unsigned i;
+    int j, ret;
+
+    if (ssock->param.ciphers_num == 0)
+	return PJ_SUCCESS;
+
+    pj_strset(&cipher_list, buf, 0);
+
+    /* Set SSL with ALL available ciphers */
+    SSL_set_cipher_list(ssock->ossl_ssl, "ALL");
+
+    /* Generate user specified cipher list in OpenSSL format */
+    sk_cipher = SSL_get_ciphers(ssock->ossl_ssl);
+    for (i = 0; i < ssock->param.ciphers_num; ++i) {
+	for (j = 0; j < sk_SSL_CIPHER_num(sk_cipher); ++j) {
+	    SSL_CIPHER *c;
+	    c = sk_SSL_CIPHER_value(sk_cipher, j);
+	    if (ssock->param.ciphers[i] == (pj_ssl_cipher)
+					   ((pj_uint32_t)c->id & 0x00FFFFFF))
+	    {
+		const char *c_name;
+
+		c_name = SSL_CIPHER_get_name(c);
+
+		/* Check buffer size */
+		if (cipher_list.slen + pj_ansi_strlen(c_name) + 2 > sizeof(buf)) {
+		    pj_assert(!"Insufficient temporary buffer for cipher");
+		    return PJ_ETOOMANY;
+		}
+
+		/* Add colon separator */
+		if (cipher_list.slen)
+		    pj_strcat2(&cipher_list, ":");
+
+		/* Add the cipher */
+		pj_strcat2(&cipher_list, c_name);
+		break;
+	    }
+	}
+    }
+
+    /* Put NULL termination in the generated cipher list */
+    cipher_list.ptr[cipher_list.slen] = '\0';
+
+    /* Finally, set chosen cipher list */
+    ret = SSL_set_cipher_list(ssock->ossl_ssl, buf);
+    if (ret < 1) {
+	return GET_SSL_STATUS(ssock);
+    }
+
+    return PJ_SUCCESS;
+}
+
+
+/* Parse OpenSSL ASN1_TIME to pj_time_val and GMT info */
+static pj_bool_t parse_ossl_asn1_time(pj_time_val *tv, pj_bool_t *gmt,
+				      const ASN1_TIME *tm)
+{
+    unsigned long parts[7] = {0};
+    char *p, *end;
+    unsigned len;
+    pj_bool_t utc;
+    pj_parsed_time pt;
+    int i;
+
+    utc = tm->type == V_ASN1_UTCTIME;
+    p = (char*)tm->data;
+    len = tm->length;
+    end = p + len - 1;
+
+    /* GMT */
+    *gmt = (*end == 'Z');
+
+    /* parse parts */
+    for (i = 0; i < 7 && p < end; ++i) {
+	pj_str_t st;
+
+	if (i==0 && !utc) {
+	    /* 4 digits year part for non-UTC time format */
+	    st.slen = 4;
+	} else if (i==6) {
+	    /* fraction of seconds */
+	    if (*p == '.') ++p;
+	    st.slen = end - p + 1;
+	} else {
+	    /* other parts always 2 digits length */
+	    st.slen = 2;
+	}
+	st.ptr = p;
+
+	parts[i] = pj_strtoul(&st);
+	p += st.slen;
+    }
+
+    /* encode parts to pj_time_val */
+    pt.year = parts[0];
+    if (utc)
+	pt.year += (pt.year < 50)? 2000:1900;
+    pt.mon = parts[1] - 1;
+    pt.day = parts[2];
+    pt.hour = parts[3];
+    pt.min = parts[4];
+    pt.sec = parts[5];
+    pt.msec = parts[6];
+
+    pj_time_encode(&pt, tv);
+
+    return PJ_TRUE;
+}
+
+
+/* Get Common Name field string from a general name string */
+static void get_cn_from_gen_name(const pj_str_t *gen_name, pj_str_t *cn)
+{
+    pj_str_t CN_sign = {"/CN=", 4};
+    char *p, *q;
+
+    pj_bzero(cn, sizeof(cn));
+
+    p = pj_strstr(gen_name, &CN_sign);
+    if (!p)
+	return;
+
+    p += 4; /* shift pointer to value part */
+    pj_strset(cn, p, gen_name->slen - (p - gen_name->ptr));
+    q = pj_strchr(cn, '/');
+    if (q)
+	cn->slen = q - p;
+}
+
+
+/* Get certificate info from OpenSSL X509, in case the certificate info
+ * hal already populated, this function will check if the contents need 
+ * to be updated by inspecting the issuer and the serial number.
+ */
+static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, X509 *x)
+{
+    pj_bool_t update_needed;
+    char buf[512];
+    pj_uint8_t serial_no[64] = {0}; /* should be >= sizeof(ci->serial_no) */
+    pj_uint8_t *p;
+    unsigned len;
+    GENERAL_NAMES *names = NULL;
+
+    pj_assert(pool && ci && x);
+
+    /* Get issuer */
+    X509_NAME_oneline(X509_get_issuer_name(x), buf, sizeof(buf));
+
+    /* Get serial no */
+    p = (pj_uint8_t*) M_ASN1_STRING_data(X509_get_serialNumber(x));
+    len = M_ASN1_STRING_length(X509_get_serialNumber(x));
+    if (len > sizeof(ci->serial_no)) 
+	len = sizeof(ci->serial_no);
+    pj_memcpy(serial_no + sizeof(ci->serial_no) - len, p, len);
+
+    /* Check if the contents need to be updated. */
+    update_needed = pj_strcmp2(&ci->issuer.info, buf) || 
+	            pj_memcmp(ci->serial_no, serial_no, sizeof(ci->serial_no));
+    if (!update_needed)
+	return;
+
+    /* Update cert info */
+
+    pj_bzero(ci, sizeof(pj_ssl_cert_info));
+
+    /* Version */
+    ci->version = X509_get_version(x) + 1;
+
+    /* Issuer */
+    pj_strdup2(pool, &ci->issuer.info, buf);
+    get_cn_from_gen_name(&ci->issuer.info, &ci->issuer.cn);
+
+    /* Serial number */
+    pj_memcpy(ci->serial_no, serial_no, sizeof(ci->serial_no));
+
+    /* Subject */
+    pj_strdup2(pool, &ci->subject.info, 
+	       X509_NAME_oneline(X509_get_subject_name(x),
+				 buf, sizeof(buf)));
+    get_cn_from_gen_name(&ci->subject.info, &ci->subject.cn);
+
+    /* Validity */
+    parse_ossl_asn1_time(&ci->validity.start, &ci->validity.gmt,
+			 X509_get_notBefore(x));
+    parse_ossl_asn1_time(&ci->validity.end, &ci->validity.gmt,
+			 X509_get_notAfter(x));
+
+    /* Subject Alternative Name extension */
+    if (ci->version >= 3) {
+	names = (GENERAL_NAMES*) X509_get_ext_d2i(x, NID_subject_alt_name,
+						  NULL, NULL);
+    }
+    if (names) {
+        unsigned i, cnt;
+
+        cnt = sk_GENERAL_NAME_num(names);
+	ci->subj_alt_name.entry = pj_pool_calloc(pool, cnt, 
+					    sizeof(*ci->subj_alt_name.entry));
+
+        for (i = 0; i < cnt; ++i) {
+	    unsigned char *p = 0;
+	    pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN;
+            const GENERAL_NAME *name;
+	    
+	    name = sk_GENERAL_NAME_value(names, i);
+
+            switch (name->type) {
+                case GEN_EMAIL:
+                    len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
+		    type = PJ_SSL_CERT_NAME_RFC822;
+                    break;
+                case GEN_DNS:
+                    len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
+		    type = PJ_SSL_CERT_NAME_DNS;
+                    break;
+                case GEN_URI:
+                    len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
+		    type = PJ_SSL_CERT_NAME_URI;
+                    break;
+                case GEN_IPADD:
+		    p = ASN1_STRING_data(name->d.ip);
+		    len = ASN1_STRING_length(name->d.ip);
+		    type = PJ_SSL_CERT_NAME_IP;
+                    break;
+		default:
+		    break;
+            }
+
+	    if (p && len && type != PJ_SSL_CERT_NAME_UNKNOWN) {
+		ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type;
+		if (type == PJ_SSL_CERT_NAME_IP) {
+		    int af = pj_AF_INET();
+		    if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6();
+		    pj_inet_ntop2(af, p, buf, sizeof(buf));
+		    pj_strdup2(pool, 
+		          &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
+		          buf);
+		} else {
+		    pj_strdup2(pool, 
+			  &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name, 
+			  (char*)p);
+		    OPENSSL_free(p);
+		}
+		ci->subj_alt_name.cnt++;
+	    }
+        }
+    }
+}
+
+
+/* Update local & remote certificates info. This function should be
+ * called after handshake or renegotiation successfully completed.
+ */
+static void update_certs_info(pj_ssl_sock_t *ssock)
+{
+    X509 *x;
+
+    pj_assert(ssock->ssl_state == SSL_STATE_ESTABLISHED);
+
+    /* Active local certificate */
+    x = SSL_get_certificate(ssock->ossl_ssl);
+    if (x) {
+	get_cert_info(ssock->pool, &ssock->local_cert_info, x);
+	/* Don't free local's X509! */
+    } else {
+	pj_bzero(&ssock->local_cert_info, sizeof(pj_ssl_cert_info));
+    }
+
+    /* Active remote certificate */
+    x = SSL_get_peer_certificate(ssock->ossl_ssl);
+    if (x) {
+	get_cert_info(ssock->pool, &ssock->remote_cert_info, x);
+	/* Free peer's X509 */
+	X509_free(x);
+    } else {
+	pj_bzero(&ssock->remote_cert_info, sizeof(pj_ssl_cert_info));
+    }
+}
+
+
+/* When handshake completed:
+ * - notify application
+ * - if handshake failed, reset SSL state
+ * - return PJ_FALSE when SSL socket instance is destroyed by application.
+ */
+static pj_bool_t on_handshake_complete(pj_ssl_sock_t *ssock, 
+				       pj_status_t status)
+{
+    /* Cancel handshake timer */
+    if (ssock->timer.id == TIMER_HANDSHAKE_TIMEOUT) {
+	pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
+	ssock->timer.id = TIMER_NONE;
+    }
+
+    /* Update certificates info on successful handshake */
+    if (status == PJ_SUCCESS)
+	update_certs_info(ssock);
+
+    /* Accepting */
+    if (ssock->is_server) {
+	if (status != PJ_SUCCESS) {
+	    /* Handshake failed in accepting, destroy our self silently. */
+
+	    char errmsg[PJ_ERR_MSG_SIZE];
+	    char buf[PJ_INET6_ADDRSTRLEN+10];
+
+	    pj_strerror(status, errmsg, sizeof(errmsg));
+	    PJ_LOG(3,(ssock->pool->obj_name, "Handshake failed in accepting "
+		      "%s: %s",
+		      pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3),
+		      errmsg));
+
+	    /* Workaround for ticket #985 */
+#if (defined(PJ_WIN32) && PJ_WIN32!=0) || (defined(PJ_WIN64) && PJ_WIN64!=0)
+	    if (ssock->param.timer_heap) {
+		pj_time_val interval = {0, DELAYED_CLOSE_TIMEOUT};
+
+		reset_ssl_sock_state(ssock);
+
+		ssock->timer.id = TIMER_CLOSE;
+		pj_time_val_normalize(&interval);
+		if (pj_timer_heap_schedule(ssock->param.timer_heap, 
+					   &ssock->timer, &interval) != 0)
+		{
+		    ssock->timer.id = TIMER_NONE;
+		    pj_ssl_sock_close(ssock);
+		}
+	    } else 
+#endif	/* PJ_WIN32 */
+	    {
+		pj_ssl_sock_close(ssock);
+	    }
+	    return PJ_FALSE;
+	}
+	/* Notify application the newly accepted SSL socket */
+	if (ssock->param.cb.on_accept_complete) {
+	    pj_bool_t ret;
+	    ret = (*ssock->param.cb.on_accept_complete)
+		      (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr,
+		       pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr));
+	    if (ret == PJ_FALSE)
+		return PJ_FALSE;
+	}
+    }
+
+    /* Connecting */
+    else {
+	/* On failure, reset SSL socket state first, as app may try to 
+	 * reconnect in the callback.
+	 */
+	if (status != PJ_SUCCESS) {
+	    /* Server disconnected us, possibly due to SSL nego failure */
+	    if (status == PJ_EEOF) {
+		unsigned long err;
+		err = ERR_get_error();
+		if (err != SSL_ERROR_NONE)
+		    status = STATUS_FROM_SSL_ERR(ssock, err);
+	    }
+	    reset_ssl_sock_state(ssock);
+	}
+	if (ssock->param.cb.on_connect_complete) {
+	    pj_bool_t ret;
+	    ret = (*ssock->param.cb.on_connect_complete)(ssock, status);
+	    if (ret == PJ_FALSE)
+		return PJ_FALSE;
+	}
+    }
+
+    return PJ_TRUE;
+}
+
+static write_data_t* alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len)
+{
+    send_buf_t *send_buf = &ssock->send_buf;
+    pj_size_t avail_len, skipped_len = 0;
+    char *reg1, *reg2;
+    pj_size_t reg1_len, reg2_len;
+    write_data_t *p;
+
+    /* Check buffer availability */
+    avail_len = send_buf->max_len - send_buf->len;
+    if (avail_len < len)
+	return NULL;
+
+    /* If buffer empty, reset start pointer and return it */
+    if (send_buf->len == 0) {
+	send_buf->start = send_buf->buf;
+	send_buf->len   = len;
+	p = (write_data_t*)send_buf->start;
+	goto init_send_data;
+    }
+
+    /* Free space may be wrapped/splitted into two regions, so let's
+     * analyze them if any region can hold the write data.
+     */
+    reg1 = send_buf->start + send_buf->len;
+    if (reg1 >= send_buf->buf + send_buf->max_len)
+	reg1 -= send_buf->max_len;
+    reg1_len = send_buf->max_len - send_buf->len;
+    if (reg1 + reg1_len > send_buf->buf + send_buf->max_len) {
+	reg1_len = send_buf->buf + send_buf->max_len - reg1;
+	reg2 = send_buf->buf;
+	reg2_len = send_buf->start - send_buf->buf;
+    } else {
+	reg2 = NULL;
+	reg2_len = 0;
+    }
+
+    /* More buffer availability check, note that the write data must be in
+     * a contigue buffer.
+     */
+    avail_len = PJ_MAX(reg1_len, reg2_len);
+    if (avail_len < len)
+	return NULL;
+
+    /* Get the data slot */
+    if (reg1_len >= len) {
+	p = (write_data_t*)reg1;
+    } else {
+	p = (write_data_t*)reg2;
+	skipped_len = reg1_len;
+    }
+
+    /* Update buffer length */
+    send_buf->len += len + skipped_len;
+
+init_send_data:
+    /* Init the new send data */
+    pj_bzero(p, sizeof(*p));
+    pj_list_init(p);
+    pj_list_push_back(&ssock->send_pending, p);
+
+    return p;
+}
+
+static void free_send_data(pj_ssl_sock_t *ssock, write_data_t *wdata)
+{
+    send_buf_t *buf = &ssock->send_buf;
+    write_data_t *spl = &ssock->send_pending;
+
+    pj_assert(!pj_list_empty(&ssock->send_pending));
+    
+    /* Free slot from the buffer */
+    if (spl->next == wdata && spl->prev == wdata) {
+	/* This is the only data, reset the buffer */
+	buf->start = buf->buf;
+	buf->len = 0;
+    } else if (spl->next == wdata) {
+	/* This is the first data, shift start pointer of the buffer and
+	 * adjust the buffer length.
+	 */
+	buf->start = (char*)wdata->next;
+	if (wdata->next > wdata) {
+	    buf->len -= ((char*)wdata->next - buf->start);
+	} else {
+	    /* Overlapped */
+	    pj_size_t right_len, left_len;
+	    right_len = buf->buf + buf->max_len - (char*)wdata;
+	    left_len  = (char*)wdata->next - buf->buf;
+	    buf->len -= (right_len + left_len);
+	}
+    } else if (spl->prev == wdata) {
+	/* This is the last data, just adjust the buffer length */
+	if (wdata->prev < wdata) {
+	    pj_size_t jump_len;
+	    jump_len = (char*)wdata -
+		       ((char*)wdata->prev + wdata->prev->record_len);
+	    buf->len -= (wdata->record_len + jump_len);
+	} else {
+	    /* Overlapped */
+	    pj_size_t right_len, left_len;
+	    right_len = buf->buf + buf->max_len -
+			((char*)wdata->prev + wdata->prev->record_len);
+	    left_len  = (char*)wdata + wdata->record_len - buf->buf;
+	    buf->len -= (right_len + left_len);
+	}
+    }
+    /* For data in the middle buffer, just do nothing on the buffer. The slot
+     * will be freed later when freeing the first/last data.
+     */
+    
+    /* Remove the data from send pending list */
+    pj_list_erase(wdata);
+}
+
+#if 0
+/* Just for testing send buffer alloc/free */
+#include <pj/rand.h>
+pj_status_t pj_ssl_sock_ossl_test_send_buf(pj_pool_t *pool)
+{
+    enum { MAX_CHUNK_NUM = 20 };
+    unsigned chunk_size, chunk_cnt, i;
+    write_data_t *wdata[MAX_CHUNK_NUM] = {0};
+    pj_time_val now;
+    pj_ssl_sock_t *ssock = NULL;
+    pj_ssl_sock_param param;
+    pj_status_t status;
+
+    pj_gettimeofday(&now);
+    pj_srand((unsigned)now.sec);
+
+    pj_ssl_sock_param_default(&param);
+    status = pj_ssl_sock_create(pool, &param, &ssock);
+    if (status != PJ_SUCCESS) {
+	return status;
+    }
+
+    if (ssock->send_buf.max_len == 0) {
+	ssock->send_buf.buf = (char*)
+			      pj_pool_alloc(ssock->pool, 
+					    ssock->param.send_buffer_size);
+	ssock->send_buf.max_len = ssock->param.send_buffer_size;
+	ssock->send_buf.start = ssock->send_buf.buf;
+	ssock->send_buf.len = 0;
+    }
+
+    chunk_size = ssock->param.send_buffer_size / MAX_CHUNK_NUM / 2;
+    chunk_cnt = 0;
+    for (i = 0; i < MAX_CHUNK_NUM; i++) {
+	wdata[i] = alloc_send_data(ssock, pj_rand() % chunk_size + 321);
+	if (wdata[i])
+	    chunk_cnt++;
+	else
+	    break;
+    }
+
+    while (chunk_cnt) {
+	i = pj_rand() % MAX_CHUNK_NUM;
+	if (wdata[i]) {
+	    free_send_data(ssock, wdata[i]);
+	    wdata[i] = NULL;
+	    chunk_cnt--;
+	}
+    }
+
+    if (ssock->send_buf.len != 0)
+	status = PJ_EBUG;
+
+    pj_ssl_sock_close(ssock);
+    return status;
+}
+#endif
+
+
+/* Flush write BIO to network socket. Note that any access to write BIO
+ * MUST be serialized, so mutex protection must cover any call to OpenSSL
+ * API (that possibly generate data for write BIO) along with the call to
+ * this function (flushing all data in write BIO generated by above 
+ * OpenSSL API call).
+ */
+static pj_status_t flush_write_bio(pj_ssl_sock_t *ssock, 
+				   pj_ioqueue_op_key_t *send_key,
+				   pj_size_t orig_len,
+				   unsigned flags)
+{
+    char *data;
+    pj_ssize_t len;
+    write_data_t *wdata;
+    pj_size_t needed_len;
+    pj_status_t status;
+
+    pj_lock_acquire(ssock->write_mutex);
+
+    /* Check if there is data in write BIO, flush it if any */
+    if (!BIO_pending(ssock->ossl_wbio)) {
+	pj_lock_release(ssock->write_mutex);
+	return PJ_SUCCESS;
+    }
+
+    /* Get data and its length */
+    len = BIO_get_mem_data(ssock->ossl_wbio, &data);
+    if (len == 0) {
+	pj_lock_release(ssock->write_mutex);
+	return PJ_SUCCESS;
+    }
+
+    /* Calculate buffer size needed, and align it to 8 */
+    needed_len = len + sizeof(write_data_t);
+    needed_len = ((needed_len + 7) >> 3) << 3;
+
+    /* Allocate buffer for send data */
+    wdata = alloc_send_data(ssock, needed_len);
+    if (wdata == NULL) {
+	pj_lock_release(ssock->write_mutex);
+	return PJ_ENOMEM;
+    }
+
+    /* Copy the data and set its properties into the send data */
+    pj_ioqueue_op_key_init(&wdata->key, sizeof(pj_ioqueue_op_key_t));
+    wdata->key.user_data = wdata;
+    wdata->app_key = send_key;
+    wdata->record_len = needed_len;
+    wdata->data_len = len;
+    wdata->plain_data_len = orig_len;
+    wdata->flags = flags;
+    pj_memcpy(&wdata->data, data, len);
+
+    /* Reset write BIO */
+    (void)BIO_reset(ssock->ossl_wbio);
+
+    /* Ticket #1573: Don't hold mutex while calling PJLIB socket send(). */
+    pj_lock_release(ssock->write_mutex);
+
+    /* Send it */
+    if (ssock->param.sock_type == pj_SOCK_STREAM()) {
+	status = pj_activesock_send(ssock->asock, &wdata->key, 
+				    wdata->data.content, &len,
+				    flags);
+    } else {
+	status = pj_activesock_sendto(ssock->asock, &wdata->key, 
+				      wdata->data.content, &len,
+				      flags,
+				      (pj_sockaddr_t*)&ssock->rem_addr,
+				      ssock->addr_len);
+    }
+
+    if (status != PJ_EPENDING) {
+	/* When the sending is not pending, remove the wdata from send
+	 * pending list.
+	 */
+	pj_lock_acquire(ssock->write_mutex);
+	free_send_data(ssock, wdata);
+	pj_lock_release(ssock->write_mutex);
+    }
+
+    return status;
+}
+
+
+static void on_timer(pj_timer_heap_t *th, struct pj_timer_entry *te)
+{
+    pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)te->user_data;
+    int timer_id = te->id;
+
+    te->id = TIMER_NONE;
+
+    PJ_UNUSED_ARG(th);
+
+    switch (timer_id) {
+    case TIMER_HANDSHAKE_TIMEOUT:
+	PJ_LOG(1,(ssock->pool->obj_name, "SSL timeout after %d.%ds",
+		  ssock->param.timeout.sec, ssock->param.timeout.msec));
+
+	on_handshake_complete(ssock, PJ_ETIMEDOUT);
+	break;
+    case TIMER_CLOSE:
+	pj_ssl_sock_close(ssock);
+	break;
+    default:
+	pj_assert(!"Unknown timer");
+	break;
+    }
+}
+
+
+/* Asynchronouse handshake */
+static pj_status_t do_handshake(pj_ssl_sock_t *ssock)
+{
+    pj_status_t status;
+    int err;
+
+    /* Perform SSL handshake */
+    pj_lock_acquire(ssock->write_mutex);
+    err = SSL_do_handshake(ssock->ossl_ssl);
+    pj_lock_release(ssock->write_mutex);
+
+    /* SSL_do_handshake() may put some pending data into SSL write BIO, 
+     * flush it if any.
+     */
+    status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
+    if (status != PJ_SUCCESS && status != PJ_EPENDING) {
+	return status;
+    }
+
+    if (err < 0) {
+	err = SSL_get_error(ssock->ossl_ssl, err);
+	if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ) 
+	{
+	    /* Handshake fails */
+	    status = STATUS_FROM_SSL_ERR(ssock, err);
+	    return status;
+	}
+    }
+
+    /* Check if handshake has been completed */
+    if (SSL_is_init_finished(ssock->ossl_ssl)) {
+	ssock->ssl_state = SSL_STATE_ESTABLISHED;
+	return PJ_SUCCESS;
+    }
+
+    return PJ_EPENDING;
+}
+
+
+/*
+ *******************************************************************
+ * Active socket callbacks.
+ *******************************************************************
+ */
+
+static pj_bool_t asock_on_data_read (pj_activesock_t *asock,
+				     void *data,
+				     pj_size_t size,
+				     pj_status_t status,
+				     pj_size_t *remainder)
+{
+    pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
+			   pj_activesock_get_user_data(asock);
+    pj_size_t nwritten;
+
+    /* Socket error or closed */
+    if (data && size > 0) {
+	/* Consume the whole data */
+	nwritten = BIO_write(ssock->ossl_rbio, data, (int)size);
+	if (nwritten < size) {
+	    status = GET_SSL_STATUS(ssock);
+	    goto on_error;
+	}
+    }
+
+    /* Check if SSL handshake hasn't finished yet */
+    if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
+	pj_bool_t ret = PJ_TRUE;
+
+	if (status == PJ_SUCCESS)
+	    status = do_handshake(ssock);
+
+	/* Not pending is either success or failed */
+	if (status != PJ_EPENDING)
+	    ret = on_handshake_complete(ssock, status);
+
+	return ret;
+    }
+
+    /* See if there is any decrypted data for the application */
+    if (ssock->read_started) {
+	do {
+	    read_data_t *buf = *(OFFSET_OF_READ_DATA_PTR(ssock, data));
+	    void *data_ = (pj_int8_t*)buf->data + buf->len;
+	    int size_ = (int)(ssock->read_size - buf->len);
+
+	    /* SSL_read() may write some data to BIO write when re-negotiation
+	     * is on progress, so let's protect it with write mutex.
+	     */
+	    pj_lock_acquire(ssock->write_mutex);
+	    size_ = SSL_read(ssock->ossl_ssl, data_, size_);
+	    pj_lock_release(ssock->write_mutex);
+
+	    if (size_ > 0 || status != PJ_SUCCESS) {
+		if (ssock->param.cb.on_data_read) {
+		    pj_bool_t ret;
+		    pj_size_t remainder_ = 0;
+
+		    if (size_ > 0)
+			buf->len += size_;
+    		
+		    ret = (*ssock->param.cb.on_data_read)(ssock, buf->data,
+							  buf->len, status,
+							  &remainder_);
+		    if (!ret) {
+			/* We've been destroyed */
+			return PJ_FALSE;
+		    }
+
+		    /* Application may have left some data to be consumed 
+		     * later.
+		     */
+		    buf->len = remainder_;
+		}
+
+		/* Active socket signalled connection closed/error, this has
+		 * been signalled to the application along with any remaining
+		 * buffer. So, let's just reset SSL socket now.
+		 */
+		if (status != PJ_SUCCESS) {
+		    reset_ssl_sock_state(ssock);
+		    return PJ_FALSE;
+		}
+
+	    } else {
+
+		int err = SSL_get_error(ssock->ossl_ssl, (int)size);
+		
+		/* SSL might just return SSL_ERROR_WANT_READ in 
+		 * re-negotiation.
+		 */
+		if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ)
+		{
+		    /* Reset SSL socket state, then return PJ_FALSE */
+		    status = STATUS_FROM_SSL_ERR(ssock, err);
+		    reset_ssl_sock_state(ssock);
+		    goto on_error;
+		}
+
+		status = do_handshake(ssock);
+		if (status == PJ_SUCCESS) {
+		    /* Renegotiation completed */
+
+		    /* Update certificates */
+		    update_certs_info(ssock);
+
+		    // Ticket #1573: Don't hold mutex while calling
+		    //               PJLIB socket send(). 
+		    //pj_lock_acquire(ssock->write_mutex);
+		    status = flush_delayed_send(ssock);
+		    //pj_lock_release(ssock->write_mutex);
+
+		    /* If flushing is ongoing, treat it as success */
+		    if (status == PJ_EBUSY)
+			status = PJ_SUCCESS;
+
+		    if (status != PJ_SUCCESS && status != PJ_EPENDING) {
+			PJ_PERROR(1,(ssock->pool->obj_name, status, 
+				     "Failed to flush delayed send"));
+			goto on_error;
+		    }
+		} else if (status != PJ_EPENDING) {
+		    PJ_PERROR(1,(ssock->pool->obj_name, status, 
+			         "Renegotiation failed"));
+		    goto on_error;
+		}
+
+		break;
+	    }
+	} while (1);
+    }
+
+    return PJ_TRUE;
+
+on_error:
+    if (ssock->ssl_state == SSL_STATE_HANDSHAKING)
+	return on_handshake_complete(ssock, status);
+
+    if (ssock->read_started && ssock->param.cb.on_data_read) {
+	pj_bool_t ret;
+	ret = (*ssock->param.cb.on_data_read)(ssock, NULL, 0, status,
+					      remainder);
+	if (!ret) {
+	    /* We've been destroyed */
+	    return PJ_FALSE;
+	}
+    }
+
+    reset_ssl_sock_state(ssock);
+    return PJ_FALSE;
+}
+
+
+static pj_bool_t asock_on_data_sent (pj_activesock_t *asock,
+				     pj_ioqueue_op_key_t *send_key,
+				     pj_ssize_t sent)
+{
+    pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
+			   pj_activesock_get_user_data(asock);
+
+    PJ_UNUSED_ARG(send_key);
+    PJ_UNUSED_ARG(sent);
+
+    if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
+	/* Initial handshaking */
+	pj_status_t status;
+	
+	status = do_handshake(ssock);
+	/* Not pending is either success or failed */
+	if (status != PJ_EPENDING)
+	    return on_handshake_complete(ssock, status);
+
+    } else if (send_key != &ssock->handshake_op_key) {
+	/* Some data has been sent, notify application */
+	write_data_t *wdata = (write_data_t*)send_key->user_data;
+	if (ssock->param.cb.on_data_sent) {
+	    pj_bool_t ret;
+	    pj_ssize_t sent_len;
+
+	    sent_len = (sent > 0)? wdata->plain_data_len : sent;
+	    ret = (*ssock->param.cb.on_data_sent)(ssock, wdata->app_key, 
+						  sent_len);
+	    if (!ret) {
+		/* We've been destroyed */
+		return PJ_FALSE;
+	    }
+	}
+
+	/* Update write buffer state */
+	pj_lock_acquire(ssock->write_mutex);
+	free_send_data(ssock, wdata);
+	pj_lock_release(ssock->write_mutex);
+
+    } else {
+	/* SSL re-negotiation is on-progress, just do nothing */
+    }
+
+    return PJ_TRUE;
+}
+
+
+static pj_bool_t asock_on_accept_complete (pj_activesock_t *asock,
+					   pj_sock_t newsock,
+					   const pj_sockaddr_t *src_addr,
+					   int src_addr_len)
+{
+    pj_ssl_sock_t *ssock_parent = (pj_ssl_sock_t*)
+				  pj_activesock_get_user_data(asock);
+    pj_ssl_sock_t *ssock;
+    pj_activesock_cb asock_cb;
+    pj_activesock_cfg asock_cfg;
+    unsigned i;
+    pj_status_t status;
+
+    PJ_UNUSED_ARG(src_addr_len);
+
+    /* Create new SSL socket instance */
+    status = pj_ssl_sock_create(ssock_parent->pool, &ssock_parent->param,
+				&ssock);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Update new SSL socket attributes */
+    ssock->sock = newsock;
+    ssock->parent = ssock_parent;
+    ssock->is_server = PJ_TRUE;
+    if (ssock_parent->cert) {
+	status = pj_ssl_sock_set_certificate(ssock, ssock->pool, 
+					     ssock_parent->cert);
+	if (status != PJ_SUCCESS)
+	    goto on_return;
+    }
+
+    /* Apply QoS, if specified */
+    status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
+				&ssock->param.qos_params, 1, 
+				ssock->pool->obj_name, NULL);
+    if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
+	goto on_return;
+
+    /* Update local address */
+    ssock->addr_len = src_addr_len;
+    status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 
+				 &ssock->addr_len);
+    if (status != PJ_SUCCESS) {
+	/* This fails on few envs, e.g: win IOCP, just tolerate this and
+	 * use parent local address instead.
+	 */
+	pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr);
+    }
+
+    /* Set remote address */
+    pj_sockaddr_cp(&ssock->rem_addr, src_addr);
+
+    /* Create SSL context */
+    status = create_ssl(ssock);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Prepare read buffer */
+    ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool, 
+					       ssock->param.async_cnt,
+					       sizeof(void*));
+    for (i = 0; i<ssock->param.async_cnt; ++i) {
+	ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
+					    ssock->pool, 
+					    ssock->param.read_buffer_size + 
+					    sizeof(read_data_t*));
+    }
+
+    /* Create active socket */
+    pj_activesock_cfg_default(&asock_cfg);
+    asock_cfg.async_cnt = ssock->param.async_cnt;
+    asock_cfg.concurrency = ssock->param.concurrency;
+    asock_cfg.whole_data = PJ_TRUE;
+
+    pj_bzero(&asock_cb, sizeof(asock_cb));
+    asock_cb.on_data_read = asock_on_data_read;
+    asock_cb.on_data_sent = asock_on_data_sent;
+
+    status = pj_activesock_create(ssock->pool,
+				  ssock->sock, 
+				  ssock->param.sock_type,
+				  &asock_cfg,
+				  ssock->param.ioqueue, 
+				  &asock_cb,
+				  ssock,
+				  &ssock->asock);
+
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Start read */
+    status = pj_activesock_start_read2(ssock->asock, ssock->pool, 
+				       (unsigned)ssock->param.read_buffer_size,
+				       ssock->asock_rbuf,
+				       PJ_IOQUEUE_ALWAYS_ASYNC);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Prepare write/send state */
+    pj_assert(ssock->send_buf.max_len == 0);
+    ssock->send_buf.buf = (char*)
+			  pj_pool_alloc(ssock->pool, 
+					ssock->param.send_buffer_size);
+    ssock->send_buf.max_len = ssock->param.send_buffer_size;
+    ssock->send_buf.start = ssock->send_buf.buf;
+    ssock->send_buf.len = 0;
+
+    /* Start handshake timer */
+    if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
+	ssock->param.timeout.msec != 0))
+    {
+	pj_assert(ssock->timer.id == TIMER_NONE);
+	ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
+	status = pj_timer_heap_schedule(ssock->param.timer_heap, 
+				        &ssock->timer,
+					&ssock->param.timeout);
+	if (status != PJ_SUCCESS)
+	    ssock->timer.id = TIMER_NONE;
+    }
+
+    /* Start SSL handshake */
+    ssock->ssl_state = SSL_STATE_HANDSHAKING;
+    SSL_set_accept_state(ssock->ossl_ssl);
+    status = do_handshake(ssock);
+
+on_return:
+    if (ssock && status != PJ_EPENDING)
+	on_handshake_complete(ssock, status);
+
+    /* Must return PJ_TRUE whatever happened, as active socket must 
+     * continue listening.
+     */
+    return PJ_TRUE;
+}
+
+
+static pj_bool_t asock_on_connect_complete (pj_activesock_t *asock,
+					    pj_status_t status)
+{
+    pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
+			   pj_activesock_get_user_data(asock);
+    unsigned i;
+
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Update local address */
+    ssock->addr_len = sizeof(pj_sockaddr);
+    status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 
+				 &ssock->addr_len);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Create SSL context */
+    status = create_ssl(ssock);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Prepare read buffer */
+    ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool, 
+					       ssock->param.async_cnt,
+					       sizeof(void*));
+    for (i = 0; i<ssock->param.async_cnt; ++i) {
+	ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
+					    ssock->pool, 
+					    ssock->param.read_buffer_size + 
+					    sizeof(read_data_t*));
+    }
+
+    /* Start read */
+    status = pj_activesock_start_read2(ssock->asock, ssock->pool, 
+				       (unsigned)ssock->param.read_buffer_size,
+				       ssock->asock_rbuf,
+				       PJ_IOQUEUE_ALWAYS_ASYNC);
+    if (status != PJ_SUCCESS)
+	goto on_return;
+
+    /* Prepare write/send state */
+    pj_assert(ssock->send_buf.max_len == 0);
+    ssock->send_buf.buf = (char*)
+			     pj_pool_alloc(ssock->pool, 
+					   ssock->param.send_buffer_size);
+    ssock->send_buf.max_len = ssock->param.send_buffer_size;
+    ssock->send_buf.start = ssock->send_buf.buf;
+    ssock->send_buf.len = 0;
+
+#ifdef SSL_set_tlsext_host_name
+    /* Set server name to connect */
+    if (ssock->param.server_name.slen) {
+	/* Server name is null terminated already */
+	if (!SSL_set_tlsext_host_name(ssock->ossl_ssl, 
+				      ssock->param.server_name.ptr))
+	{
+	    char err_str[PJ_ERR_MSG_SIZE];
+
+	    ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str));
+	    PJ_LOG(3,(ssock->pool->obj_name, "SSL_set_tlsext_host_name() "
+		"failed: %s", err_str));
+	}
+    }
+#endif
+
+    /* Start SSL handshake */
+    ssock->ssl_state = SSL_STATE_HANDSHAKING;
+    SSL_set_connect_state(ssock->ossl_ssl);
+
+    status = do_handshake(ssock);
+    if (status != PJ_EPENDING)
+	goto on_return;
+
+    return PJ_TRUE;
+
+on_return:
+    return on_handshake_complete(ssock, status);
+}
+
+
+
+/*
+ *******************************************************************
+ * API
+ *******************************************************************
+ */
+
+/* Load credentials from files. */
+PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files (pj_pool_t *pool,
+						 const pj_str_t *CA_file,
+						 const pj_str_t *cert_file,
+						 const pj_str_t *privkey_file,
+						 const pj_str_t *privkey_pass,
+						 pj_ssl_cert_t **p_cert)
+{
+    pj_ssl_cert_t *cert;
+
+    PJ_ASSERT_RETURN(pool && CA_file && cert_file && privkey_file, PJ_EINVAL);
+
+    cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
+    pj_strdup_with_null(pool, &cert->CA_file, CA_file);
+    pj_strdup_with_null(pool, &cert->cert_file, cert_file);
+    pj_strdup_with_null(pool, &cert->privkey_file, privkey_file);
+    pj_strdup_with_null(pool, &cert->privkey_pass, privkey_pass);
+
+    *p_cert = cert;
+
+    return PJ_SUCCESS;
+}
+
+
+/* Set SSL socket credentials. */
+PJ_DECL(pj_status_t) pj_ssl_sock_set_certificate(
+					    pj_ssl_sock_t *ssock,
+					    pj_pool_t *pool,
+					    const pj_ssl_cert_t *cert)
+{
+    pj_ssl_cert_t *cert_;
+
+    PJ_ASSERT_RETURN(ssock && pool && cert, PJ_EINVAL);
+
+    cert_ = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
+    pj_memcpy(cert_, cert, sizeof(cert));
+    pj_strdup_with_null(pool, &cert_->CA_file, &cert->CA_file);
+    pj_strdup_with_null(pool, &cert_->cert_file, &cert->cert_file);
+    pj_strdup_with_null(pool, &cert_->privkey_file, &cert->privkey_file);
+    pj_strdup_with_null(pool, &cert_->privkey_pass, &cert->privkey_pass);
+
+    ssock->cert = cert_;
+
+    return PJ_SUCCESS;
+}
+
+
+/* Get available ciphers. */
+PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[],
+					         unsigned *cipher_num)
+{
+    unsigned i;
+
+    PJ_ASSERT_RETURN(ciphers && cipher_num, PJ_EINVAL);
+
+    if (openssl_cipher_num == 0) {
+	init_openssl();
+	shutdown_openssl();
+    }
+
+    if (openssl_cipher_num == 0) {
+	*cipher_num = 0;
+	return PJ_ENOTFOUND;
+    }
+
+    *cipher_num = PJ_MIN(*cipher_num, openssl_cipher_num);
+
+    for (i = 0; i < *cipher_num; ++i)
+	ciphers[i] = openssl_ciphers[i].id;
+
+    return PJ_SUCCESS;
+}
+
+
+/* Get cipher name string */
+PJ_DEF(const char*) pj_ssl_cipher_name(pj_ssl_cipher cipher)
+{
+    unsigned i;
+
+    if (openssl_cipher_num == 0) {
+	init_openssl();
+	shutdown_openssl();
+    }
+
+    for (i = 0; i < openssl_cipher_num; ++i) {
+	if (cipher == openssl_ciphers[i].id)
+	    return openssl_ciphers[i].name;
+    }
+
+    return NULL;
+}
+
+/* Check if the specified cipher is supported by SSL/TLS backend. */
+PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher)
+{
+    unsigned i;
+
+    if (openssl_cipher_num == 0) {
+	init_openssl();
+	shutdown_openssl();
+    }
+
+    for (i = 0; i < openssl_cipher_num; ++i) {
+	if (cipher == openssl_ciphers[i].id)
+	    return PJ_TRUE;
+    }
+
+    return PJ_FALSE;
+}
+
+
+/*
+ * Create SSL socket instance. 
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool,
+					const pj_ssl_sock_param *param,
+					pj_ssl_sock_t **p_ssock)
+{
+    pj_ssl_sock_t *ssock;
+    pj_status_t status;
+
+    PJ_ASSERT_RETURN(pool && param && p_ssock, PJ_EINVAL);
+    PJ_ASSERT_RETURN(param->sock_type == pj_SOCK_STREAM(), PJ_ENOTSUP);
+
+    pool = pj_pool_create(pool->factory, "ssl%p", 512, 512, NULL);
+
+    /* Create secure socket */
+    ssock = PJ_POOL_ZALLOC_T(pool, pj_ssl_sock_t);
+    ssock->pool = pool;
+    ssock->sock = PJ_INVALID_SOCKET;
+    ssock->ssl_state = SSL_STATE_NULL;
+    pj_list_init(&ssock->write_pending);
+    pj_list_init(&ssock->write_pending_empty);
+    pj_list_init(&ssock->send_pending);
+    pj_timer_entry_init(&ssock->timer, 0, ssock, &on_timer);
+    pj_ioqueue_op_key_init(&ssock->handshake_op_key,
+			   sizeof(pj_ioqueue_op_key_t));
+
+    /* Create secure socket mutex */
+    status = pj_lock_create_recursive_mutex(pool, pool->obj_name,
+					    &ssock->write_mutex);
+    if (status != PJ_SUCCESS)
+	return status;
+
+    /* Init secure socket param */
+    ssock->param = *param;
+    ssock->param.read_buffer_size = ((ssock->param.read_buffer_size+7)>>3)<<3;
+    if (param->ciphers_num > 0) {
+	unsigned i;
+	ssock->param.ciphers = (pj_ssl_cipher*)
+			       pj_pool_calloc(pool, param->ciphers_num, 
+					      sizeof(pj_ssl_cipher));
+	for (i = 0; i < param->ciphers_num; ++i)
+	    ssock->param.ciphers[i] = param->ciphers[i];
+    }
+
+    /* Server name must be null-terminated */
+    pj_strdup_with_null(pool, &ssock->param.server_name, 
+			&param->server_name);
+
+    /* Finally */
+    *p_ssock = ssock;
+
+    return PJ_SUCCESS;
+}
+
+
+/*
+ * Close the secure socket. This will unregister the socket from the
+ * ioqueue and ultimately close the socket.
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock)
+{
+    pj_pool_t *pool;
+
+    PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
+
+    if (!ssock->pool)
+	return PJ_SUCCESS;
+
+    if (ssock->timer.id != TIMER_NONE) {
+	pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
+	ssock->timer.id = TIMER_NONE;
+    }
+
+    reset_ssl_sock_state(ssock);
+    pj_lock_destroy(ssock->write_mutex);
+    
+    pool = ssock->pool;
+    ssock->pool = NULL;
+    if (pool)
+	pj_pool_release(pool);
+
+    return PJ_SUCCESS;
+}
+
+
+/*
+ * Associate arbitrary data with the secure socket.
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data(pj_ssl_sock_t *ssock,
+					      void *user_data)
+{
+    PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
+
+    ssock->param.user_data = user_data;
+    return PJ_SUCCESS;
+}
+
+
+/*
+ * Retrieve the user data previously associated with this secure
+ * socket.
+ */
+PJ_DEF(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock)
+{
+    PJ_ASSERT_RETURN(ssock, NULL);
+
+    return ssock->param.user_data;
+}
+
+
+/*
+ * Retrieve the local address and port used by specified SSL socket.
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock,
+					  pj_ssl_sock_info *info)
+{
+    pj_bzero(info, sizeof(*info));
+
+    /* Established flag */
+    info->established = (ssock->ssl_state == SSL_STATE_ESTABLISHED);
+
+    /* Protocol */
+    info->proto = ssock->param.proto;
+
+    /* Local address */
+    pj_sockaddr_cp(&info->local_addr, &ssock->local_addr);
+    
+    if (info->established) {
+	const SSL_CIPHER *cipher;
+
+	/* Current cipher */
+	cipher = SSL_get_current_cipher(ssock->ossl_ssl);
+	info->cipher = (cipher->id & 0x00FFFFFF);
+
+	/* Remote address */
+	pj_sockaddr_cp(&info->remote_addr, &ssock->rem_addr);
+
+	/* Certificates info */
+	info->local_cert_info = &ssock->local_cert_info;
+	info->remote_cert_info = &ssock->remote_cert_info;
+
+	/* Verification status */
+	info->verify_status = ssock->verify_status;
+    }
+
+    /* Last known OpenSSL error code */
+    info->last_native_err = ssock->last_err;
+
+    return PJ_SUCCESS;
+}
+
+
+/*
+ * Starts read operation on this secure socket.
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock,
+					    pj_pool_t *pool,
+					    unsigned buff_size,
+					    pj_uint32_t flags)
+{
+    void **readbuf;
+    unsigned i;
+
+    PJ_ASSERT_RETURN(ssock && pool && buff_size, PJ_EINVAL);
+    PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
+
+    readbuf = (void**) pj_pool_calloc(pool, ssock->param.async_cnt, 
+				      sizeof(void*));
+
+    for (i=0; i<ssock->param.async_cnt; ++i) {
+	readbuf[i] = pj_pool_alloc(pool, buff_size);
+    }
+
+    return pj_ssl_sock_start_read2(ssock, pool, buff_size, 
+				   readbuf, flags);
+}
+
+
+/*
+ * Same as #pj_ssl_sock_start_read(), except that the application
+ * supplies the buffers for the read operation so that the acive socket
+ * does not have to allocate the buffers.
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock,
+					     pj_pool_t *pool,
+					     unsigned buff_size,
+					     void *readbuf[],
+					     pj_uint32_t flags)
+{
+    unsigned i;
+
+    PJ_ASSERT_RETURN(ssock && pool && buff_size && readbuf, PJ_EINVAL);
+    PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
+
+    /* Create SSL socket read buffer */
+    ssock->ssock_rbuf = (read_data_t*)pj_pool_calloc(pool, 
+					       ssock->param.async_cnt,
+					       sizeof(read_data_t));
+
+    /* Store SSL socket read buffer pointer in the activesock read buffer */
+    for (i=0; i<ssock->param.async_cnt; ++i) {
+	read_data_t **p_ssock_rbuf = 
+			OFFSET_OF_READ_DATA_PTR(ssock, ssock->asock_rbuf[i]);
+
+	ssock->ssock_rbuf[i].data = readbuf[i];
+	ssock->ssock_rbuf[i].len = 0;
+
+	*p_ssock_rbuf = &ssock->ssock_rbuf[i];
+    }
+
+    ssock->read_size = buff_size;
+    ssock->read_started = PJ_TRUE;
+    ssock->read_flags = flags;
+
+    return PJ_SUCCESS;
+}
+
+
+/*
+ * Same as pj_ssl_sock_start_read(), except that this function is used
+ * only for datagram sockets, and it will trigger \a on_data_recvfrom()
+ * callback instead.
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock,
+						pj_pool_t *pool,
+						unsigned buff_size,
+						pj_uint32_t flags)
+{
+    PJ_UNUSED_ARG(ssock);
+    PJ_UNUSED_ARG(pool);
+    PJ_UNUSED_ARG(buff_size);
+    PJ_UNUSED_ARG(flags);
+
+    return PJ_ENOTSUP;
+}
+
+
+/*
+ * Same as #pj_ssl_sock_start_recvfrom() except that the recvfrom() 
+ * operation takes the buffer from the argument rather than creating
+ * new ones.
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock,
+						 pj_pool_t *pool,
+						 unsigned buff_size,
+						 void *readbuf[],
+						 pj_uint32_t flags)
+{
+    PJ_UNUSED_ARG(ssock);
+    PJ_UNUSED_ARG(pool);
+    PJ_UNUSED_ARG(buff_size);
+    PJ_UNUSED_ARG(readbuf);
+    PJ_UNUSED_ARG(flags);
+
+    return PJ_ENOTSUP;
+}
+
+/* Write plain data to SSL and flush write BIO. */
+static pj_status_t ssl_write(pj_ssl_sock_t *ssock, 
+			     pj_ioqueue_op_key_t *send_key,
+			     const void *data,
+			     pj_ssize_t size,
+			     unsigned flags)
+{
+    pj_status_t status;
+    int nwritten;
+
+    /* Write the plain data to SSL, after SSL encrypts it, write BIO will
+     * contain the secured data to be sent via socket. Note that re-
+     * negotitation may be on progress, so sending data should be delayed
+     * until re-negotiation is completed.
+     */
+    pj_lock_acquire(ssock->write_mutex);
+    nwritten = SSL_write(ssock->ossl_ssl, data, (int)size);
+    pj_lock_release(ssock->write_mutex);
+    
+    if (nwritten == size) {
+	/* All data written, flush write BIO to network socket */
+	status = flush_write_bio(ssock, send_key, size, flags);
+    } else if (nwritten <= 0) {
+	/* SSL failed to process the data, it may just that re-negotiation
+	 * is on progress.
+	 */
+	int err;
+	err = SSL_get_error(ssock->ossl_ssl, nwritten);
+	if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_NONE) {
+	    /* Re-negotiation is on progress, flush re-negotiation data */
+	    status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
+	    if (status == PJ_SUCCESS || status == PJ_EPENDING)
+		/* Just return PJ_EBUSY when re-negotiation is on progress */
+		status = PJ_EBUSY;
+	} else {
+	    /* Some problem occured */
+	    status = STATUS_FROM_SSL_ERR(ssock, err);
+	}
+    } else {
+	/* nwritten < *size, shouldn't happen, unless write BIO cannot hold 
+	 * the whole secured data, perhaps because of insufficient memory.
+	 */
+	status = PJ_ENOMEM;
+    }
+
+    return status;
+}
+
+/* Flush delayed data sending in the write pending list. */
+static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock)
+{
+    /* Check for another ongoing flush */
+    if (ssock->flushing_write_pend)
+	return PJ_EBUSY;
+
+    pj_lock_acquire(ssock->write_mutex);
+
+    /* Again, check for another ongoing flush */
+    if (ssock->flushing_write_pend) {
+	pj_lock_release(ssock->write_mutex);
+	return PJ_EBUSY;
+    }
+
+    /* Set ongoing flush flag */
+    ssock->flushing_write_pend = PJ_TRUE;
+
+    while (!pj_list_empty(&ssock->write_pending)) {
+        write_data_t *wp;
+	pj_status_t status;
+
+	wp = ssock->write_pending.next;
+
+	/* Ticket #1573: Don't hold mutex while calling socket send. */
+	pj_lock_release(ssock->write_mutex);
+
+	status = ssl_write(ssock, &wp->key, wp->data.ptr, 
+			   wp->plain_data_len, wp->flags);
+	if (status != PJ_SUCCESS) {
+	    /* Reset ongoing flush flag first. */
+	    ssock->flushing_write_pend = PJ_FALSE;
+	    return status;
+	}
+
+	pj_lock_acquire(ssock->write_mutex);
+	pj_list_erase(wp);
+	pj_list_push_back(&ssock->write_pending_empty, wp);
+    }
+
+    /* Reset ongoing flush flag */
+    ssock->flushing_write_pend = PJ_FALSE;
+
+    pj_lock_release(ssock->write_mutex);
+
+    return PJ_SUCCESS;
+}
+
+/* Sending is delayed, push back the sending data into pending list. */
+static pj_status_t delay_send (pj_ssl_sock_t *ssock,
+			       pj_ioqueue_op_key_t *send_key,
+			       const void *data,
+			       pj_ssize_t size,
+			       unsigned flags)
+{
+    write_data_t *wp;
+
+    pj_lock_acquire(ssock->write_mutex);
+
+    /* Init write pending instance */
+    if (!pj_list_empty(&ssock->write_pending_empty)) {
+	wp = ssock->write_pending_empty.next;
+	pj_list_erase(wp);
+    } else {
+	wp = PJ_POOL_ZALLOC_T(ssock->pool, write_data_t);
+    }
+
+    wp->app_key = send_key;
+    wp->plain_data_len = size;
+    wp->data.ptr = data;
+    wp->flags = flags;
+
+    pj_list_push_back(&ssock->write_pending, wp);
+    
+    pj_lock_release(ssock->write_mutex);
+
+    /* Must return PJ_EPENDING */
+    return PJ_EPENDING;
+}
+
+/**
+ * Send data using the socket.
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock,
+				      pj_ioqueue_op_key_t *send_key,
+				      const void *data,
+				      pj_ssize_t *size,
+				      unsigned flags)
+{
+    pj_status_t status;
+
+    PJ_ASSERT_RETURN(ssock && data && size && (*size>0), PJ_EINVAL);
+    PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
+
+    // Ticket #1573: Don't hold mutex while calling PJLIB socket send().
+    //pj_lock_acquire(ssock->write_mutex);
+
+    /* Flush delayed send first. Sending data might be delayed when 
+     * re-negotiation is on-progress.
+     */
+    status = flush_delayed_send(ssock);
+    if (status == PJ_EBUSY) {
+	/* Re-negotiation or flushing is on progress, delay sending */
+	status = delay_send(ssock, send_key, data, *size, flags);
+	goto on_return;
+    } else if (status != PJ_SUCCESS) {
+	goto on_return;
+    }
+
+    /* Write data to SSL */
+    status = ssl_write(ssock, send_key, data, *size, flags);
+    if (status == PJ_EBUSY) {
+	/* Re-negotiation is on progress, delay sending */
+	status = delay_send(ssock, send_key, data, *size, flags);
+    }
+
+on_return:
+    //pj_lock_release(ssock->write_mutex);
+    return status;
+}
+
+
+/**
+ * Send datagram using the socket.
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock,
+					pj_ioqueue_op_key_t *send_key,
+					const void *data,
+					pj_ssize_t *size,
+					unsigned flags,
+					const pj_sockaddr_t *addr,
+					int addr_len)
+{
+    PJ_UNUSED_ARG(ssock);
+    PJ_UNUSED_ARG(send_key);
+    PJ_UNUSED_ARG(data);
+    PJ_UNUSED_ARG(size);
+    PJ_UNUSED_ARG(flags);
+    PJ_UNUSED_ARG(addr);
+    PJ_UNUSED_ARG(addr_len);
+
+    return PJ_ENOTSUP;
+}
+
+
+/**
+ * Starts asynchronous socket accept() operations on this secure socket. 
+ */
+PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock,
+					      pj_pool_t *pool,
+					      const pj_sockaddr_t *localaddr,
+					      int addr_len)
+{
+    pj_activesock_cb asock_cb;
+    pj_activesock_cfg asock_cfg;
+    pj_status_t status;
+
+    PJ_ASSERT_RETURN(ssock && pool && localaddr && addr_len, PJ_EINVAL);
+
+    /* Create socket */
+    status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0, 
+			    &ssock->sock);
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Apply SO_REUSEADDR */
+    if (ssock->param.reuse_addr) {
+	int enabled = 1;
+	status = pj_sock_setsockopt(ssock->sock, pj_SOL_SOCKET(),
+				    pj_SO_REUSEADDR(),
+				    &enabled, sizeof(enabled));
+	if (status != PJ_SUCCESS) {
+	    PJ_PERROR(4,(ssock->pool->obj_name, status,
+		         "Warning: error applying SO_REUSEADDR"));
+	}
+    }
+
+    /* Apply QoS, if specified */
+    status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
+				&ssock->param.qos_params, 2, 
+				ssock->pool->obj_name, NULL);
+    if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
+	goto on_error;
+
+    /* Bind socket */
+    status = pj_sock_bind(ssock->sock, localaddr, addr_len);
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Start listening to the address */
+    status = pj_sock_listen(ssock->sock, PJ_SOMAXCONN);
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Create active socket */
+    pj_activesock_cfg_default(&asock_cfg);
+    asock_cfg.async_cnt = ssock->param.async_cnt;
+    asock_cfg.concurrency = ssock->param.concurrency;
+    asock_cfg.whole_data = PJ_TRUE;
+
+    pj_bzero(&asock_cb, sizeof(asock_cb));
+    asock_cb.on_accept_complete = asock_on_accept_complete;
+
+    status = pj_activesock_create(pool,
+				  ssock->sock, 
+				  ssock->param.sock_type,
+				  &asock_cfg,
+				  ssock->param.ioqueue, 
+				  &asock_cb,
+				  ssock,
+				  &ssock->asock);
+
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Start accepting */
+    status = pj_activesock_start_accept(ssock->asock, pool);
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Update local address */
+    ssock->addr_len = addr_len;
+    status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 
+				 &ssock->addr_len);
+    if (status != PJ_SUCCESS)
+	pj_sockaddr_cp(&ssock->local_addr, localaddr);
+
+    ssock->is_server = PJ_TRUE;
+
+    return PJ_SUCCESS;
+
+on_error:
+    reset_ssl_sock_state(ssock);
+    return status;
+}
+
+
+/**
+ * Starts asynchronous socket connect() operation.
+ */
+PJ_DECL(pj_status_t) pj_ssl_sock_start_connect(pj_ssl_sock_t *ssock,
+					       pj_pool_t *pool,
+					       const pj_sockaddr_t *localaddr,
+					       const pj_sockaddr_t *remaddr,
+					       int addr_len)
+{
+    pj_activesock_cb asock_cb;
+    pj_activesock_cfg asock_cfg;
+    pj_status_t status;
+
+    PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len,
+		     PJ_EINVAL);
+
+    /* Create socket */
+    status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0, 
+			    &ssock->sock);
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Apply QoS, if specified */
+    status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
+				&ssock->param.qos_params, 2, 
+				ssock->pool->obj_name, NULL);
+    if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
+	goto on_error;
+
+    /* Bind socket */
+    status = pj_sock_bind(ssock->sock, localaddr, addr_len);
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Create active socket */
+    pj_activesock_cfg_default(&asock_cfg);
+    asock_cfg.async_cnt = ssock->param.async_cnt;
+    asock_cfg.concurrency = ssock->param.concurrency;
+    asock_cfg.whole_data = PJ_TRUE;
+
+    pj_bzero(&asock_cb, sizeof(asock_cb));
+    asock_cb.on_connect_complete = asock_on_connect_complete;
+    asock_cb.on_data_read = asock_on_data_read;
+    asock_cb.on_data_sent = asock_on_data_sent;
+
+    status = pj_activesock_create(pool,
+				  ssock->sock, 
+				  ssock->param.sock_type,
+				  &asock_cfg,
+				  ssock->param.ioqueue, 
+				  &asock_cb,
+				  ssock,
+				  &ssock->asock);
+
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Save remote address */
+    pj_sockaddr_cp(&ssock->rem_addr, remaddr);
+
+    /* Start timer */
+    if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
+	ssock->param.timeout.msec != 0))
+    {
+	pj_assert(ssock->timer.id == TIMER_NONE);
+	ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
+	status = pj_timer_heap_schedule(ssock->param.timer_heap,
+					&ssock->timer,
+				        &ssock->param.timeout);
+	if (status != PJ_SUCCESS)
+	    ssock->timer.id = TIMER_NONE;
+    }
+
+    status = pj_activesock_start_connect(ssock->asock, pool, remaddr,
+					 addr_len);
+
+    if (status == PJ_SUCCESS)
+	asock_on_connect_complete(ssock->asock, PJ_SUCCESS);
+    else if (status != PJ_EPENDING)
+	goto on_error;
+
+    /* Update local address */
+    ssock->addr_len = addr_len;
+    status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
+				 &ssock->addr_len);
+    /* Note that we may not get an IP address here. This can
+     * happen for example on Windows, where getsockname()
+     * would return 0.0.0.0 if socket has just started the
+     * async connect. In this case, just leave the local
+     * address with 0.0.0.0 for now; it will be updated
+     * once the socket is established.
+     */
+
+    /* Update SSL state */
+    ssock->is_server = PJ_FALSE;
+
+    return PJ_EPENDING;
+
+on_error:
+    reset_ssl_sock_state(ssock);
+    return status;
+}
+
+
+PJ_DEF(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock)
+{
+    int ret;
+    pj_status_t status;
+
+    PJ_ASSERT_RETURN(ssock->ssl_state == SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
+
+    if (SSL_renegotiate_pending(ssock->ossl_ssl))
+	return PJ_EPENDING;
+
+    ret = SSL_renegotiate(ssock->ossl_ssl);
+    if (ret <= 0) {
+	status = GET_SSL_STATUS(ssock);
+    } else {
+	status = do_handshake(ssock);
+    }
+
+    return status;
+}
+
+#endif  /* PJ_HAS_SSL_SOCK */
+
diff --git a/jni/pjproject-android/.svn/pristine/db/db7024d2d36f07370ca25e031113bab3d3fd2d37.svn-base b/jni/pjproject-android/.svn/pristine/db/db7024d2d36f07370ca25e031113bab3d3fd2d37.svn-base
new file mode 100644
index 0000000..a4fc7e5
--- /dev/null
+++ b/jni/pjproject-android/.svn/pristine/db/db7024d2d36f07370ca25e031113bab3d3fd2d37.svn-base
@@ -0,0 +1,147 @@
+/* $Id$ */
+/* 
+ * Copyright (C) 2003-2007 Benny Prijono <benny@prijono.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
+ */
+
+/*
+ * Contributed by:
+ *  Toni < buldozer at aufbix dot org >
+ */
+
+#ifndef __PJMEDIA_MP3_PORT_H__
+#define __PJMEDIA_MP3_PORT_H__
+
+
+/**
+ * @file mp3_port.h
+ * @brief MP3 writer
+ */
+#include <pjmedia/port.h>
+
+/**
+ * @defgroup PJMEDIA_MP3_FILE_REC MP3 Audio File Writer (Recorder)
+ * @ingroup PJMEDIA_PORT
+ * @brief MP3 Audio File Writer (Recorder)
+ * @{
+ *
+ * This section describes MP3 file writer. Currently it only works on Windows
+ * using BladeEncDLL of the LAME MP3 encoder. <b>Note that the LAME_ENC.DLL 
+ * file must exist in the PATH so that the encoder can work properly.</b>
+ *
+ * The MP3 file writer is created with #pjmedia_mp3_writer_port_create() which
+ * among other things specifies the desired file name and audio properties.
+ * It then takes PCM input when #pjmedia_port_put_frame() is called and encode
+ * the PCM input into MP3 streams before writing it to the .mp3 file.
+ */
+
+
+PJ_BEGIN_DECL
+
+
+/**
+ * This structure contains encoding options that can be specified during
+ * MP3 writer port creation. Application should always zero the structure
+ * before setting some value to make sure that default options will be used.
+ */
+typedef struct pjmedia_mp3_encoder_option
+{
+    /** Specify whether variable bit rate should be used. Variable bitrate
+     *  would normally produce better quality at the expense of probably
+     *  larger file.
+     */
+    pj_bool_t	vbr;
+
+    /** Target bitrate, in bps. If VBR is enabled, this settings specifies 
+     *  the  average bit-rate requested, and will make the encoder ignore 
+     *  the quality setting. For CBR, this specifies the actual bitrate,
+     *  and if this option is zero, it will be set to the sampling rate
+     *  multiplied by number of channels.
+     */
+    unsigned	bit_rate;
+
+    /** Encoding quality, 0-9, with 0 is the highest quality. For VBR, the 
+     *  quality setting will only take effect when bit_rate setting is zero.
+     */
+    unsigned	quality;
+
+} pjmedia_mp3_encoder_option;
+
+
+/**
+ * Create a media port to record PCM media to a MP3 file. After the port
+ * is created, application can call #pjmedia_port_put_frame() to feed the
+ * port with PCM frames. The port then will encode the PCM frame into MP3
+ * stream, and store it to MP3 file specified in the argument.
+ *
+ * When application has finished with writing MP3 file, it must destroy the
+ * media port with #pjmedia_port_destroy() so that the MP3 file can be
+ * closed properly.
+ *
+ * @param pool		    Pool to create memory buffers for this port.
+ * @param filename	    File name.
+ * @param clock_rate	    The sampling rate.
+ * @param channel_count	    Number of channels.
+ * @param samples_per_frame Number of samples per frame.
+ * @param bits_per_sample   Number of bits per sample (eg 16).
+ * @param option	    Optional option to set encoding parameters.
+ * @param p_port	    Pointer to receive the file port instance.
+ *
+ * @return		    PJ_SUCCESS on success.
+ */
+PJ_DECL(pj_status_t) 
+pjmedia_mp3_writer_port_create(pj_pool_t *pool,
+			       const char *filename,
+			       unsigned clock_rate,
+			       unsigned channel_count,
+			       unsigned samples_per_frame,
+			       unsigned bits_per_sample,
+			       const pjmedia_mp3_encoder_option *option,
+			       pjmedia_port **p_port );
+
+/**
+ * Register the callback to be called when the file writing has reached
+ * certain size. Application can use this callback, for example, to limit
+ * the size of the output file.
+ *
+ * @param port		The file writer port.
+ * @param pos		The file position on which the callback will be called.
+ * @param user_data	User data to be specified in the callback, and will be
+ *			given on the callback.
+ * @param cb		Callback to be called. If the callback returns non-
+ *			PJ_SUCCESS, the writing will stop. Note that if 
+ *			application destroys the port in the callback, it must
+ *			return non-PJ_SUCCESS here.
+ *
+ * @return		PJ_SUCCESS on success.
+ */
+PJ_DECL(pj_status_t) 
+pjmedia_mp3_writer_port_set_cb( pjmedia_port *port,
+				pj_size_t pos,
+				void *user_data,
+				pj_status_t (*cb)(pjmedia_port *port,
+							void *usr_data));
+
+
+/**
+ * @}
+ */
+
+
+PJ_END_DECL
+
+#endif	/* __PJMEDIA_MP3_PORT_H__ */
+
diff --git a/jni/pjproject-android/.svn/pristine/db/dbaa2fa6b861819f3e600c399e1553908dd54cc6.svn-base b/jni/pjproject-android/.svn/pristine/db/dbaa2fa6b861819f3e600c399e1553908dd54cc6.svn-base
new file mode 100644
index 0000000..f74b126
--- /dev/null
+++ b/jni/pjproject-android/.svn/pristine/db/dbaa2fa6b861819f3e600c399e1553908dd54cc6.svn-base
@@ -0,0 +1,208 @@
+/* $Id$ */
+/*
+ * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+#include <pjmedia/converter.h>
+#include <pj/errno.h>
+
+#if PJMEDIA_HAS_LIBSWSCALE && PJMEDIA_HAS_LIBAVUTIL
+
+#include "ffmpeg_util.h"
+#include <libswscale/swscale.h>
+
+static pj_status_t factory_create_converter(pjmedia_converter_factory *cf,
+					    pj_pool_t *pool,
+					    const pjmedia_conversion_param*prm,
+					    pjmedia_converter **p_cv);
+static void factory_destroy_factory(pjmedia_converter_factory *cf);
+static pj_status_t libswscale_conv_convert(pjmedia_converter *converter,
+					   pjmedia_frame *src_frame,
+					   pjmedia_frame *dst_frame);
+static void libswscale_conv_destroy(pjmedia_converter *converter);
+
+
+struct fmt_info
+{
+    const pjmedia_video_format_info 	*fmt_info;
+    pjmedia_video_apply_fmt_param 	 apply_param;
+};
+
+struct ffmpeg_converter
+{
+    pjmedia_converter 			 base;
+    struct SwsContext 			*sws_ctx;
+    struct fmt_info			 src,
+					 dst;
+};
+
+static pjmedia_converter_factory_op libswscale_factory_op =
+{
+    &factory_create_converter,
+    &factory_destroy_factory
+};
+
+static pjmedia_converter_op liswscale_converter_op =
+{
+    &libswscale_conv_convert,
+    &libswscale_conv_destroy
+};
+
+static pj_status_t factory_create_converter(pjmedia_converter_factory *cf,
+					    pj_pool_t *pool,
+					    const pjmedia_conversion_param *prm,
+					    pjmedia_converter **p_cv)
+{
+    enum PixelFormat srcFormat, dstFormat;
+    const pjmedia_video_format_detail *src_detail, *dst_detail;
+    const pjmedia_video_format_info *src_fmt_info, *dst_fmt_info;
+    struct SwsContext *sws_ctx;
+    struct ffmpeg_converter *fcv;
+    pj_status_t status;
+
+    PJ_UNUSED_ARG(cf);
+
+    /* Only supports video */
+    if (prm->src.type != PJMEDIA_TYPE_VIDEO ||
+	prm->dst.type != prm->src.type ||
+	prm->src.detail_type != PJMEDIA_FORMAT_DETAIL_VIDEO ||
+	prm->dst.detail_type != prm->src.detail_type)
+    {
+	return PJ_ENOTSUP;
+    }
+
+    /* lookup source format info */
+    src_fmt_info = pjmedia_get_video_format_info(
+		      pjmedia_video_format_mgr_instance(),
+		      prm->src.id);
+    if (!src_fmt_info)
+	return PJ_ENOTSUP;
+
+    /* lookup destination format info */
+    dst_fmt_info = pjmedia_get_video_format_info(
+		      pjmedia_video_format_mgr_instance(),
+		      prm->dst.id);
+    if (!dst_fmt_info)
+	return PJ_ENOTSUP;
+
+    src_detail = pjmedia_format_get_video_format_detail(&prm->src, PJ_TRUE);
+    dst_detail = pjmedia_format_get_video_format_detail(&prm->dst, PJ_TRUE);
+
+    status = pjmedia_format_id_to_PixelFormat(prm->src.id, &srcFormat);
+    if (status != PJ_SUCCESS)
+	return PJ_ENOTSUP;
+
+    status = pjmedia_format_id_to_PixelFormat(prm->dst.id, &dstFormat);
+    if (status != PJ_SUCCESS)
+	return PJ_ENOTSUP;
+
+    sws_ctx = sws_getContext(src_detail->size.w, src_detail->size.h, srcFormat,
+		             dst_detail->size.w, dst_detail->size.h, dstFormat,
+			     SWS_BICUBIC,
+			     NULL, NULL, NULL);
+    if (sws_ctx == NULL)
+	return PJ_ENOTSUP;
+
+    fcv = PJ_POOL_ZALLOC_T(pool, struct ffmpeg_converter);
+    fcv->base.op = &liswscale_converter_op;
+    fcv->sws_ctx = sws_ctx;
+    fcv->src.apply_param.size = src_detail->size;
+    fcv->src.fmt_info = src_fmt_info;
+    fcv->dst.apply_param.size = dst_detail->size;
+    fcv->dst.fmt_info = dst_fmt_info;
+
+    *p_cv = &fcv->base;
+
+    return PJ_SUCCESS;
+}
+
+static void factory_destroy_factory(pjmedia_converter_factory *cf)
+{
+    PJ_UNUSED_ARG(cf);
+}
+
+static pj_status_t libswscale_conv_convert(pjmedia_converter *converter,
+					   pjmedia_frame *src_frame,
+					   pjmedia_frame *dst_frame)
+{
+    struct ffmpeg_converter *fcv = (struct ffmpeg_converter*)converter;
+    struct fmt_info *src = &fcv->src,
+	            *dst = &fcv->dst;
+    int h;
+
+    src->apply_param.buffer = src_frame->buf;
+    (*src->fmt_info->apply_fmt)(src->fmt_info, &src->apply_param);
+
+    dst->apply_param.buffer = dst_frame->buf;
+    (*dst->fmt_info->apply_fmt)(dst->fmt_info, &dst->apply_param);
+
+    h = sws_scale(fcv->sws_ctx,
+	          (const uint8_t* const *)src->apply_param.planes,
+	          src->apply_param.strides,
+		  0, src->apply_param.size.h,
+		  dst->apply_param.planes, dst->apply_param.strides);
+
+    //sws_scale() return value can't be trusted? There are cases when
+    //sws_scale() returns zero but conversion seems to work okay.
+    //return h==(int)dst->apply_param.size.h ? PJ_SUCCESS : PJ_EUNKNOWN;
+    PJ_UNUSED_ARG(h);
+
+    return PJ_SUCCESS;
+}
+
+static void libswscale_conv_destroy(pjmedia_converter *converter)
+{
+    struct ffmpeg_converter *fcv = (struct ffmpeg_converter*)converter;
+    if (fcv->sws_ctx) {
+	struct SwsContext *tmp = fcv->sws_ctx;
+	fcv->sws_ctx = NULL;
+	sws_freeContext(tmp);
+    }
+}
+
+static pjmedia_converter_factory libswscale_factory =
+{
+    NULL, NULL,					/* list */
+    "libswscale",				/* name */
+    PJMEDIA_CONVERTER_PRIORITY_NORMAL+1,	/* priority */
+    NULL					/* op will be init-ed later  */
+};
+
+PJ_DEF(pj_status_t)
+pjmedia_libswscale_converter_init(pjmedia_converter_mgr *mgr)
+{
+    libswscale_factory.op = &libswscale_factory_op;
+    pjmedia_ffmpeg_add_ref();
+    return pjmedia_converter_mgr_register_factory(mgr, &libswscale_factory);
+}
+
+
+PJ_DEF(pj_status_t)
+pjmedia_libswscale_converter_shutdown(pjmedia_converter_mgr *mgr,
+				      pj_pool_t *pool)
+{
+    PJ_UNUSED_ARG(pool);
+    pjmedia_ffmpeg_dec_ref();
+    return pjmedia_converter_mgr_unregister_factory(mgr, &libswscale_factory,
+						    PJ_TRUE);
+}
+
+#ifdef _MSC_VER
+#   pragma comment( lib, "avutil.lib")
+#   pragma comment( lib, "swscale.lib")
+#endif
+
+#endif /* #if PJMEDIA_HAS_LIBSWSCALE && PJMEDIA_HAS_LIBAVUTIL */