Ejemplo n.º 1
0
  /** Process the invite request. */
  public void processInvite(RequestEvent requestEvent, ServerTransaction serverTransaction) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    try {
      System.out.println("b2bua: got an Invite sending Trying");
      ServerTransaction st = requestEvent.getServerTransaction();
      if (st == null) {
        st = sipProvider.getNewServerTransaction(request);
      }
      Dialog dialog = st.getDialog();

      ToHeader to = (ToHeader) request.getHeader(ToHeader.NAME);
      SipURI toUri = (SipURI) to.getAddress().getURI();

      SipURI target = registrar.get(toUri.getUser());

      if (target == null) {
        System.out.println("User " + toUri + " is not registered.");
        throw new RuntimeException("User not registered " + toUri);
      } else {
        ClientTransaction otherLeg = call(target);
        otherLeg.setApplicationData(st);
        st.setApplicationData(otherLeg);
        dialog.setApplicationData(otherLeg.getDialog());
        otherLeg.getDialog().setApplicationData(dialog);
      }

    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
Ejemplo n.º 2
0
 /** JAIN Listener method. */
 public void processTimeout(TimeoutEvent timeOutEvent) {
   ProxyDebug.println("TimeoutEvent received");
   SipProvider sipProvider = (SipProvider) timeOutEvent.getSource();
   TransactionsMapping transactionsMapping = null;
   if (timeOutEvent.isServerTransaction()) {
     ServerTransaction serverTransaction = timeOutEvent.getServerTransaction();
     Dialog dialog = serverTransaction.getDialog();
     if (dialog != null) {
       transactionsMapping = (TransactionsMapping) dialog.getApplicationData();
       transactionsMapping.removeMapping(serverTransaction);
     }
   } else {
     ClientTransaction clientTransaction = timeOutEvent.getClientTransaction();
     Dialog dialog = clientTransaction.getDialog();
     ServerTransaction st = null;
     if (dialog != null) {
       transactionsMapping = (TransactionsMapping) dialog.getApplicationData();
       if (transactionsMapping != null) {
         st = transactionsMapping.getServerTransaction(clientTransaction);
       }
       if (st == null) {
         ProxyDebug.println(
             "ERROR, Unable to retrieve the server transaction," + " cannot process timeout!");
         return;
       }
     } else {
       ProxyDebug.println(
           "ERROR, Unable to retrieve the transaction Mapping," + " cannot process timeout!");
       return;
     }
     Request request = st.getRequest();
     // This removes the given mapping from the table but not
     // necessarily the whole thing.
     transactionsMapping.removeMapping(clientTransaction);
     if (!transactionsMapping.hasMapping(st)) {
       // No more mappings left in the transaction table.
       try {
         Response response = messageFactory.createResponse(Response.REQUEST_TIMEOUT, request);
         st.sendResponse(response);
       } catch (ParseException ex) {
         ex.printStackTrace();
       } catch (SipException ex1) {
         ex1.printStackTrace();
       }
     }
   }
 }
  public void processOK(Response responseCloned, ClientTransaction clientTransaction) {
    DebugIM.println("Processing OK for MESSAGE in progress...");

    if (clientTransaction == null) {
      // This could occur if this is a retransmission of the OK.
      DebugIM.println("ERROR, IMProcessing, processOK(), the transaction is null");
      return;
    }

    InstantMessagingGUI instantMessagingGUI = imUA.getInstantMessagingGUI();
    ListenerInstantMessaging listenerInstantMessaging =
        instantMessagingGUI.getListenerInstantMessaging();
    ChatSessionManager chatSessionManager = listenerInstantMessaging.getChatSessionManager();
    ChatSession chatSession = null;

    Dialog dialog = clientTransaction.getDialog();
    if (dialog == null) {
      DebugIM.println("ERROR, IMProcessing, processOK(), the dialog is null");
      return;
    }

    String fromURL = IMUtilities.getKey(responseCloned, "To");
    if (chatSessionManager.hasAlreadyChatSession(fromURL)) {
      chatSession = chatSessionManager.getChatSession(fromURL);
      chatSession.displayLocalText();
      // WE remove the text typed:
      chatSession.removeSentText();

      if (chatSession.isEstablishedSession()) {
      } else {
        DebugIM.println("DEBUG, IMMessageProcessing, we mark the " + " session established");
        chatSession.setDialog(dialog);
        chatSession.setEstablishedSession(true);
      }
    } else {
      // This is a bug!!!
      DebugIM.println("Error: IMMessageProcessing, processOK(), the chatSession is null");
    }
    DebugIM.println("Processing OK for MESSAGE completed...");
  }
Ejemplo n.º 4
0
 /** Test whether new ClientTransactions are properly created. */
 public void testGetNewClientTransaction() {
   try {
     Request invite = createTiInviteRequest(null, null, null);
     ClientTransaction tran = null;
     try {
       tran = tiSipProvider.getNewClientTransaction(invite);
     } catch (TransactionUnavailableException exc) {
       exc.printStackTrace();
       fail(
           "A TransactionUnavailableException was thrown while trying to "
               + "create a new client transaction");
     }
     assertNotNull(
         "A null ClientTransaction was returned by SipProvider." + "getNewClientTransaction().",
         tran);
     String tranBranch = tran.getBranchId();
     String reqBranch = ((ViaHeader) invite.getHeader(ViaHeader.NAME)).getBranch();
     assertEquals(
         "The newly created transaction did not have the same "
             + "branch id as the request that created it",
         tranBranch,
         reqBranch);
     assertNotNull(
         "The newly created transaction returned a null Dialog. "
             + "Please check the docs on Transaction.getDialog()",
         tran.getDialog());
     assertNotNull(
         "The transaction's getRequest() method returned a null Request ", tran.getRequest());
     assertEquals(
         "The transaction's getRequest() method returned a Request "
             + "that did not match the one that we used to create it!",
         tran.getRequest(),
         invite);
   } catch (Throwable exc) {
     exc.printStackTrace();
     fail(exc.getClass().getName() + ": " + exc.getMessage());
   }
   assertTrue(new Exception().getStackTrace()[0].toString(), true);
 }
  public void processOK(Response responseCloned, ClientTransaction clientTransaction) {
    try {
      logger.debug("Processing OK for SUBSCRIBE in progress...");

      ExpiresHeader expiresHeader = (ExpiresHeader) responseCloned.getHeader(ExpiresHeader.NAME);
      if (expiresHeader != null && expiresHeader.getExpires() == 0) {
        logger.debug(
            "DEBUG, IMSubscribeProcessing, processOK(), we got" + " the OK for the unsubscribe...");
      } else {

        // We have to create or update the presentity!
        PresenceManager presenceManager = imUA.getPresenceManager();
        String presentityURL = IMUtilities.getKey(responseCloned, "To");

        Dialog dialog = clientTransaction.getDialog();
        if (dialog != null) presenceManager.addPresentity(presentityURL, responseCloned, dialog);
        else {
          logger.debug(
              "ERROR, IMSubscribeProcessing, processOK(), the"
                  + " dialog for the SUBSCRIBE we sent is null!!!"
                  + " No presentity added....");
        }

        // WE have to create a new Buddy in the GUI!!!
        InstantMessagingGUI imGUI = imUA.getInstantMessagingGUI();
        BuddyList buddyList = imGUI.getBuddyList();
        if (!buddyList.hasBuddy(presentityURL)) {
          buddyList.addBuddy(presentityURL, "offline");
        } else {
          logger.debug("The buddy is already in the Buddy list...");
        }
      }
      logger.debug("Processing OK for SUBSCRIBE completed...");
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
    public void init() {
      SipFactory sipFactory = null;
      sipStack = null;
      sipFactory = SipFactory.getInstance();
      sipFactory.setPathName("gov.nist");
      Properties properties = new Properties();
      // If you want to try TCP transport change the following to
      String transport = "udp";
      String peerHostPort = "127.0.0.1:5070";
      properties.setProperty("javax.sip.OUTBOUND_PROXY", peerHostPort + "/" + transport);
      // If you want to use UDP then uncomment this.
      properties.setProperty("javax.sip.STACK_NAME", "shootist");

      // The following properties are specific to nist-sip
      // and are not necessarily part of any other jain-sip
      // implementation.
      // You can set a max message size for tcp transport to
      // guard against denial of service attack.
      properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "shootistdebug.txt");
      properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "shootistlog.txt");

      // Drop the client connection after we are done with the transaction.
      properties.setProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS", "false");
      // Set to 0 (or NONE) in your production code for max speed.
      // You need 16 (or TRACE) for logging traces. 32 (or DEBUG) for debug + traces.
      // Your code will limp at 32 but it is best for debugging.
      properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "DEBUG");
      if (System.getProperty("enableNIO") != null
          && System.getProperty("enableNIO").equalsIgnoreCase("true")) {
        properties.setProperty(
            "gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY",
            NioMessageProcessorFactory.class.getName());
      }
      try {
        // Create SipStack object
        sipStack = sipFactory.createSipStack(properties);
        System.out.println("createSipStack " + sipStack);
      } catch (PeerUnavailableException e) {
        // could not find
        // gov.nist.jain.protocol.ip.sip.SipStackImpl
        // in the classpath
        e.printStackTrace();
        System.err.println(e.getMessage());
        fail("Problem with setup");
      }

      try {
        headerFactory = sipFactory.createHeaderFactory();
        addressFactory = sipFactory.createAddressFactory();
        messageFactory = sipFactory.createMessageFactory();
        udpListeningPoint = sipStack.createListeningPoint("127.0.0.1", 5060, "udp");
        sipProvider = sipStack.createSipProvider(udpListeningPoint);
        Shootist listener = this;
        sipProvider.addSipListener(listener);

        String fromName = "BigGuy";
        String fromSipAddress = "here.com";
        String fromDisplayName = "The Master Blaster";

        String toSipAddress = "there.com";
        String toUser = "******";
        String toDisplayName = "The Little Blister";

        // create >From Header
        SipURI fromAddress = addressFactory.createSipURI(fromName, fromSipAddress);

        Address fromNameAddress = addressFactory.createAddress(fromAddress);
        fromNameAddress.setDisplayName(fromDisplayName);
        FromHeader fromHeader = headerFactory.createFromHeader(fromNameAddress, "12345");

        // create To Header
        SipURI toAddress = addressFactory.createSipURI(toUser, toSipAddress);
        Address toNameAddress = addressFactory.createAddress(toAddress);
        toNameAddress.setDisplayName(toDisplayName);
        ToHeader toHeader = headerFactory.createToHeader(toNameAddress, null);

        // create Request URI
        SipURI requestURI = addressFactory.createSipURI(toUser, peerHostPort);

        // Create ViaHeaders

        ArrayList viaHeaders = new ArrayList();
        String ipAddress = udpListeningPoint.getIPAddress();
        ViaHeader viaHeader =
            headerFactory.createViaHeader(
                ipAddress, sipProvider.getListeningPoint(transport).getPort(), transport, null);

        // add via headers
        viaHeaders.add(viaHeader);

        // Create ContentTypeHeader
        ContentTypeHeader contentTypeHeader =
            headerFactory.createContentTypeHeader("application", "sdp");

        // Create a new CallId header
        CallIdHeader callIdHeader = sipProvider.getNewCallId();

        // Create a new Cseq header
        CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L, Request.INVITE);

        // Create a new MaxForwardsHeader
        MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70);

        // Create the request.
        Request request =
            messageFactory.createRequest(
                requestURI,
                Request.INVITE,
                callIdHeader,
                cSeqHeader,
                fromHeader,
                toHeader,
                viaHeaders,
                maxForwards);
        // Create contact headers
        String host = "127.0.0.1";

        SipURI contactUrl = addressFactory.createSipURI(fromName, host);
        contactUrl.setPort(udpListeningPoint.getPort());
        contactUrl.setLrParam();

        // Create the contact name address.
        SipURI contactURI = addressFactory.createSipURI(fromName, host);
        contactURI.setPort(sipProvider.getListeningPoint(transport).getPort());

        Address contactAddress = addressFactory.createAddress(contactURI);

        // Add the contact address.
        contactAddress.setDisplayName(fromName);

        contactHeader = headerFactory.createContactHeader(contactAddress);
        request.addHeader(contactHeader);

        // You can add extension headers of your own making
        // to the outgoing SIP request.
        // Add the extension header.
        Header extensionHeader = headerFactory.createHeader("My-Header", "my header value");
        request.addHeader(extensionHeader);

        String sdpData =
            "v=0\r\n"
                + "o=4855 13760799956958020 13760799956958020"
                + " IN IP4  129.6.55.78\r\n"
                + "s=mysession session\r\n"
                + "p=+46 8 52018010\r\n"
                + "c=IN IP4  129.6.55.78\r\n"
                + "t=0 0\r\n"
                + "m=audio 6022 RTP/AVP 0 4 18\r\n"
                + "a=rtpmap:0 PCMU/8000\r\n"
                + "a=rtpmap:4 G723/8000\r\n"
                + "a=rtpmap:18 G729A/8000\r\n"
                + "a=ptime:20\r\n";
        byte[] contents = sdpData.getBytes();

        request.setContent(contents, contentTypeHeader);
        // You can add as many extension headers as you
        // want.

        extensionHeader = headerFactory.createHeader("My-Other-Header", "my new header value ");
        request.addHeader(extensionHeader);

        Header callInfoHeader =
            headerFactory.createHeader("Call-Info", "<http://www.antd.nist.gov>");
        request.addHeader(callInfoHeader);

        // Create the client transaction.
        ClientTransaction inviteTid = sipProvider.getNewClientTransaction(request);

        // send the request out.
        inviteTid.sendRequest();

        dialog = inviteTid.getDialog();

      } catch (Exception ex) {
        fail("cannot create or send initial invite");
      }
    }
  public void processResponse(ResponseEvent responseReceivedEvent) {
    /// System.out.println("=> BUNDLE: br.ufes.inf.ngn.televoto.client.logic | CLASS: LogicListener
    // | METOD: processResponse ");//By Ju
    try {
      Response myResponse = responseReceivedEvent.getResponse();
      logger.info("<<< " + myResponse.toString());

      ClientTransaction thisClientTransaction = responseReceivedEvent.getClientTransaction();

      int myStatusCode = myResponse.getStatusCode();

      switch (status) {
        case WAIT_PROV:
          if (!thisClientTransaction.equals(myClientTransaction))
            myClientTransaction = thisClientTransaction;

          if (myStatusCode < 200) {
            status = WAIT_FINAL;
            myDialog = thisClientTransaction.getDialog();
          } else if (myStatusCode < 300) {
            myDialog = thisClientTransaction.getDialog();
            CSeqHeader originalCSeq =
                (CSeqHeader) myClientTransaction.getRequest().getHeader(CSeqHeader.NAME);
            long numseq = originalCSeq.getSeqNumber();
            Request myAck = myDialog.createAck(numseq);
            myAck.addHeader(myContactHeader);
            myDialog.sendAck(myAck);
            // logger.info(">>> "+myAck.toString());
            status = ESTABLISHED;
            byte[] cont = (byte[]) myResponse.getContent();
            answerInfo = mySdpManager.getSdp(cont);

          } else {
            if (myStatusCode == 401) {

            } else {
              status = IDLE;
              CSeqHeader originalCSeq =
                  (CSeqHeader) myClientTransaction.getRequest().getHeader(CSeqHeader.NAME);
              long numseq = originalCSeq.getSeqNumber();
              Request myAck = myDialog.createAck(numseq);
              myAck.addHeader(myContactHeader);
              myDialog.sendAck(myAck);
              // logger.info(">>> "+myAck.toString());
            }
          }
          break;

        case WAIT_FINAL:
          if (!thisClientTransaction.equals(myClientTransaction))
            myClientTransaction = thisClientTransaction;

          if (myStatusCode < 200) {
            status = WAIT_FINAL;
            myDialog = thisClientTransaction.getDialog();
          } else if (myStatusCode < 300) {
            if (useQueue.equals("yes")) {
              status = IDLE;
            } else {
              status = ESTABLISHED;
            }

            myDialog = thisClientTransaction.getDialog();
            CSeqHeader originalCSeq =
                (CSeqHeader) myClientTransaction.getRequest().getHeader(CSeqHeader.NAME);
            long numseq = originalCSeq.getSeqNumber();
            Request myAck = myDialog.createAck(numseq); // Aquiiii
            myAck.addHeader(myContactHeader);
            myDialog.sendAck(myAck);
            // logger.info(">>> "+myAck.toString());
            byte[] cont = (byte[]) myResponse.getContent();
            answerInfo = mySdpManager.getSdp(cont);

          } else {
            // Cancelando requisição ao cliente
            Request myCancelRequest = myClientTransaction.createCancel();
            ClientTransaction myCancelClientTransaction =
                mySipProvider.getNewClientTransaction(myCancelRequest);
            myCancelClientTransaction.sendRequest();
            // logger.info(">>> " + myCancelRequest.toString());
            status = IDLE;
          }
          break;

        case REGISTERING:
          if (!thisClientTransaction.equals(myClientTransaction))
            myClientTransaction = thisClientTransaction;

          if (myStatusCode == 200) {
            status = IDLE;
            if (!Unregistring) {

              System.out.println(myName + ": Registrado");

              // inserir captura de timestamp
              // logger.info(myName + ";INVITE;" +  getTime());
              // Random gerador = new Random();
              // int temp = gerador.nextInt(10);
              // System.out.println(myName + ": Esperando " + temp + "segundos");
              // Thread.sleep(temp);

              System.out.println(myName + ": chamando " + destination);

              SdpInfo offerInfo = new SdpInfo();
              offerInfo.IpAddress = myIP;
              offerInfo.aport = myAudioPort;
              offerInfo.aformat = 0;
              byte[] content = mySdpManager.createSdp(offerInfo);

              // Via
              // ViaHeader comentei
              myViaHeader = myHeaderFactory.createViaHeader(myIP, myPort, "udp", null);
              myViaHeader.setRPort();
              ArrayList viaHeaders = new ArrayList();
              viaHeaders.add(myViaHeader);

              // From
              Address addressOfRecord = myAddressFactory.createAddress("<sip:" + myUserID + ">");
              FromHeader myFromHeader = myHeaderFactory.createFromHeader(addressOfRecord, "456249");

              // To
              String dstURI[] = destination.split("@");
              String dstSipAlias = dstURI[0];
              Address destinationAddress =
                  myAddressFactory.createAddress("<sip:" + destination + ">");
              javax.sip.address.URI myRequestURI = destinationAddress.getURI();
              ToHeader myToHeader = myHeaderFactory.createToHeader(destinationAddress, null);

              // MaxForwards
              MaxForwardsHeader myMaxForwardsHeader = myHeaderFactory.createMaxForwardsHeader(70);

              // Call-ID
              CallIdHeader myCallIdHeader = mySipProvider.getNewCallId();

              // CSeq
              Random random = new Random();
              CSeqHeader myCSeqHeader =
                  myHeaderFactory.createCSeqHeader(random.nextInt(1000) * 1L, "INVITE");

              // Create SIP request
              Request myRequest =
                  myMessageFactory.createRequest(
                      myRequestURI,
                      "INVITE",
                      myCallIdHeader,
                      myCSeqHeader,
                      myFromHeader,
                      myToHeader,
                      viaHeaders,
                      myMaxForwardsHeader);

              // Contact
              Address contactAddress =
                  myAddressFactory.createAddress(
                      "<sip:" + mySipAlias + "@" + myIP + ":" + myPort + ";transport=udp>");
              myContactHeader = myHeaderFactory.createContactHeader(contactAddress);
              myRequest.addHeader(myContactHeader);

              // Allow
              Allow myAllow = new Allow();
              myAllow.setMethod(
                  "INVITE, ACK, CANCEL, BYE, MESSAGE, OPTIONS, NOTIFY, PRACK, UPDATE, REFER");
              myRequest.addHeader(myAllow);

              // Privacy
              Privacy myPrivacy = new Privacy("none");
              myRequest.addHeader(myPrivacy);

              // PPreferredIdentity
              HeaderFactoryImpl myHeaderFactoryImpl = new HeaderFactoryImpl();
              PPreferredIdentityHeader myPPreferredIdentityHeader =
                  myHeaderFactoryImpl.createPPreferredIdentityHeader(
                      myAddressFactory.createAddress("sip:" + myName + '@' + myServer));
              myRequest.addHeader(myPPreferredIdentityHeader);

              // Route
              Address routeAddress =
                  myAddressFactory.createAddress("sip:orig@scscf." + myServer + ":6060;lr");
              // RouteHeader comentei
              myRouteHeader = myHeaderFactory.createRouteHeader(routeAddress);
              myRequest.addHeader(myRouteHeader);

              // Para proxy funcionar
              SipURI outboundProxyURI = myAddressFactory.createSipURI("proxy", myProxyIP);
              outboundProxyURI.setLrParam();
              outboundProxyURI.setPort(myProxyPort);
              myRouteHeader =
                  myHeaderFactory.createRouteHeader(
                      myAddressFactory.createAddress(outboundProxyURI));
              myRequest.addFirst(myRouteHeader);

              // Content Type
              ContentTypeHeader contentTypeHeader =
                  myHeaderFactory.createContentTypeHeader("application", "sdp");
              myRequest.setContent(content, contentTypeHeader);

              // ClientTransaction comentei aqui
              myClientTransaction = mySipProvider.getNewClientTransaction(myRequest);
              myClientTransaction.setRetransmitTimer(700);
              myClientTransaction.sendRequest();

              status = WAIT_PROV;

              logger.info(">>> " + myRequest.toString());

            } else {
              this.setOff(mySipStack);
            }
          } else {
            if (myStatusCode == 403) {

              System.out.println("Problemas com credenciais!!!!\n");
            } else if (myStatusCode == 401) {

              myName = (String) this.getLocalName();
              myUserID = (String) this.getLocalName() + "@" + myServer;

              Address contactAddress =
                  myAddressFactory.createAddress("sip:" + myName + '@' + myIP + ":" + myPort);
              myContactHeader = myHeaderFactory.createContactHeader(contactAddress);

              myViaHeader = myHeaderFactory.createViaHeader(myIP, myPort, "udp", null);

              fromAddress = myAddressFactory.createAddress(myName + " <sip:" + myUserID + ">");

              Address registrarAddress = myAddressFactory.createAddress("sip:" + myServer);
              Address registerToAddress = fromAddress;
              Address registerFromAddress = fromAddress;

              ToHeader myToHeader = myHeaderFactory.createToHeader(registerToAddress, null);
              FromHeader myFromHeader =
                  myHeaderFactory.createFromHeader(registerFromAddress, "647554");

              ArrayList myViaHeaders = new ArrayList();
              myViaHeaders.add(myViaHeader);

              // System.out.println("myClientTransaction.getRequest():"+
              // myClientTransaction.getRequest());
              CSeqHeader originalCSeq =
                  (CSeqHeader) myClientTransaction.getRequest().getHeader(CSeqHeader.NAME);
              long numseq = originalCSeq.getSeqNumber();
              MaxForwardsHeader myMaxForwardsHeader = myHeaderFactory.createMaxForwardsHeader(70);
              CSeqHeader myCSeqHeader = myHeaderFactory.createCSeqHeader(numseq + 1L, "REGISTER");

              CallIdHeader myCallID =
                  (CallIdHeader) myClientTransaction.getRequest().getHeader(CallIdHeader.NAME);
              CallIdHeader myCallIDHeader = myCallID;
              SipURI myRequestURI = (SipURI) registrarAddress.getURI();
              Request myRegisterRequest =
                  myMessageFactory.createRequest(
                      myRequestURI,
                      "REGISTER",
                      myCallIDHeader,
                      myCSeqHeader,
                      myFromHeader,
                      myToHeader,
                      myViaHeaders,
                      myMaxForwardsHeader);
              myRegisterRequest.addHeader(myContactHeader);

              // Expires
              ExpiresHeader myExpiresHeader;
              if (Unregistring) {
                myExpiresHeader = myHeaderFactory.createExpiresHeader(0);
                myContactHeader.setExpires(0);
              } else {
                myExpiresHeader = myHeaderFactory.createExpiresHeader(60000);
              }
              myRegisterRequest.addHeader(myExpiresHeader);

              // Allow
              Allow myAllow = new Allow();
              myAllow.setMethod(
                  "INVITE, ACK, CANCEL, BYE, MESSAGE, OPTIONS, NOTIFY, PRACK, UPDATE, REFER");
              myRegisterRequest.addHeader(myAllow);

              // Privacy
              Privacy myPrivacy = new Privacy("none");
              myRegisterRequest.addHeader(myPrivacy);

              // PPreferredIdentity
              HeaderFactoryImpl myHeaderFactoryImpl = new HeaderFactoryImpl();
              PPreferredIdentityHeader myPPreferredIdentityHeader =
                  myHeaderFactoryImpl.createPPreferredIdentityHeader(
                      myAddressFactory.createAddress("sip:" + myName + '@' + myServer));
              myRegisterRequest.addHeader(myPPreferredIdentityHeader);

              // Supported
              Supported mySupported = new Supported("path");
              myRegisterRequest.addHeader(mySupported);

              myWWWAuthenticateHeader =
                  Utils.makeAuthHeader(
                      myHeaderFactory, myResponse, myRegisterRequest, myUserID, myPassword);
              myRegisterRequest.addHeader(myWWWAuthenticateHeader);

              myClientTransaction = mySipProvider.getNewClientTransaction(myRegisterRequest);
              myClientTransaction.sendRequest();

              // logger.info(">>> "+myRegisterRequest.toString());
              // System.out.println(">>> " + myRegisterRequest.toString());
              status = REGISTERING;
            }
          }
          break;
      }
    } catch (Exception excep) {
      excep.printStackTrace();
    }
  }
    public void processResponse(ResponseEvent responseReceivedEvent) {
      System.out.println("Got a response");
      Response response = (Response) responseReceivedEvent.getResponse();
      ClientTransaction tid = responseReceivedEvent.getClientTransaction();
      CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME);

      System.out.println(
          "Response received : Status Code = " + response.getStatusCode() + " " + cseq);

      if (tid == null) {

        // RFC3261: MUST respond to every 2xx
        if (ackRequest != null && dialog != null) {
          System.out.println("re-sending ACK");
          try {
            dialog.sendAck(ackRequest);
          } catch (SipException se) {
            se.printStackTrace();
            fail("Unxpected exception ");
          }
        }
        return;
      }
      // If the caller is supposed to send the bye
      if (callerSendsBye && !byeTaskRunning) {
        byeTaskRunning = true;
        new Timer().schedule(new ByeTask(dialog), 4000);
      }
      System.out.println("transaction state is " + tid.getState());
      System.out.println("Dialog = " + tid.getDialog());
      System.out.println("Dialog State is " + tid.getDialog().getState());

      assertSame("Checking dialog identity", tid.getDialog(), this.dialog);

      try {
        if (response.getStatusCode() == Response.OK) {
          if (cseq.getMethod().equals(Request.INVITE)) {
            System.out.println("Dialog after 200 OK  " + dialog);
            System.out.println("Dialog State after 200 OK  " + dialog.getState());
            Request ackRequest = dialog.createAck(cseq.getSeqNumber());
            System.out.println("Sending ACK");
            dialog.sendAck(ackRequest);

            // JvB: test REFER, reported bug in tag handling
            //                      Request referRequest = dialog.createRequest("REFER");
            //                      //simulating a balancer that will forward the request to the
            // recovery node
            //                      SipURI referRequestURI = addressFactory.createSipURI(null,
            // "127.0.0.1:5080");
            //                      referRequest.setRequestURI(referRequestURI);
            //                      dialog.sendRequest(
            // sipProvider.getNewClientTransaction(referRequest));
            //
          } else if (cseq.getMethod().equals(Request.CANCEL)) {
            if (dialog.getState() == DialogState.CONFIRMED) {
              // oops cancel went in too late. Need to hang up the
              // dialog.
              System.out.println("Sending BYE -- cancel went in too late !!");
              Request byeRequest = dialog.createRequest(Request.BYE);
              ClientTransaction ct = sipProvider.getNewClientTransaction(byeRequest);
              dialog.sendRequest(ct);
            }

          } else if (cseq.getMethod().equals(Request.BYE)) {
            okToByeReceived = true;
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(0);
      }
    }
  /*
   * (non-Javadoc)
   *
   * @see gov.nist.javax.sip.clientauthutils.AuthenticationHelper#handleChallenge(javax.sip.message.Response,
   *      javax.sip.ClientTransaction, javax.sip.SipProvider)
   */
  public ClientTransaction handleChallenge(
      Response challenge,
      ClientTransaction challengedTransaction,
      SipProvider transactionCreator,
      int cacheTime)
      throws SipException, NullPointerException {
    try {
      if (sipStack.isLoggingEnabled()) {
        sipStack.getStackLogger().logDebug("handleChallenge: " + challenge);
      }

      SIPRequest challengedRequest = ((SIPRequest) challengedTransaction.getRequest());

      Request reoriginatedRequest = null;
      /*
       * If the challenged request is part of a Dialog and the
       * Dialog is confirmed the re-originated request should be
       * generated as an in-Dialog request.
       */
      if (challengedRequest.getToTag() != null
          || challengedTransaction.getDialog() == null
          || challengedTransaction.getDialog().getState() != DialogState.CONFIRMED) {
        reoriginatedRequest = (Request) challengedRequest.clone();
      } else {
        /*
         * Re-originate the request by consulting the dialog. In particular
         * the route set could change between the original request and the
         * in-dialog challenge.
         */
        reoriginatedRequest =
            challengedTransaction.getDialog().createRequest(challengedRequest.getMethod());
        Iterator<String> headerNames = challengedRequest.getHeaderNames();
        while (headerNames.hasNext()) {
          String headerName = headerNames.next();
          if (reoriginatedRequest.getHeader(headerName) != null) {
            ListIterator<Header> iterator = reoriginatedRequest.getHeaders(headerName);
            while (iterator.hasNext()) {
              reoriginatedRequest.addHeader(iterator.next());
            }
          }
        }
      }

      // remove the branch id so that we could use the request in a new
      // transaction
      removeBranchID(reoriginatedRequest);

      if (challenge == null || reoriginatedRequest == null) {
        throw new NullPointerException("A null argument was passed to handle challenge.");
      }

      ListIterator authHeaders = null;

      if (challenge.getStatusCode() == Response.UNAUTHORIZED) {
        authHeaders = challenge.getHeaders(WWWAuthenticateHeader.NAME);
      } else if (challenge.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED) {
        authHeaders = challenge.getHeaders(ProxyAuthenticateHeader.NAME);
      } else {
        throw new IllegalArgumentException("Unexpected status code ");
      }

      if (authHeaders == null) {
        throw new IllegalArgumentException(
            "Could not find WWWAuthenticate or ProxyAuthenticate headers");
      }

      // Remove all authorization headers from the request (we'll re-add them
      // from cache)
      reoriginatedRequest.removeHeader(AuthorizationHeader.NAME);
      reoriginatedRequest.removeHeader(ProxyAuthorizationHeader.NAME);

      // rfc 3261 says that the cseq header should be augmented for the new
      // request. do it here so that the new dialog (created together with
      // the new client transaction) takes it into account.
      // Bug report - Fredrik Wickstrom
      CSeqHeader cSeq = (CSeqHeader) reoriginatedRequest.getHeader((CSeqHeader.NAME));
      try {
        cSeq.setSeqNumber(cSeq.getSeqNumber() + 1l);
      } catch (InvalidArgumentException ex) {
        throw new SipException("Invalid CSeq -- could not increment : " + cSeq.getSeqNumber());
      }

      /* Resolve this to the next hop based on the previous lookup. If we are not using
       * lose routing (RFC2543) then just attach hop as a maddr param.
       */
      if (challengedRequest.getRouteHeaders() == null) {
        Hop hop = ((SIPClientTransaction) challengedTransaction).getNextHop();
        SipURI sipUri = (SipURI) reoriginatedRequest.getRequestURI();
        sipUri.setMAddrParam(hop.getHost());
        if (hop.getPort() != -1) sipUri.setPort(hop.getPort());
      }
      ClientTransaction retryTran = transactionCreator.getNewClientTransaction(reoriginatedRequest);

      WWWAuthenticateHeader authHeader = null;
      SipURI requestUri = (SipURI) challengedTransaction.getRequest().getRequestURI();
      while (authHeaders.hasNext()) {
        authHeader = (WWWAuthenticateHeader) authHeaders.next();
        String realm = authHeader.getRealm();
        AuthorizationHeader authorization = null;
        String sipDomain;
        if (this.accountManager instanceof SecureAccountManager) {
          UserCredentialHash credHash =
              ((SecureAccountManager) this.accountManager)
                  .getCredentialHash(challengedTransaction, realm);
          URI uri = reoriginatedRequest.getRequestURI();
          sipDomain = credHash.getSipDomain();
          authorization =
              this.getAuthorization(
                  reoriginatedRequest.getMethod(),
                  uri.toString(),
                  (reoriginatedRequest.getContent() == null)
                      ? ""
                      : new String(reoriginatedRequest.getRawContent()),
                  authHeader,
                  credHash);
        } else {
          UserCredentials userCreds =
              ((AccountManager) this.accountManager).getCredentials(challengedTransaction, realm);
          sipDomain = userCreds.getSipDomain();
          if (userCreds == null)
            throw new SipException("Cannot find user creds for the given user name and realm");

          // we haven't yet authenticated this realm since we were
          // started.

          authorization =
              this.getAuthorization(
                  reoriginatedRequest.getMethod(),
                  reoriginatedRequest.getRequestURI().toString(),
                  (reoriginatedRequest.getContent() == null)
                      ? ""
                      : new String(reoriginatedRequest.getRawContent()),
                  authHeader,
                  userCreds);
        }
        sipStack
            .getStackLogger()
            .logDebug("Created authorization header: " + authorization.toString());

        if (cacheTime != 0)
          cachedCredentials.cacheAuthorizationHeader(sipDomain, authorization, cacheTime);

        reoriginatedRequest.addHeader(authorization);
      }

      if (sipStack.isLoggingEnabled()) {
        sipStack.getStackLogger().logDebug("Returning authorization transaction." + retryTran);
      }
      return retryTran;
    } catch (SipException ex) {
      throw ex;
    } catch (Exception ex) {
      sipStack.getStackLogger().logError("Unexpected exception ", ex);
      throw new SipException("Unexpected exception ", ex);
    }
  }
Ejemplo n.º 10
0
  /**
   * Implements {@link MethodProcessor#processResponse(ResponseEvent)}. Handles only responses to
   * SUBSCRIBE requests because they are the only requests concerning event package subscribers (and
   * the only requests sent by them, for that matter) and if the processing of a given response
   * requires event package-specific handling, delivers the response to the matching
   * <tt>Subscription</tt> instance. Examples of such event package-specific handling include
   * letting the respective <tt>Subscription</tt> handle the success or failure in the establishment
   * of a subscription.
   *
   * @param responseEvent a <tt>ResponseEvent</tt> specifying the SIP <tt>Response</tt> to be
   *     processed
   * @return <tt>true</tt> if the SIP <tt>Response</tt> specified by <tt>responseEvent</tt> was
   *     processed; otherwise, <tt>false</tt>
   */
  @Override
  public boolean processResponse(ResponseEvent responseEvent) {
    Response response = responseEvent.getResponse();

    CSeqHeader cseqHeader = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
    if (cseqHeader == null) {
      logger.error("An incoming response did not contain a CSeq header");
      return false;
    }
    if (!Request.SUBSCRIBE.equals(cseqHeader.getMethod())) return false;

    ClientTransaction clientTransaction = responseEvent.getClientTransaction();
    Request request = clientTransaction.getRequest();

    /*
     * Don't handle responses to requests not coming from this event
     * package.
     */
    if (request != null) {
      EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME);
      if ((eventHeader == null) || !eventPackage.equalsIgnoreCase(eventHeader.getEventType()))
        return false;
    }

    // Find the subscription.
    CallIdHeader callIdHeader = (CallIdHeader) response.getHeader(CallIdHeader.NAME);
    String callId = callIdHeader.getCallId();
    Subscription subscription = getSubscription(callId);

    // if it's the response to an unsubscribe message, we just ignore it
    // whatever the response is however if we need to handle a
    // challenge, we do it
    ExpiresHeader expHeader = response.getExpires();
    int statusCode = response.getStatusCode();
    SipProvider sourceProvider = (SipProvider) responseEvent.getSource();
    if (((expHeader != null) && (expHeader.getExpires() == 0))
        || (subscription == null)) // this handle the unsubscription
    // case where we removed the contact
    // from subscribedContacts
    {
      boolean processed = false;

      if ((statusCode == Response.UNAUTHORIZED)
          || (statusCode == Response.PROXY_AUTHENTICATION_REQUIRED)) {
        try {
          processAuthenticationChallenge(clientTransaction, response, sourceProvider);
          processed = true;
        } catch (OperationFailedException e) {
          logger.error("can't handle the challenge", e);
        }
      } else if ((statusCode != Response.OK) && (statusCode != Response.ACCEPTED)) processed = true;

      // any other cases (200/202) will imply a NOTIFY, so we will
      // handle the end of a subscription there
      return processed;
    }

    if ((statusCode >= Response.OK) && (statusCode < Response.MULTIPLE_CHOICES)) {
      // OK (200/202)
      if ((statusCode == Response.OK) || (statusCode == Response.ACCEPTED)) {
        if (expHeader == null) {
          // not conform to rfc3265
          logger.error("no Expires header in this response");
          return false;
        }

        SubscriptionRefreshTask refreshTask = new SubscriptionRefreshTask(subscription);
        subscription.setTimerTask(refreshTask);

        int refreshDelay = expHeader.getExpires();
        // try to keep a margin if the refresh delay allows it
        if (refreshDelay >= (2 * refreshMargin)) refreshDelay -= refreshMargin;
        timer.schedule(refreshTask, refreshDelay * 1000);

        // do it to remember the dialog in case of a polling
        // subscription (which means no call to finalizeSubscription)
        subscription.setDialog(clientTransaction.getDialog());

        subscription.processSuccessResponse(responseEvent, statusCode);
      }
    } else if ((statusCode >= Response.MULTIPLE_CHOICES) && (statusCode < Response.BAD_REQUEST)) {
      if (logger.isInfoEnabled())
        logger.info(
            "Response to subscribe to "
                + subscription.getAddress()
                + ": "
                + response.getReasonPhrase());
    } else if (statusCode >= Response.BAD_REQUEST) {
      // if the response is a 423 response, just re-send the request
      // with a valid expires value
      if (statusCode == Response.INTERVAL_TOO_BRIEF) {
        MinExpiresHeader min = (MinExpiresHeader) response.getHeader(MinExpiresHeader.NAME);

        if (min == null) {
          logger.error("no minimal expires value in this 423 " + "response");
          return false;
        }

        ExpiresHeader exp = request.getExpires();

        try {
          exp.setExpires(min.getExpires());
        } catch (InvalidArgumentException e) {
          logger.error("can't set the new expires value", e);
          return false;
        }

        ClientTransaction transac = null;
        try {
          transac = protocolProvider.getDefaultJainSipProvider().getNewClientTransaction(request);
        } catch (TransactionUnavailableException e) {
          logger.error("can't create the client transaction", e);
          return false;
        }

        try {
          transac.sendRequest();
        } catch (SipException e) {
          logger.error("can't send the new request", e);
          return false;
        }

        return true;
        // UNAUTHORIZED (401/407)
      } else if ((statusCode == Response.UNAUTHORIZED)
          || (statusCode == Response.PROXY_AUTHENTICATION_REQUIRED)) {
        try {
          processAuthenticationChallenge(clientTransaction, response, sourceProvider);
        } catch (OperationFailedException e) {
          logger.error("can't handle the challenge", e);

          removeSubscription(callId, subscription);
          subscription.processFailureResponse(responseEvent, statusCode);
        }
        // 408 480 486 600 603 : non definitive reject
        // others: definitive reject (or not implemented)
      } else {
        if (logger.isDebugEnabled()) logger.debug("error received from the network:\n" + response);

        removeSubscription(callId, subscription);
        subscription.processFailureResponse(responseEvent, statusCode);
      }
    }

    return true;
  }